VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "mscomctl.ocx"
Begin VB.UserControl EAS_Client 
   ClientHeight    =   13350
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   18240
   ScaleHeight     =   13350
   ScaleWidth      =   18240
   Begin VB.Frame fra_SAP_Detail 
      Height          =   3435
      Left            =   600
      TabIndex        =   27
      Top             =   4425
      Visible         =   0   'False
      Width           =   6585
      Begin VB.CommandButton cmd_CloseSAPDetail 
         Height          =   700
         Left            =   5700
         Style           =   1  'Graphical
         TabIndex        =   29
         Tag             =   "cmd_CloseRecentPDF"
         Top             =   165
         Width           =   800
      End
      Begin Project1.ArmGrid grd_SAP_Detail 
         Height          =   2415
         Left            =   90
         TabIndex        =   28
         Tag             =   "grd_SAP_Detail"
         Top             =   915
         Width           =   6420
         _ExtentX        =   11324
         _ExtentY        =   4260
      End
   End
   Begin VB.Frame fra_RecentPDF 
      Height          =   5490
      Left            =   7560
      TabIndex        =   13
      Top             =   2910
      Visible         =   0   'False
      Width           =   7320
      Begin VB.Frame fra_RecentPDFView 
         Height          =   4545
         Left            =   30
         TabIndex        =   17
         Top             =   900
         Width           =   7260
      End
      Begin VB.CommandButton cmd_CloseRecentPDF 
         Height          =   700
         Left            =   6405
         Style           =   1  'Graphical
         TabIndex        =   16
         Tag             =   "cmd_CloseRecentPDF"
         Top             =   195
         Width           =   800
      End
      Begin VB.CommandButton cmd_AddRecentPdf 
         Height          =   700
         Left            =   120
         Style           =   1  'Graphical
         TabIndex        =   15
         Tag             =   "cmd_AddRecentPdf"
         Top             =   180
         Width           =   800
      End
      Begin VB.TextBox txt_RecentNumber 
         Alignment       =   2  'Center
         BackColor       =   &H8000000F&
         Height          =   345
         Left            =   2610
         Locked          =   -1  'True
         TabIndex        =   14
         Top             =   255
         Width           =   2055
      End
   End
   Begin VB.Frame fra_PDF_Directory 
      Height          =   2670
      Left            =   0
      TabIndex        =   24
      Top             =   0
      Width           =   4425
      Begin Project1.ArmCombobox cbo_DriveList 
         Height          =   345
         Left            =   90
         TabIndex        =   36
         Top             =   135
         Width           =   4215
         _ExtentX        =   7435
         _ExtentY        =   609
      End
      Begin VB.DirListBox lst_DirectoryList 
         Height          =   2115
         Left            =   75
         TabIndex        =   25
         Top             =   510
         Width           =   4230
      End
   End
   Begin VB.Frame fra_Detail 
      Height          =   1935
      Left            =   45
      TabIndex        =   22
      Top             =   8475
      Width           =   10515
      Begin VB.CommandButton cmd_CheckDocumentNumber 
         Caption         =   "R"
         BeginProperty Font 
            Name            =   "Wingdings 2"
            Size            =   14.25
            Charset         =   2
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   360
         Left            =   7290
         TabIndex        =   2
         Top             =   195
         Width           =   360
      End
      Begin VB.TextBox txt_DocumentNumber 
         Height          =   360
         Left            =   5190
         MaxLength       =   10
         TabIndex        =   1
         Top             =   195
         Width           =   2085
      End
      Begin VB.TextBox txt_PageNumber 
         Height          =   360
         Left            =   8925
         TabIndex        =   3
         Top             =   195
         Width           =   615
      End
      Begin VB.CommandButton cmd_CheckCustomer 
         Caption         =   "R"
         BeginProperty Font 
            Name            =   "Wingdings 2"
            Size            =   14.25
            Charset         =   2
            Weight          =   400
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   360
         Left            =   3690
         TabIndex        =   6
         Top             =   622
         Width           =   360
      End
      Begin VB.CommandButton cmd_Validate 
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   238
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   700
         Left            =   9645
         Style           =   1  'Graphical
         TabIndex        =   11
         Tag             =   "cmd_Validate"
         Top             =   225
         Width           =   800
      End
      Begin VB.TextBox txt_CustomerNumber 
         Height          =   375
         Left            =   1470
         MaxLength       =   10
         TabIndex        =   4
         Top             =   615
         Width           =   1890
      End
      Begin VB.TextBox txt_CustomerName 
         BackColor       =   &H8000000F&
         Height          =   345
         Left            =   4125
         Locked          =   -1  'True
         TabIndex        =   7
         TabStop         =   0   'False
         Top             =   630
         Width           =   5415
      End
      Begin VB.CommandButton cmd_SearchCustomer 
         Caption         =   "..."
         Height          =   360
         Left            =   3345
         TabIndex        =   5
         Tag             =   "cmd_SearchCustomer"
         Top             =   622
         Width           =   360
      End
      Begin Project1.ArmCombobox cbo_InvoiceType 
         Height          =   345
         Left            =   1470
         TabIndex        =   8
         Top             =   1065
         Width           =   2250
         _ExtentX        =   3969
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_CostCentre 
         Height          =   345
         Left            =   5205
         TabIndex        =   9
         Top             =   1020
         Width           =   2730
         _ExtentX        =   4815
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_CountryOfOrigin 
         Height          =   345
         Left            =   1470
         TabIndex        =   10
         Top             =   1470
         Width           =   2250
         _ExtentX        =   3969
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_DocumentType 
         Height          =   345
         Left            =   1470
         TabIndex        =   0
         Top             =   203
         Width           =   1920
         _ExtentX        =   3387
         _ExtentY        =   609
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Page nr."
         Height          =   225
         Index           =   3
         Left            =   7785
         TabIndex        =   35
         Tag             =   "lbl_PageNr"
         Top             =   270
         Width           =   1050
      End
      Begin VB.Label lbl_DocumentNumber 
         Caption         =   "#Document number"
         Height          =   225
         Left            =   3495
         TabIndex        =   34
         Tag             =   "lbl_DocumentNumber"
         Top             =   263
         Width           =   1620
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Document type"
         Height          =   225
         Index           =   0
         Left            =   75
         TabIndex        =   33
         Tag             =   "lbl_DocumentType"
         Top             =   263
         Width           =   1380
      End
      Begin VB.Label lbl_CountryOfOrigin 
         Caption         =   "#Country of origin"
         Height          =   225
         Left            =   75
         TabIndex        =   32
         Tag             =   "lbl_CountryOfOrigin"
         Top             =   1515
         Width           =   1380
      End
      Begin VB.Label lbl_CostCentre 
         Caption         =   "#Cost centre"
         Height          =   225
         Left            =   3780
         TabIndex        =   31
         Tag             =   "lbl_CostCentre"
         Top             =   1095
         Width           =   1380
      End
      Begin VB.Label lbl_InvoiceType 
         Caption         =   "#Invoice type"
         Height          =   225
         Left            =   75
         TabIndex        =   30
         Tag             =   "lbl_InvoiceType"
         Top             =   1125
         Width           =   1320
      End
      Begin VB.Label lbl_Customer 
         Caption         =   "#Customer"
         Height          =   225
         Left            =   75
         TabIndex        =   23
         Tag             =   "lbl_Customer"
         Top             =   690
         Width           =   1350
      End
   End
   Begin VB.Frame fra_PDFControl 
      Height          =   915
      Left            =   4485
      TabIndex        =   19
      Top             =   0
      Width           =   10650
      Begin VB.CommandButton cmd_Quit 
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   238
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   700
         Left            =   9675
         Style           =   1  'Graphical
         TabIndex        =   37
         Tag             =   "cmd_Validate"
         Top             =   150
         Width           =   800
      End
      Begin VB.CommandButton cmd_ZoomPlus 
         Caption         =   "#Zoom +"
         Height          =   495
         Left            =   120
         TabIndex        =   21
         Tag             =   "cmd_ZoomPlus"
         Top             =   270
         Width           =   975
      End
      Begin VB.CommandButton cmd_ZoomMinus 
         Caption         =   "#Zoom -"
         Height          =   495
         Left            =   1155
         TabIndex        =   20
         Tag             =   "cmd_ZoomMinus"
         Top             =   270
         Width           =   975
      End
   End
   Begin VB.Frame fra_PDFView 
      Height          =   7590
      Left            =   4485
      TabIndex        =   18
      Top             =   915
      Width           =   10530
   End
   Begin MSComctlLib.ListView lvw_RecentDocument 
      Height          =   1905
      Left            =   10575
      TabIndex        =   12
      Tag             =   "lvw_RecentDocument"
      Top             =   8595
      Width           =   4485
      _ExtentX        =   7911
      _ExtentY        =   3360
      View            =   3
      LabelEdit       =   1
      LabelWrap       =   -1  'True
      HideSelection   =   0   'False
      FullRowSelect   =   -1  'True
      _Version        =   393217
      ForeColor       =   -2147483640
      BackColor       =   -2147483643
      Appearance      =   1
      NumItems        =   0
   End
   Begin MSComctlLib.ListView lvw_PDF_Files 
      Height          =   5760
      Left            =   15
      TabIndex        =   26
      Tag             =   "lvw_PDF_Files"
      Top             =   2685
      Width           =   4365
      _ExtentX        =   7699
      _ExtentY        =   10160
      View            =   3
      LabelEdit       =   1
      LabelWrap       =   -1  'True
      HideSelection   =   0   'False
      AllowReorder    =   -1  'True
      FullRowSelect   =   -1  'True
      _Version        =   393217
      ForeColor       =   -2147483640
      BackColor       =   -2147483643
      BorderStyle     =   1
      Appearance      =   1
      NumItems        =   1
      BeginProperty ColumnHeader(1) {BDD1F052-858B-11D1-B16A-00C0F0283628} 
         Text            =   "Name"
         Object.Width           =   5292
      EndProperty
   End
End
Attribute VB_Name = "EAS_Client"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

#If ENV = LIVE Then
    Dim mo_Db As Object
#Else
    Dim mo_Db As ARMSYSCOMLib.ArmDb
#End If

#If ENV = LIVE Then
    Dim mo_Sys As Object
#Else
    Dim mo_Sys As ARMSYSCOMLib.ArmSYS
#End If

#If ENV = LIVE Then
    Dim mo_FSO As Object
#Else
    Dim mo_FSO As Scripting.FileSystemObject
#End If

Private ms_Language_Code                As String       'current user interface language
Private ml_U_code                       As Long         'U_Code (GEN_Systems_Users) of logged user
Private ms_LoginName                    As String       'contain loginname
Private mb_InternalInit                 As Boolean      'framework is doing some own control manipulation, all events should handle
Private mb_Initialized                  As Boolean      'framework is doing some own control manipulation, all events should handle
Private ms_DecimalSeparator             As String       'locale decimal separator
Private ms_ThousandSeparator            As String       'locale thousand separator
Private mc_ScreenLabels                 As Long         'cursor containing screen constants for current component

Private Type SAPDocument
    DocumentType As eDocumentType
    DocumentStatus As eZipDocumentStatus
    ID As Long
    PageId As Long
    Number As String
    PageNr As Long
    FileNameOriginal As String
    FileNameServer As String
    CCU_CapKey As String
    CUST_Code As String
    CT_Code As String
    COC_Code As Long
    INV_Code As Long
    
End Type

Private Type SAPCustomerDetail
    CustomerNumber As String
    Name As String
    City As String
    Street As String
    PostalCode As String
    Phone As String
    Fax As String
    CT_Code As String
End Type

Private Type SAPDocumentDetail
    DocumentNumber As String
    DocumentType As String
    DocumentDate As String
    CustomerNumber As String
    CreationDate As String
    CreationTime As String
    DocumentCategory As String
End Type

Private Enum eDocumentType
    dtNone = 0
    dtSalesOrder = 1
    dtPriceRequest = 2
    dtCreditMemo = 3
    dtDebitMemo = 4
    dtReturn = 5
    dtOfficeInvoice = 6
    dtAdminCustomer = 7
End Enum

Private Enum eZipDocumentStatus
    None = 0
    Waiting = 1
    Uploaded = 2
End Enum

#If ENV = LIVE Then
Dim mo_Pdf As Object
Dim mo_RecentPdf As Object
#Else
Dim mo_Pdf As AcroPDFLibCtl.AcroPDF
Dim mo_RecentPdf As AcroPDFLibCtl.AcroPDF
#End If

Dim md_PdfZoomPercent As Single
Dim ms_DocumentServerDir As String
Dim ms_DocumentScanDir As String
Dim ml_MaxZipRecordCount As Long
Dim ms_MsgInfo As Variant
Dim ms_NetworkBoardID As String
Dim ms_ComputerName As String
Dim ml_ZipTableIndex() As Long
Dim mo_WshNetwork As Object
Dim msa_MapNetworkDrive() As String
Dim ms_NetworkPath As String
Dim ms_NetworkDrive As String
Dim ms_NetworkUser As String
Dim ms_NetworkPassword As String
Dim mb_AppCreatedMappedDrive As Boolean
Dim mt_LastSAPDocumentDetail As SAPDocumentDetail
Dim mt_LastSAPCustomerDetail As SAPCustomerDetail
Dim ms_UrlCustomerDetail As String
Dim ms_UrlSalesOrder As String
Dim ms_ZoomViewPdf As String

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

Private Const SCREEN_NAME As String = "EAS_Client"
Private Const LOCALE_USER_DEFAULT = &H400
Private Const ICON_RELOAD = 115

Private Const SW_SHOWNORMAL = 1

Private Const LOCALE_SDECIMAL = &HE ' Decimal separator
Private Const LOCALE_STHOUSAND = &HF ' Thousand separator
Private Const CL_COLOR_ENABLED As Long = &H80000005
Private Const CL_COLOR_DISABLED As Long = &H8000000F
Private Const CL_COLOR_LOCKED As Long = &H80000018
Private Const C_ERRORRAISE As Long = 2500
Private Const C_MSG_ID_BASE As Long = 9300

Private Const FRM_SPACE_VER = 120
Private Const FRM_SPACE_HOR = 100

'Private Const C_CUSTOMER_DETAIL_URL As String = "http://10.68.16.36/EASWebService/Service1.asmx/Customer_GetDetail"
'Private Const C_SALES_ORDER_URL As String = "http://10.68.16.36/EASWebService/Service1.asmx/SalesOrder_GetDetail"
Private Const C_SERVICE_USER As String = "NXT"
Private Const C_SERVICE_PASSW As String = "ous42pri"
Private Const C_DOCUMENT_TYPE_GR_CODE As Long = 70
Private Const C_ERROR_FILES_DIR As String = "Bad_Files"

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

Private Enum ArmCusErr
    DuplicityDetected = C_ERRORRAISE + 2301                ' detected row with same unique id
End Enum

Public Event quit()

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

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

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

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

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

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

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

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

Property Let LoginName(as_Login As String)
ms_LoginName = as_Login
End Property

Property Let U_Code(al_Code As Long)
ml_U_code = al_Code
End Property

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

Public Property Set ArmDb(ByRef local_connection As Object)
    If Not (local_connection Is Nothing) Then
        Set mo_Db = local_connection
    End If
End Property

Public Function Load_A_Com() As Boolean
On Error GoTo ErrHandler

Dim ll_Index As Long
Dim lo_Control As Object
    
    Load_A_Com = False
    
    If mb_Initialized Then
        Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    End If
    
    mb_InternalInit = False
    ms_DecimalSeparator = Format(0, ".")
    mc_ScreenLabels = 0
    Dim sBuffer As String
    Dim nBufferLen As Long
    nBufferLen = 255
    sBuffer = String$(nBufferLen, vbNullChar)
    nBufferLen = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, sBuffer, nBufferLen)
    If nBufferLen > 0 Then
        ms_ThousandSeparator = Left$(sBuffer, nBufferLen - 1)
    End If
    
    For Each lo_Control In UserControl.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
            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
        End Select
    Next
    
    ml_MaxZipRecordCount = Trim(GetAConfigData(mo_Db, "EAS_MaxZipRecordCount"))
    ms_DocumentScanDir = Trim(GetAConfigDataByCountry(mo_Db, "EAS_DocumentScanDir"))
    
    Dim ls_EAS_ClientRight As String
    ls_EAS_ClientRight = Trim(GetAConfigData(mo_Db, "EAS_ClientRight"))
    If InStr(1, SEP & ls_EAS_ClientRight & SEP, SEP & ml_U_code & SEP) <= 0 Then
        Load_A_Com = False
        Exit Function
    End If
    
    Dim ls_MapNetworkDrive As String
    ls_MapNetworkDrive = GetAConfigDataByCountry(mo_Db, "EAS_MapNetworkDrive")
    
    If (ms_DocumentScanDir = "") Or (ls_MapNetworkDrive = "") Then
        Load_A_Com = False
        Exit Function
    End If
    
    msa_MapNetworkDrive = Split(ls_MapNetworkDrive, SEP)
    
    
    ReDim ml_ZipTableIndex(eDocumentType.dtAdminCustomer)
    For ll_Index = 0 To eDocumentType.dtAdminCustomer
        ml_ZipTableIndex(ll_Index) = 0
    Next
    md_PdfZoomPercent = 100
    
    Set mo_FSO = CreateObject("Scripting.FileSystemObject")
#If ENV = LIVE Then
    Set mo_Sys = CreateObject("ArmSYSCOM.ArmSys")
#Else
    Set mo_Sys = New ARMSYSCOMLib.ArmSYS
#End If
    
    Set mo_WshNetwork = CreateObject("WScript.Network")
    
    
    
    ms_NetworkPath = msa_MapNetworkDrive(0)
    ms_NetworkUser = msa_MapNetworkDrive(1)
    ms_NetworkPassword = msa_MapNetworkDrive(2)
    ms_NetworkDrive = msa_MapNetworkDrive(3)
    mb_AppCreatedMappedDrive = False
    
    If Trim(ms_NetworkDrive) = "" Then
        ' in this case we upload using direct network path
        ms_DocumentServerDir = ms_NetworkPath
    Else
        ms_DocumentServerDir = ms_NetworkDrive & "\"
        ' check if C_MAPPED_DRIVE is mapped
        If Not NetworkDriveExists(mo_WshNetwork, ms_NetworkDrive) Then
            mb_AppCreatedMappedDrive = MapNetworkDrive(mo_WshNetwork, ms_NetworkDrive, msa_MapNetworkDrive(0), msa_MapNetworkDrive(1), msa_MapNetworkDrive(2))
        End If
    End If
    
    
    ms_ComputerName = mo_WshNetwork.ComputerName
    ms_NetworkBoardID = GetMACAddress()
    
    If (ms_DocumentServerDir <> "") And right(ms_DocumentServerDir, 1) <> "\" Then ms_DocumentServerDir = ms_DocumentServerDir & "\"
    If (ms_DocumentScanDir <> "") And right(ms_DocumentScanDir, 1) <> "\" Then ms_DocumentScanDir = ms_DocumentScanDir & "\"
    
    If Not mo_FSO.FolderExists(ms_DocumentServerDir) Then
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$PATH$"
        ms_MsgInfo(0, 1) = ms_DocumentServerDir
        Call MsgBox(MsgText(C_MSG_ID_BASE + 0, ms_Language_Code, "Server directory does not exists: $PATH$", ms_MsgInfo))
        Load_A_Com = False
        Exit Function
    End If
    ' test if curently mapped drive points to service dir on the other side
    If Not mo_FSO.FolderExists(ms_DocumentServerDir & C_ERROR_FILES_DIR) Then
        ' drive is not propably pointing ok
        Call MsgBox(MsgText(666, ms_Language_Code, "Existing mapped drive is propably not configured correctly!. Upload for Hires pictures may not work."))
    End If
    
    ms_UrlCustomerDetail = GetAConfigData(mo_Db, "EAS_UrlCustomer")
    If (ms_UrlCustomerDetail = "") Then
        Err.Raise ArmErr.CPTNotInitialized, "EAS_UrlCustomer", "A_Config value 'EAS_UrlCustomer' not initialized"
    End If
    
    ms_UrlSalesOrder = GetAConfigData(mo_Db, "EAS_UrlSalesOrder")
    If (ms_UrlSalesOrder = "") Then
        Err.Raise ArmErr.CPTNotInitialized, "EAS_UrlSalesOrder", "A_Config value 'EAS_UrlSalesOrder' not initialized"
    End If
    
    ms_ZoomViewPdf = GetAConfigData(mo_Db, "EAS_ZoomView")
    
    Call InitComponents
    Call InitDirectory(ms_DocumentScanDir)
    Call ReadFileList(ms_DocumentScanDir)
    Call DeleteTemporaryFiles
    mb_Initialized = True
    Load_A_Com = True
    Exit Function
ErrHandler:
    Load_A_Com = False
    Call ErrorMessage("Load_A_COM")
End Function

Public Function Unload_A_Com() As Boolean
On Error GoTo ErrHandler
    
    Dim lo_Control As Object
    Dim ll_Idx As Long
    
    If mc_ScreenLabels <> 0 Then mo_Db.Close (mc_ScreenLabels)
    mc_ScreenLabels = 0
   
    For Each lo_Control In UserControl.Controls
        Select Case UCase(TypeName(lo_Control))
        Case "ARMCOMBOBOX", "TOOLBARCONTROL", "ARMGRID", "ARMTREEVIEW", "ARMCHECKVIEW", "ARMPICKER"
            Call lo_Control.Unload_A_Com
        End Select
    Next
    
    If Not (mo_RecentPdf Is Nothing) Then
        Call mo_RecentPdf.LoadFile("")
        Set mo_RecentPdf = Nothing
    End If
        
    If Not (mo_Pdf Is Nothing) Then
        Call mo_Pdf.LoadFile("")
        Set mo_Pdf = Nothing
    End If
    
    Set mo_Db = Nothing
    Set mo_FSO = Nothing
    ' Unmap Drive
    If (ms_NetworkDrive <> "") And Not (mo_WshNetwork Is Nothing) And mb_AppCreatedMappedDrive Then
        Call mo_WshNetwork.RemoveNetworkDrive(ms_NetworkDrive)
    End If
    Set mo_WshNetwork = Nothing
    mb_Initialized = False
    Unload_A_Com = True
    Exit Function
ErrHandler:
    Unload_A_Com = False
    If Err.Number = -2147022495 Then
        Exit Function
    End If
    Call ErrorMessage("Unload_A_Com")
End Function

Private Sub InitDirectory(ByVal as_dir As String)
On Error GoTo ErrHandler
    
Dim ls_drive As String

    mb_InternalInit = True
    If mo_FSO.FolderExists(as_dir) Then
        If Left(as_dir, 1) = "\" Then
            ls_drive = as_dir
        Else
            ls_drive = Left(as_dir, 1) & ":"
        End If
        
        If Not cbo_DriveList.SearchItem(ls_drive) Then
            Call cbo_DriveList.AddItem(Array(ls_drive, ls_drive), True)
        End If
        lst_DirectoryList.Path = as_dir
    Else
        Call cbo_DriveList.SearchItem(Left(App.Path, 1) & ":")
        lst_DirectoryList.Path = App.Path
    End If
    mb_InternalInit = False
    Exit Sub
ErrHandler:
    mb_InternalInit = False
    Call ErrorHandler("InitDirectory")
End Sub

Private Sub InitComponents()
On Error GoTo ErrHandler
    
    Dim lo_ColumnHeader As ColumnHeader
    
    cmd_Validate.Picture = LoadResPicture(129, vbResIcon)
    cmd_AddRecentPdf.Picture = LoadResPicture(101, vbResIcon)
    cmd_CloseRecentPDF.Picture = LoadResPicture(132, vbResIcon)
    cmd_CloseSAPDetail.Picture = LoadResPicture(132, vbResIcon)
    cmd_Quit.Picture = LoadResPicture(132, vbResIcon)
    
    fra_SAP_Detail.Visible = False
    
    Set mo_Pdf = Controls.Add("AcroPDF.PDF.1", "AcroPDF1")
    Call mo_Pdf.ZOrder(1)
    Set mo_Pdf.Container = fra_PDFView
    Call mo_Pdf.Move(0, 0, fra_PDFView.Width, fra_PDFView.Height)
    mo_Pdf.Visible = True
    
    Set mo_RecentPdf = Controls.Add("AcroPDF.PDF.1", "AcroPDF2")
    Call mo_RecentPdf.ZOrder(1)
    Set mo_RecentPdf.Container = fra_RecentPDFView
    Call mo_RecentPdf.Move(0, 0, fra_RecentPDFView.Width, fra_RecentPDFView.Height)
    mo_RecentPdf.Visible = True
    
    lvw_PDF_Files.ListItems.Clear
    lvw_PDF_Files.ColumnHeaders.Clear
    Set lo_ColumnHeader = lvw_PDF_Files.ColumnHeaders.Add(, , "#Name", 2500)
    lo_ColumnHeader.Tag = "lvw_PDF_Files.Name"
    Set lo_ColumnHeader = lvw_PDF_Files.ColumnHeaders.Add(, , "#Date", 1500)
    lo_ColumnHeader.Tag = "lvw_PDF_Files.Date"
    
    lvw_RecentDocument.ListItems.Clear
    lvw_RecentDocument.ColumnHeaders.Clear
    Set lo_ColumnHeader = lvw_RecentDocument.ColumnHeaders.Add(, , "#Document nr.", 1800)
    lo_ColumnHeader.Tag = "lvw_RecentDocument.DocumentNr"
    Set lo_ColumnHeader = lvw_RecentDocument.ColumnHeaders.Add(, , "#Page nr.", 1000)
    lo_ColumnHeader.Tag = "lvw_RecentDocument.PageNr"
    Set lo_ColumnHeader = lvw_RecentDocument.ColumnHeaders.Add(, , "#Customer nr.", 2300)
    lo_ColumnHeader.Tag = "lvw_RecentDocument.CustomerNr"
    
    cbo_DocumentType.Request = ReplacePlaceHolder("exec A_References_ML_LstSafe $GR_Code$,'E'", "$GR_Code$", C_DOCUMENT_TYPE_GR_CODE)
    Call cbo_DocumentType.Load
    Call cbo_DocumentType.SearchItem(eDocumentType.dtSalesOrder)
    
    cbo_CostCentre.Request = "exec EAS_CostCentre_lst 'E'"
    cbo_InvoiceType.Request = ReplacePlaceHolder("exec EAS_InvoiceType_lst $Language_Code$", "$Language_Code$", SQLStr(ms_Language_Code))
    cbo_CountryOfOrigin.Request = ReplacePlaceHolder("exec EAS_Countries_lst $Language_Code$", "$Language_Code$", SQLStr(ms_Language_Code))
    
    grd_SAP_Detail.UnBound = True
    grd_SAP_Detail.SetColumns (Array( _
        "Name®©1500®©1®©Name®©#Name", _
        "Desc®©3500®©0®©Desc®©#Desc"))
    
    Call LoadDriveCombo(cbo_DriveList)
    Call LoadRecentDocument
    
    Call LoadLabels(mo_Db, Me, SCREEN_NAME, ms_Language_Code)
    Exit Sub
ErrHandler:
    mb_InternalInit = False
    Call ErrorHandler("InitComponents")
End Sub

Private Sub LoadDriveCombo(ByRef ao_Combo As ArmCombobox)
On Error GoTo ErrHandler

    Dim lo_Drives As Object
    Dim lo_Drive As Object
    Dim ll_Index As Long
    
    Set lo_Drives = mo_FSO.Drives
    For Each lo_Drive In lo_Drives
        Call ao_Combo.AddItem(Array(lo_Drive.DriveLetter & ":", lo_Drive.DriveLetter & ":"))
    Next
    Exit Sub
ErrHandler:
    Call ErrorMessage("LoadDriveCombo")
End Sub

Private Sub LoadRecentDocument()
On Error GoTo ErrHandler
Const RECENT_PRICEREQUEST_REQ As String = "exec EAS_PriceRequestPage_lst $U_Code$"
Const RECENT_SALESORDER_REQ As String = "exec EAS_SalesOrderPage_lst $U_Code$"
Const RECENT_CREDITMEMO_REQ As String = "exec EAS_CreditMemoPage_lst $U_Code$"
Const RECENT_DEBITMEMO_REQ As String = "exec EAS_DebitMemoPage_lst $U_Code$"
Const RECENT_RETURN_REQ As String = "exec EAS_ReturnPage_lst $U_Code$"
Const RECENT_OFFICEINVOICE_REQ As String = "exec EAS_OfficeInvoicePage_lst $U_Code$"
Const RECENT_ADMINCUSTOMER_REQ As String = "exec EAS_AdminCustomerPage_lst $U_Code$"

    Dim lc_Cursor As Long
    Dim ls_Request As String
    Dim lo_item As ListItem
    Dim lv_Fields As Variant
    Dim ls_Prefix As String
    Dim le_DocumentType As eDocumentType
    Dim ll_Idx As Long
    
    le_DocumentType = GetDocumentType
    Select Case le_DocumentType
    Case eDocumentType.dtPriceRequest
        ls_Request = RECENT_PRICEREQUEST_REQ
        lv_Fields = Array("PRP_Id", "PRQ_Id", "PRP_PageNr", "CUST_Code")
    Case eDocumentType.dtSalesOrder
        ls_Request = RECENT_SALESORDER_REQ
        lv_Fields = Array("SLP_Id", "SLO_Number", "SLP_PageNr")
    Case eDocumentType.dtCreditMemo
        ls_Request = RECENT_CREDITMEMO_REQ
        lv_Fields = Array("CRP_Id", "CRM_Number", "CRP_PageNr")
    Case eDocumentType.dtDebitMemo
        ls_Request = RECENT_DEBITMEMO_REQ
        lv_Fields = Array("DBP_Id", "DBM_Number", "DBP_PageNr")
    Case eDocumentType.dtReturn
        ls_Request = RECENT_RETURN_REQ
        lv_Fields = Array("REP_Id", "RET_Number", "REP_PageNr")
    Case eDocumentType.dtOfficeInvoice
        ls_Request = RECENT_OFFICEINVOICE_REQ
        lv_Fields = Array("OFP_Id", "OFI_Id", "OFP_PageNr")
    Case eDocumentType.dtAdminCustomer
        ls_Request = RECENT_ADMINCUSTOMER_REQ
        lv_Fields = Array("ACP_Id", "ACU_Id", "ACP_PageNr", "CUST_Code")
    Case Else
        Err.Raise ArmErr.CompFncFailed, "GetDocumentType", "Unknown document type : " & le_DocumentType
    End Select
    
    If HasCustomerInput(le_DocumentType) Then
        lvw_RecentDocument.ColumnHeaders(3).Width = 2300
    Else
        lvw_RecentDocument.ColumnHeaders(3).Width = 0
    End If
    
    ls_Prefix = GetDocumentPrefix(le_DocumentType)
    ls_Request = ReplacePlaceHolder(ls_Request, "$U_Code$", ml_U_code)
    lc_Cursor = OpenSQLSafe(mo_Db, ls_Request)
    lvw_RecentDocument.ListItems.Clear
    While Not mo_Db.EOF(lc_Cursor)
        Set lo_item = lvw_RecentDocument.ListItems.Add(, , mo_Db.GetFields(lc_Cursor, lv_Fields(1)))
        lo_item.Tag = ms_DocumentServerDir & ls_Prefix & "_" & mo_Db.GetFields(lc_Cursor, lv_Fields(0)) & "_*.PDF"
        For ll_Idx = 2 To UBound(lv_Fields)
            Call lo_item.ListSubItems.Add(, , mo_Db.GetFields(lc_Cursor, lv_Fields(ll_Idx)))
        Next
        Call mo_Db.Next(lc_Cursor)
    Wend
    Call mo_Db.Close(lc_Cursor)
    Exit Sub
ErrHandler:
    Call mo_Db.Close(lc_Cursor)
    Call ErrorHandler("LoadRecentDocument")
End Sub

Private Sub cmd_AddRecentPDF_Click()
On Error GoTo ErrHandler

    Call RecentDocument_AddInit
    fra_RecentPDF.Visible = False
    Exit Sub
ErrHandler:
    Call ErrorMessage("cmd_AddRecentPDF_Click")
End Sub

Private Sub cmd_CloseRecentPDF_Click()
On Error GoTo ErrHandler
    
    fra_RecentPDF.Visible = False
    Exit Sub
ErrHandler:
    Call ErrorMessage("cmd_CloseRecentPDF_Click")
End Sub

Private Sub cmd_Quit_Click()
    RaiseEvent quit
End Sub

Private Sub cmd_SearchCustomer_Click()
On Error GoTo ErrHandler
    
Dim ls_CCUCapKey As String
Dim lo_SeekForm As SeekForm
Dim lv_Code As Variant
Dim lv_Desc As String
    
    fra_RecentPDF.Visible = False
    fra_SAP_Detail.Visible = False
    gs_CaptureCountry = "GB"
    Set lo_SeekForm = New SeekForm
    Load lo_SeekForm
    lo_SeekForm.Language = ms_Language_Code
    Set lo_SeekForm.ArmDb = mo_Db
    lo_SeekForm.ComponentType = "CUSTOMER"
    lo_SeekForm.TreeViewFiltersDesc = ""
    lo_SeekForm.TreeViewFilters = "" & SEP & "" & SEP & "" & SEP & "NULL"
    lo_SeekForm.TreeView_DateType = "0"
    lo_SeekForm.Load_A_Com
    lo_SeekForm.SYS_code = 1
    
    Call lo_SeekForm.show(vbModal)
    
    If lo_SeekForm.SelectedData = True Then
        txt_CustomerName.Text = lo_SeekForm.SelectedItemDesc
        txt_CustomerNumber.Text = GetSeparatedStringElement(lo_SeekForm.SelectedItemFull, "CUST_Code")
    End If
    
    Call lo_SeekForm.Unload_A_Com
    Unload lo_SeekForm
    Set lo_SeekForm = Nothing
    Exit Sub
ErrHandler:
    Call ErrorMessage("cmd_SearchCustomer_Click")
End Sub

Private Sub cmd_CheckDocumentNumber_Click()
On Error GoTo ErrHandler
    
  
    fra_SAP_Detail.Visible = False
    fra_RecentPDF.Visible = False
    Call LockScreen(True)
    If (Trim(txt_DocumentNumber.Text) <> "") Then
        If GetSAPDocumentDetail(Trim(txt_DocumentNumber.Text), mt_LastSAPDocumentDetail) Then
            Call grd_SAP_Detail.ClearGrid
            grd_SAP_Detail.Rows = 6
            grd_SAP_Detail.Data(0, "Name") = GetLabel("lbl_DocNrSapGrd_DocumentType", "#Document type")
            grd_SAP_Detail.Data(0, "Desc") = mt_LastSAPDocumentDetail.DocumentType
            
            grd_SAP_Detail.Data(1, "Name") = GetLabel("lbl_DocNrSapGrd_DocumentDate", "#Document date")
            grd_SAP_Detail.Data(1, "Desc") = mt_LastSAPDocumentDetail.DocumentDate
        
            grd_SAP_Detail.Data(2, "Name") = GetLabel("lbl_DocNrSapGrd_CustomerNumber", "#Customer number")
            grd_SAP_Detail.Data(2, "Desc") = mt_LastSAPDocumentDetail.CustomerNumber
            
            grd_SAP_Detail.Data(3, "Name") = GetLabel("lbl_DocNrSapGrd_CreationDate", "#Creation date")
            grd_SAP_Detail.Data(3, "Desc") = mt_LastSAPDocumentDetail.CreationDate
            
            grd_SAP_Detail.Data(4, "Name") = GetLabel("lbl_DocNrSapGrd_CreationTime", "#Creation time")
            grd_SAP_Detail.Data(4, "Desc") = mt_LastSAPDocumentDetail.CreationTime
            
            grd_SAP_Detail.Data(5, "Name") = GetLabel("lbl_DocNrSapGrd_DocumentCat", "#Document category")
            grd_SAP_Detail.Data(5, "Desc") = mt_LastSAPDocumentDetail.DocumentCategory
            Call fra_SAP_Detail.ZOrder
            Call fra_SAP_Detail.Move(cmd_CheckDocumentNumber.Left, fra_Detail.Top + cmd_CheckDocumentNumber.Top - fra_SAP_Detail.Height)
            fra_SAP_Detail.Visible = True
        Else
            Call MsgBox(MsgText(C_MSG_ID_BASE + 1, ms_Language_Code, "#SAP document not found"))
        End If
    End If
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_CheckDocumentNumber_Click")
End Sub

Private Sub txt_DocumentNumber_LostFocus()
On Error GoTo ErrHandler
       
    fra_SAP_Detail.Visible = False
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_DocumentNumber_LostFocus")
End Sub

Private Sub cmd_CheckCustomer_Click()
On Error GoTo ErrHandler
    
    fra_SAP_Detail.Visible = False
    fra_RecentPDF.Visible = False
    Call LockScreen(True)
    If (Trim(txt_CustomerNumber.Text) <> "") Then
        If GetSAPCustomerDetail(Trim(txt_CustomerNumber.Text), mt_LastSAPCustomerDetail) Then
            Call grd_SAP_Detail.ClearGrid
            grd_SAP_Detail.Rows = 7
            grd_SAP_Detail.Data(0, "Name") = GetLabel("lbl_CustSapGrd_Name", "#Name")
            grd_SAP_Detail.Data(0, "Desc") = mt_LastSAPCustomerDetail.Name
            
            grd_SAP_Detail.Data(1, "Name") = GetLabel("lbl_CustSapGrd_Street", "#Street")
            grd_SAP_Detail.Data(1, "Desc") = mt_LastSAPCustomerDetail.Street
        
            grd_SAP_Detail.Data(2, "Name") = GetLabel("lbl_CustSapGrd_City", "#City")
            grd_SAP_Detail.Data(2, "Desc") = mt_LastSAPCustomerDetail.City
            
            grd_SAP_Detail.Data(3, "Name") = GetLabel("lbl_CustSapGrd_PostalCode", "#Postal code")
            grd_SAP_Detail.Data(3, "Desc") = mt_LastSAPCustomerDetail.PostalCode
            
            grd_SAP_Detail.Data(4, "Name") = GetLabel("lbl_CustSapGrd_Phone", "#Phone")
            grd_SAP_Detail.Data(4, "Desc") = mt_LastSAPCustomerDetail.Phone
            
            grd_SAP_Detail.Data(5, "Name") = GetLabel("lbl_CustSapGrd_Fax", "#Fax")
            grd_SAP_Detail.Data(5, "Desc") = mt_LastSAPCustomerDetail.Fax
            
            grd_SAP_Detail.Data(6, "Name") = GetLabel("lbl_CustSapGrd_CountryISO", "#Country ISO")
            grd_SAP_Detail.Data(6, "Desc") = mt_LastSAPCustomerDetail.CT_Code
            Call fra_SAP_Detail.Move(cmd_CheckCustomer.Left, fra_Detail.Top + cmd_CheckCustomer.Top - fra_SAP_Detail.Height)
            Call fra_SAP_Detail.ZOrder
            fra_SAP_Detail.Visible = True
        Else
            Call MsgBox(MsgText(C_MSG_ID_BASE + 2, ms_Language_Code, "#Customer number not found"))
        End If
    End If
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_CheckCustomer_Click")
End Sub

Private Sub txt_CustomerNumber_LostFocus()
On Error GoTo ErrHandler
       
    fra_SAP_Detail.Visible = False
    Exit Sub
ErrHandler:
    Call ErrorMessage("txt_CustomerNumber_LostFocus")
End Sub

Private Sub cmd_CloseSAPDetail_Click()
On Error GoTo ErrHandler
       
    fra_SAP_Detail.Visible = False
    Exit Sub
ErrHandler:
    Call ErrorMessage("cmd_CloseSAPDetail_Click")
End Sub

Private Sub cmd_ZoomMinus_Click()
On Error GoTo ErrHandler
    
    fra_SAP_Detail.Visible = False
    md_PdfZoomPercent = md_PdfZoomPercent - 10
    Call mo_Pdf.setZoom(md_PdfZoomPercent)
    Exit Sub
ErrHandler:
    Call ErrorMessage("cmd_ZoomMinus_Click")
End Sub

Private Sub cmd_ZoomPlus_Click()
On Error GoTo ErrHandler
    
    fra_SAP_Detail.Visible = False
    md_PdfZoomPercent = md_PdfZoomPercent + 10
    Call mo_Pdf.setZoom(md_PdfZoomPercent)
    Exit Sub
ErrHandler:
    Call ErrorMessage("cmd_ZoomPlus_Click")
End Sub

Private Sub RecentDocument_AddInit()
On Error GoTo ErrHandler

    Dim le_DocumentType As eDocumentType
    
    le_DocumentType = GetDocumentType()
    txt_DocumentNumber.Text = lvw_RecentDocument.SelectedItem.Text
    txt_PageNumber.Text = Val(lvw_RecentDocument.SelectedItem.ListSubItems(1).Text) + 1
    If HasCustomerInput(le_DocumentType) Then
        txt_CustomerNumber.Text = lvw_RecentDocument.SelectedItem.ListSubItems(2).Text
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("RecentDocument_AddInit")
End Sub

Private Sub cbo_DocumentType_ComboItemSelected()
On Error GoTo ErrHandler
    
    Dim le_DocumentType As eDocumentType
    Dim lb_HasCustomerInput As Boolean
    Dim lb_HasInvoiceInput As Boolean
    Dim lb_HasSAPNumberInput As Boolean
    
    le_DocumentType = GetDocumentType()
    
    fra_RecentPDF.Visible = False
    fra_SAP_Detail.Visible = False
    
    lb_HasSAPNumberInput = HasSAPNumberInput(le_DocumentType)
    txt_DocumentNumber.Locked = Not lb_HasSAPNumberInput
    txt_DocumentNumber.BackColor = IIf(lb_HasSAPNumberInput, vbWindowBackground, vbButtonFace)
    cmd_CheckDocumentNumber.Visible = lb_HasSAPNumberInput
    
    lb_HasCustomerInput = HasCustomerInput(le_DocumentType)
    lbl_Customer.Visible = lb_HasCustomerInput
    txt_CustomerNumber.Visible = lb_HasCustomerInput
    txt_CustomerName.Visible = lb_HasCustomerInput
    cmd_SearchCustomer.Visible = lb_HasCustomerInput
    cmd_CheckCustomer.Visible = lb_HasCustomerInput
    
    lb_HasInvoiceInput = HasInvoiceInput(le_DocumentType)
    lbl_InvoiceType.Visible = lb_HasInvoiceInput
    cbo_InvoiceType.Visible = lb_HasInvoiceInput
    lbl_CountryOfOrigin.Visible = lb_HasInvoiceInput
    cbo_CountryOfOrigin.Visible = lb_HasInvoiceInput
    lbl_CostCentre.Visible = lb_HasInvoiceInput
    cbo_CostCentre.Visible = lb_HasInvoiceInput
    
    Call LoadRecentDocument
    Call Document_Clear
    Exit Sub
ErrHandler:
    Call ErrorMessage("cbo_DocumentType_ComboItemSelected")
End Sub

Private Function GetSeparatedStringElement(ByVal as_SeparatedString As String, ByVal as_Name As String) As String
On Error GoTo ErrHandler
    
    Dim lsa_Array() As String
    Dim ll_Idx As Long
    
    GetSeparatedStringElement = ""
    lsa_Array = Split(as_SeparatedString, SEP)
    ll_Idx = 0
    While ll_Idx < UBound(lsa_Array)
        If StrComp(as_Name, lsa_Array(ll_Idx), vbTextCompare) = 0 Then
            GetSeparatedStringElement = lsa_Array(ll_Idx + 1)
            Exit Function
        End If
        ll_Idx = ll_Idx + 3
    Wend
    Exit Function
ErrHandler:
    Call ErrorHandler("GetSeparatedStringElement")
End Function

Private Function GetDocumentType() As eDocumentType
On Error GoTo ErrHandler

    GetDocumentType = eDocumentType.dtNone
    If cbo_DocumentType.SelectedItem Is Nothing Then
        Exit Function
    End If
    GetDocumentType = cbo_DocumentType.SelectedItem.Key
    Exit Function
ErrHandler:
    Call ErrorHandler("GetDocumentType")
End Function

Private Function GetDocumentPrefix(ByVal ae_DocumentType As eDocumentType) As String
On Error GoTo ErrHandler

    Select Case ae_DocumentType
    Case eDocumentType.dtPriceRequest
        GetDocumentPrefix = "PR"
    Case eDocumentType.dtSalesOrder
        GetDocumentPrefix = "SO"
    Case eDocumentType.dtCreditMemo
        GetDocumentPrefix = "CM"
    Case eDocumentType.dtDebitMemo
        GetDocumentPrefix = "DM"
    Case eDocumentType.dtReturn
        GetDocumentPrefix = "RE"
    Case eDocumentType.dtOfficeInvoice
        GetDocumentPrefix = "OI"
    Case eDocumentType.dtAdminCustomer
        GetDocumentPrefix = "AC"
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("GetDocumentPrefix")
End Function

Private Function HasCustomerInput(ByVal ae_DocumentType As eDocumentType) As Boolean
On Error GoTo ErrHandler

    Select Case ae_DocumentType
    Case eDocumentType.dtPriceRequest, eDocumentType.dtAdminCustomer
        HasCustomerInput = True
    Case eDocumentType.dtSalesOrder, eDocumentType.dtCreditMemo, _
        eDocumentType.dtDebitMemo, eDocumentType.dtReturn, _
        eDocumentType.dtOfficeInvoice
        HasCustomerInput = False
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("HasCustomerInput")
End Function

Private Function HasSAPNumberInput(ByVal ae_DocumentType As eDocumentType) As Boolean
On Error GoTo ErrHandler

    Select Case ae_DocumentType
    Case eDocumentType.dtSalesOrder, eDocumentType.dtCreditMemo, _
        eDocumentType.dtDebitMemo, eDocumentType.dtReturn
        HasSAPNumberInput = True
    Case eDocumentType.dtPriceRequest, eDocumentType.dtAdminCustomer, _
         eDocumentType.dtOfficeInvoice
        HasSAPNumberInput = False
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("HasSAPNumberInput")
End Function

Private Function HasInvoiceInput(ByVal ae_DocumentType As eDocumentType) As Boolean
On Error GoTo ErrHandler

    Select Case ae_DocumentType
    Case eDocumentType.dtOfficeInvoice
        HasInvoiceInput = True
    Case eDocumentType.dtSalesOrder, eDocumentType.dtCreditMemo, _
        eDocumentType.dtDebitMemo, eDocumentType.dtReturn, _
        eDocumentType.dtPriceRequest, eDocumentType.dtAdminCustomer
        HasInvoiceInput = False
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("HasInvoiceInput")
End Function

Private Function Document_Check(ByRef at_Document As SAPDocument, ByRef ao_FocusControl As Control) As Boolean
On Error GoTo ErrHandler

    Dim lv_ClaimCustomer As Variant
    
    Document_Check = False
    Set ao_FocusControl = Nothing
    
    at_Document.FileNameOriginal = GetSelectedPDF()
    at_Document.DocumentType = GetDocumentType()
    
    If at_Document.FileNameOriginal = "" Then
        Call MsgBox(MsgText(C_MSG_ID_BASE + 3, ms_Language_Code, "#Please, select PDF document"))
        Set ao_FocusControl = lvw_PDF_Files
        Exit Function
    End If
    If Not mo_FSO.FileExists(at_Document.FileNameOriginal) Then
        Call MsgBox(MsgText(C_MSG_ID_BASE + 4, ms_Language_Code, "#Selected document has been already removed"))
        Set ao_FocusControl = lvw_PDF_Files
        Exit Function
    End If
    
    at_Document.ID = 0
    at_Document.PageId = 0
    at_Document.PageNr = 0
    If isNumeric(Trim(txt_PageNumber.Text)) Then
        at_Document.PageNr = Val(Trim(txt_PageNumber.Text))
    End If
    If at_Document.PageNr <= 0 Then
        Call MsgBox(MsgText(C_MSG_ID_BASE + 5, ms_Language_Code, "#Please, enter correct page number"))
        Set ao_FocusControl = txt_PageNumber
        Exit Function
    End If
    
    at_Document.CT_Code = ""
    If HasInvoiceInput(at_Document.DocumentType) Then
        If cbo_CountryOfOrigin.SelectedItem Is Nothing Then
            Call MsgBox(MsgText(C_MSG_ID_BASE + 6, ms_Language_Code, "#Please, enter Country of origin"))
            Set ao_FocusControl = cbo_CountryOfOrigin
            Exit Function
        Else
            at_Document.CT_Code = cbo_CountryOfOrigin.SelectedItem.Key
        End If
        
        If cbo_CostCentre.SelectedItem Is Nothing Then
            Call MsgBox(MsgText(C_MSG_ID_BASE + 7, ms_Language_Code, "#Please, enter Cost Centre"))
            Set ao_FocusControl = cbo_CostCentre
            Exit Function
        Else
            at_Document.COC_Code = cbo_CostCentre.SelectedItem.Key
        End If
    
        If cbo_InvoiceType.SelectedItem Is Nothing Then
            Call MsgBox(MsgText(C_MSG_ID_BASE + 8, ms_Language_Code, "#Please, enter Invoice type"))
            Set ao_FocusControl = cbo_InvoiceType
            Exit Function
        Else
            at_Document.INV_Code = cbo_InvoiceType.SelectedItem.Key
        End If
    End If
    
    at_Document.CCU_CapKey = ""
    at_Document.CUST_Code = ""
    Dim lt_Document As SAPDocument
    If HasSAPNumberInput(at_Document.DocumentType) Then
        If isNumeric(Trim(txt_DocumentNumber.Text)) Then
            at_Document.Number = right("0000000000" & Val(Trim(txt_DocumentNumber.Text)), 10)
        Else
            at_Document.Number = ""
        End If
        If at_Document.Number = "" Then
            Call MsgBox(MsgText(C_MSG_ID_BASE + 9, ms_Language_Code, "#Please, enter document number"))
            Set ao_FocusControl = txt_DocumentNumber
            Exit Function
        End If
        
        If at_Document.Number <> mt_LastSAPDocumentDetail.DocumentNumber Then
            If Not GetSAPDocumentDetail(at_Document.Number, mt_LastSAPDocumentDetail) Then
                Call MsgBox(MsgText(C_MSG_ID_BASE + 1, ms_Language_Code, "#SAP document not found"))
                Set ao_FocusControl = txt_DocumentNumber
                Exit Function
            End If
        End If
        lt_Document = GetDocument(at_Document.DocumentType, at_Document.Number, at_Document.PageNr)
        If (lt_Document.Number = at_Document.Number) Then
            at_Document.ID = lt_Document.ID
            If (lt_Document.PageNr = at_Document.PageNr) Then
                Call MsgBox(MsgText(C_MSG_ID_BASE + 10, ms_Language_Code, "#This page is already exists in this document"))
                Set ao_FocusControl = txt_PageNumber
                Exit Function
            End If
        End If
        ' get customer number of this document
        at_Document.CUST_Code = Trim(mt_LastSAPDocumentDetail.CustomerNumber)
        If at_Document.CUST_Code = "" Then
            Call MsgBox(MsgText(C_MSG_ID_BASE + 2, ms_Language_Code, "#Customer number not found"))
            Exit Function
        End If
        ' check if we have customer in Sifyb, if yes, retrieve his CCU_CapKey
        lv_ClaimCustomer = GetClaimCustomer(at_Document.CUST_Code)
        If (IsArray(lv_ClaimCustomer)) Then
            at_Document.CCU_CapKey = lv_ClaimCustomer(0)
        End If
    Else
        If isNumeric(Trim(txt_DocumentNumber.Text)) Then
            at_Document.ID = Val(Trim(txt_DocumentNumber.Text))
        Else
            at_Document.ID = 0
        End If
        If at_Document.ID <> 0 Then
            lt_Document = GetDocument(at_Document.DocumentType, at_Document.ID, at_Document.PageNr)
            If (lt_Document.ID = at_Document.ID) And (lt_Document.PageNr = at_Document.PageNr) Then
                Call MsgBox(MsgText(C_MSG_ID_BASE + 10, ms_Language_Code, "#This page is already exists in this document"))
                Set ao_FocusControl = txt_DocumentNumber
                Exit Function
            End If
        End If
    End If
    
    If HasCustomerInput(at_Document.DocumentType) Then
        If Trim(txt_CustomerNumber.Text) <> "" Then
            at_Document.CUST_Code = right("0000000000" & Trim(txt_CustomerNumber.Text), 10)
        End If
        
        If at_Document.CUST_Code = "" Then
            Call MsgBox(MsgText(C_MSG_ID_BASE + 11, ms_Language_Code, "#Please, enter customer number"))
            Set ao_FocusControl = txt_CustomerNumber
            Exit Function
        End If
        
        lv_ClaimCustomer = GetClaimCustomer(at_Document.CUST_Code)
        If (IsArray(lv_ClaimCustomer)) Then
            at_Document.CCU_CapKey = lv_ClaimCustomer(0)
            at_Document.CT_Code = lv_ClaimCustomer(2)
        Else
            ' check if we do not retreve customer from SAP recently
            If at_Document.CUST_Code = mt_LastSAPCustomerDetail.CustomerNumber Then
                at_Document.CT_Code = mt_LastSAPCustomerDetail.CT_Code
            Else
                If GetSAPCustomerDetail(at_Document.CUST_Code, mt_LastSAPCustomerDetail) Then
                    at_Document.CT_Code = mt_LastSAPCustomerDetail.CT_Code
                Else
                    Call MsgBox(MsgText(C_MSG_ID_BASE + 2, ms_Language_Code, "#Customer number not found"))
                    Set ao_FocusControl = txt_CustomerNumber
                    Exit Function
                End If
            End If
        End If
    End If
    Document_Check = True
    Exit Function
ErrHandler:
    Call ErrorHandler("Document_Check")
End Function

Private Sub Document_UpdateLocal(ByRef at_Document As SAPDocument)
On Error GoTo ErrHandler

    Dim lo_item As ListItem
    Dim ls_Prefix As String
    Dim ls_DocumentNumber As String
    
    ls_Prefix = GetDocumentPrefix(at_Document.DocumentType)
    If HasSAPNumberInput(at_Document.DocumentType) Then
        txt_DocumentNumber.Text = at_Document.Number
        Set lo_item = lvw_RecentDocument.ListItems.Add(1, , at_Document.Number)
    Else
        txt_DocumentNumber.Text = at_Document.ID
        Set lo_item = lvw_RecentDocument.ListItems.Add(1, , at_Document.ID)
    End If
    lo_item.Tag = ms_DocumentServerDir & ls_Prefix & "_" & at_Document.PageId & "_*.PDF"
    Call lo_item.ListSubItems.Add(, , at_Document.PageNr)
    If HasCustomerInput(at_Document.DocumentType) Then
        Call lo_item.ListSubItems.Add(, , at_Document.CUST_Code)
    End If
    
    txt_PageNumber.Text = ""
    txt_DocumentNumber.Text = ""
    Call SetNextPDF_File
    Exit Sub
ErrHandler:
    Call ErrorHandler("Document_UpdateLocal")
End Sub

Private Sub SetNextPDF_File()
On Error GoTo ErrHandler
    Dim lo_item As ListItem
    
    Dim ll_OldIndex As Long
    ll_OldIndex = lvw_PDF_Files.SelectedItem.Index
    Call lvw_PDF_Files.ListItems.Remove(ll_OldIndex)
    If ll_OldIndex > lvw_PDF_Files.ListItems.Count Then ll_OldIndex = lvw_PDF_Files.ListItems.Count
    If ll_OldIndex > 0 Then lvw_PDF_Files.ListItems(ll_OldIndex).Selected = True
    Call lvw_PDF_Files_Click
    Exit Sub
ErrHandler:
    Call ErrorHandler("SetNextPDF_File")
End Sub

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

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

Private Sub Document_Clear()
On Error GoTo ErrHandler
    
    txt_DocumentNumber.Text = ""
    txt_PageNumber.Text = ""
    txt_CustomerName.Text = ""
    txt_CustomerNumber.Text = ""
    Exit Sub
ErrHandler:
    Call ErrorHandler("Document_Clear")
End Sub

Private Function CreatePDFDocumentName(ByRef at_Document As SAPDocument) As String
On Error GoTo ErrHandler

    CreatePDFDocumentName = GetDocumentPrefix(at_Document.DocumentType) & "_" & _
                    at_Document.PageId & "_" & _
                    right("00" & ml_ZipTableIndex(at_Document.DocumentType), 3) & "_" & _
                    at_Document.DocumentStatus & "_" & _
                    ms_LoginName & "_" & _
                    ms_ComputerName & ".PDF"
    Exit Function
ErrHandler:
    Call ErrorHandler("CreatePDFDocumentName")
End Function

Private Sub Document_Save(ByRef at_Document As SAPDocument)
On Error GoTo ErrHandler

    Dim ls_FileName As String
    
    at_Document.PageId = GetNewPageId(at_Document.DocumentType)
    at_Document.DocumentStatus = eZipDocumentStatus.None
    
    at_Document.FileNameServer = ms_DocumentServerDir & CreatePDFDocumentName(at_Document)
    
    ' first move pdf to the service archive directory with status None = 0, service will not touch it now
    Call Document_Move(at_Document.FileNameOriginal, at_Document.FileNameServer)
    
    
    ' then create sql records for this file, so service uploaded can upload file to sql with correct id
    If at_Document.ID = 0 Then
        Call InsertDocument(at_Document)
    End If
    Call InsertDocumentPage(at_Document)
    
    ' now rename file on server to status Waiting = 1, so service can start to upload it to sql server
    at_Document.DocumentStatus = eZipDocumentStatus.Waiting
    ls_FileName = CreatePDFDocumentName(at_Document)
    Call Document_Rename(at_Document.FileNameServer, ls_FileName)
    at_Document.FileNameServer = ms_DocumentServerDir & ls_FileName
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Document_Save")
End Sub

Private Sub cmd_Validate_Click()
On Error GoTo ErrHandler

    Dim lt_Document As SAPDocument
    Dim lo_Control As Control
    
    Call LockScreen(True)
    
    fra_SAP_Detail.Visible = False
    fra_RecentPDF.Visible = False
    If Document_Check(lt_Document, lo_Control) Then
        Call Document_Save(lt_Document)
        Call Document_UpdateLocal(lt_Document)
    End If
    
    Call LockScreen(False)
    
    If Not lo_Control Is Nothing Then
        Call lo_Control.SetFocus
    End If
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("cmd_Validate_Click")
End Sub

Private Function GetSelectedPDF() As String
On Error GoTo ErrHandler

Dim ls_PdfFile As String
    
    GetSelectedPDF = ""
    If lvw_PDF_Files.SelectedItem Is Nothing Then
        Exit Function
    End If
    GetSelectedPDF = lvw_PDF_Files.SelectedItem.Tag
    Exit Function
ErrHandler:
    Call ErrorHandler("GetSelectedPDF")
End Function

Private Function GetNewDocumentId(ByVal ae_DocumentType As eDocumentType) As Long
On Error GoTo ErrHandler

    GetNewDocumentId = 0
    Select Case ae_DocumentType
    Case eDocumentType.dtSalesOrder
        GetNewDocumentId = GetSequenceCode("EAS_SalesOrder")
    Case eDocumentType.dtPriceRequest
        GetNewDocumentId = GetSequenceCode("EAS_PriceRequest")
    Case eDocumentType.dtDebitMemo
        GetNewDocumentId = GetSequenceCode("EAS_DebitMemo")
    Case eDocumentType.dtCreditMemo
        GetNewDocumentId = GetSequenceCode("EAS_CreditMemo")
    Case eDocumentType.dtReturn
        GetNewDocumentId = GetSequenceCode("EAS_Return")
    Case eDocumentType.dtAdminCustomer
        GetNewDocumentId = GetSequenceCode("EAS_AdminCustomer")
    Case eDocumentType.dtOfficeInvoice
        GetNewDocumentId = GetSequenceCode("EAS_OfficeInvoice")
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("GetNewDocumentId")
End Function

Private Sub InsertDocument(ByRef at_Document As SAPDocument)
Const REQ_SALESORDER_INSERT  As String = "exec EAS_SalesOrder_ins $Id$, $Number$, $CCU_Capkey$, $CUST_Code$, $U_Code$"
Const REQ_PRICEREQUEST_INSERT  As String = "exec EAS_PriceRequest_ins $Id$, $CCU_Capkey$, $CUST_Code$, $CT_Code$, $U_Code$"
Const REQ_DEBITMEMO_INSERT  As String = "exec EAS_DebitMemo_ins $Id$, $Number$, $CCU_Capkey$, $CUST_Code$, $U_Code$"
Const REQ_CREDITMEMO_INSERT  As String = "exec EAS_CreditMemo_ins $Id$, $Number$, $CCU_Capkey$, $CUST_Code$, $U_Code$"
Const REQ_RETURN_INSERT  As String = "exec EAS_Return_ins $Id$, $Number$, $CCU_Capkey$, $CUST_Code$, $U_Code$"
Const REQ_ADMINCUSTOMER_INSERT  As String = "exec EAS_AdminCustomer_ins $Id$, $CCU_Capkey$, $CUST_Code$, $CT_Code$, $U_Code$"
Const REQ_OFFICEINVOICE_INSERT  As String = "exec EAS_OfficeInvoice_ins $Id$, $CT_Code$, $COC_Code$, $INV_Code$, $U_Code$"

On Error GoTo ErrHandler

    Dim ls_Request As String
    
    at_Document.ID = GetNewDocumentId(at_Document.DocumentType)
    
    Select Case at_Document.DocumentType
    Case eDocumentType.dtSalesOrder
        ls_Request = REQ_SALESORDER_INSERT
    Case eDocumentType.dtPriceRequest
        ls_Request = REQ_PRICEREQUEST_INSERT
    Case eDocumentType.dtDebitMemo
        ls_Request = REQ_DEBITMEMO_INSERT
    Case eDocumentType.dtCreditMemo
        ls_Request = REQ_CREDITMEMO_INSERT
    Case eDocumentType.dtReturn
        ls_Request = REQ_RETURN_INSERT
    Case eDocumentType.dtAdminCustomer
        ls_Request = REQ_ADMINCUSTOMER_INSERT
    Case eDocumentType.dtOfficeInvoice
        ls_Request = REQ_OFFICEINVOICE_INSERT
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & at_Document.DocumentType
    End Select
    
    ls_Request = ReplacePlaceHolder(ls_Request, "$Id$", at_Document.ID)
    If at_Document.CCU_CapKey = "" Then
        ls_Request = ReplacePlaceHolder(ls_Request, "$CCU_Capkey$", "NULL")
    Else
        ls_Request = ReplacePlaceHolder(ls_Request, "$CCU_Capkey$", SQLStr(at_Document.CCU_CapKey))
    End If
    ls_Request = ReplacePlaceHolder(ls_Request, "$CUST_Code$", SQLStr(at_Document.CUST_Code))
    If at_Document.CT_Code = "" Then
        ls_Request = ReplacePlaceHolder(ls_Request, "$CT_Code$", "NULL")
    Else
        ls_Request = ReplacePlaceHolder(ls_Request, "$CT_Code$", SQLStr(at_Document.CT_Code))
    End If
    If at_Document.COC_Code = 0 Then
        ls_Request = ReplacePlaceHolder(ls_Request, "$COC_Code$", "NULL")
    Else
        ls_Request = ReplacePlaceHolder(ls_Request, "$COC_Code$", at_Document.COC_Code)
    End If
    If at_Document.INV_Code = 0 Then
        ls_Request = ReplacePlaceHolder(ls_Request, "$INV_Code$", "NULL")
    Else
        ls_Request = ReplacePlaceHolder(ls_Request, "$INV_Code$", at_Document.INV_Code)
    End If
    ls_Request = ReplacePlaceHolder(ls_Request, "$Number$", SQLStr(at_Document.Number))
    ls_Request = ReplacePlaceHolder(ls_Request, "$U_Code$", ml_U_code)
    Call ExecuteSQLSafe(mo_Db, ls_Request, 1)
    Exit Sub
ErrHandler:
    Call ErrorHandler("InsertDocument")
End Sub

Private Function GetNewPageId(ByVal ae_DocumentType As eDocumentType) As Long
On Error GoTo ErrHandler

    GetNewPageId = 0
    Select Case ae_DocumentType
    Case eDocumentType.dtSalesOrder
        GetNewPageId = GetSequenceCode("EAS_SalesOrderPage")
    Case eDocumentType.dtPriceRequest
        GetNewPageId = GetSequenceCode("EAS_PriceRequestPage")
    Case eDocumentType.dtDebitMemo
        GetNewPageId = GetSequenceCode("EAS_DebitMemoPage")
    Case eDocumentType.dtCreditMemo
        GetNewPageId = GetSequenceCode("EAS_CreditMemoPage")
    Case eDocumentType.dtReturn
        GetNewPageId = GetSequenceCode("EAS_ReturnPage")
    Case eDocumentType.dtAdminCustomer
        GetNewPageId = GetSequenceCode("EAS_AdminCustomerPage")
    Case eDocumentType.dtOfficeInvoice
        GetNewPageId = GetSequenceCode("EAS_OfficeInvoicePage")
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    Exit Function
ErrHandler:
    Call ErrorHandler("GetNewPageId")
End Function

Private Sub InsertDocumentPage(ByRef at_Document As SAPDocument)
Const REQ_SALESORDERPAGE_INSERT  As String = "exec EAS_SalesOrderPage_ins $PageId$, $Id$, $PageNr$, $NetworkBoardID$, $UserName$, $ComputerName$, $ZipTableIndex$, $Status$, $U_Code$"
Const REQ_PRICEREQUESTPAGE_INSERT  As String = "exec EAS_PriceRequestPage_ins $PageId$, $Id$, $PageNr$, $NetworkBoardID$, $UserName$, $ComputerName$, $ZipTableIndex$, $Status$, $U_Code$"
Const REQ_DEBITMEMOPAGE_INSERT  As String = "exec EAS_DebitMemoPage_ins $PageId$, $Id$, $PageNr$, $NetworkBoardID$, $UserName$, $ComputerName$, $ZipTableIndex$, $Status$, $U_Code$"
Const REQ_CREDITMEMOPAGE_INSERT  As String = "exec EAS_CreditMemoPage_ins $PageId$, $Id$, $PageNr$, $NetworkBoardID$, $UserName$, $ComputerName$, $ZipTableIndex$, $Status$, $U_Code$"
Const REQ_RETURNPAGE_INSERT  As String = "exec EAS_ReturnPage_ins $PageId$, $Id$, $PageNr$, $NetworkBoardID$, $UserName$, $ComputerName$, $ZipTableIndex$, $Status$, $U_Code$"
Const REQ_ADMINCUSTOMERPAGE_INSERT  As String = "exec EAS_AdminCustomerPage_ins $PageId$, $Id$, $PageNr$, $NetworkBoardID$, $UserName$, $ComputerName$, $ZipTableIndex$, $Status$, $U_Code$"
Const REQ_OFFICEINVOICEPAGE_INSERT  As String = "exec EAS_OfficeInvoicePage_ins $PageId$, $Id$, $PageNr$, $NetworkBoardID$, $UserName$, $ComputerName$, $ZipTableIndex$, $Status$, $U_Code$"
On Error GoTo ErrHandler

    Dim ls_Request As String
    Dim ll_Count As Long
    
    If ml_ZipTableIndex(at_Document.DocumentType) = 0 Then
        ml_ZipTableIndex(at_Document.DocumentType) = GetDocumentZipTableIndexMax(at_Document.DocumentType)
    End If

    ll_Count = GetDocumentPageCount(at_Document.DocumentType, ml_ZipTableIndex(at_Document.DocumentType))
    If ll_Count >= ml_MaxZipRecordCount Then
        ml_ZipTableIndex(at_Document.DocumentType) = ml_ZipTableIndex(at_Document.DocumentType) + 1
    End If
    
    Select Case at_Document.DocumentType
    Case eDocumentType.dtSalesOrder
        ls_Request = REQ_SALESORDERPAGE_INSERT
    Case eDocumentType.dtPriceRequest
        ls_Request = REQ_PRICEREQUESTPAGE_INSERT
    Case eDocumentType.dtDebitMemo
        ls_Request = REQ_DEBITMEMOPAGE_INSERT
    Case eDocumentType.dtCreditMemo
        ls_Request = REQ_CREDITMEMOPAGE_INSERT
    Case eDocumentType.dtReturn
        ls_Request = REQ_RETURNPAGE_INSERT
    Case eDocumentType.dtAdminCustomer
        ls_Request = REQ_ADMINCUSTOMERPAGE_INSERT
    Case eDocumentType.dtOfficeInvoice
        ls_Request = REQ_OFFICEINVOICEPAGE_INSERT
    Case Else
        Err.Raise ArmErr.CompFncFailed, "at_Document.DocumentType", "Unknown document type : " & at_Document.DocumentType
    End Select
    
    ls_Request = ReplacePlaceHolder(ls_Request, "$PageId$", at_Document.PageId)
    ls_Request = ReplacePlaceHolder(ls_Request, "$Id$", at_Document.ID)
    ls_Request = ReplacePlaceHolder(ls_Request, "$PageNr$", at_Document.PageNr)
    ls_Request = ReplacePlaceHolder(ls_Request, "$NetworkBoardID$", SQLStr(ms_NetworkBoardID))
    ls_Request = ReplacePlaceHolder(ls_Request, "$UserName$", SQLStr(ms_LoginName))
    ls_Request = ReplacePlaceHolder(ls_Request, "$ComputerName$", SQLStr(ms_ComputerName))
    ls_Request = ReplacePlaceHolder(ls_Request, "$ZipTableIndex$", ml_ZipTableIndex(at_Document.DocumentType))
    ls_Request = ReplacePlaceHolder(ls_Request, "$Status$", eZipDocumentStatus.Waiting)
    ls_Request = ReplacePlaceHolder(ls_Request, "$U_Code$", ml_U_code)
    Call ExecuteSQLSafe(mo_Db, ls_Request, 1)
    Exit Sub
ErrHandler:
    Call ErrorHandler("InsertDocumentPage")
End Sub

Private Function GetDocument(ByVal ae_DocumentType As eDocumentType, ByVal as_DocId As String, ByVal al_PageNr As Long) As SAPDocument
Const REQ_SALESORDER_SEL  As String = "exec EAS_SalesOrderPage_sel2 $Id$, $PageNr$"
Const REQ_PRICEREQUEST_SEL  As String = "exec EAS_PriceRequestPage_sel2 $Id$, $PageNr$"
Const REQ_DEBITMEMO_SEL  As String = "exec EAS_DebitMemoPage_sel2 $Id$, $PageNr$"
Const REQ_CREDITMEMO_SEL  As String = "exec EAS_CreditMemoPage_sel2 $Id$, $PageNr$"
Const REQ_RETURN_SEL  As String = "exec EAS_ReturnPage_sel2 $Id$, $PageNr$"
Const REQ_ADMINCUSTOMER_SEL  As String = "exec EAS_AdminCustomerPage_sel2 $Id$, $PageNr$"
Const REQ_OFFICEINVOICE_SEL  As String = "exec EAS_OfficeInvoicePage_sel2 $Id$, $PageNr$"
On Error GoTo ErrHandler

    Dim ls_Request As String
    Dim lc_Cursor As Long
    Dim lo_Document As SAPDocument
    
    lo_Document.DocumentType = ae_DocumentType
    
    Select Case ae_DocumentType
    Case eDocumentType.dtSalesOrder
        ls_Request = REQ_SALESORDER_SEL
    Case eDocumentType.dtPriceRequest
        ls_Request = REQ_PRICEREQUEST_SEL
    Case eDocumentType.dtDebitMemo
        ls_Request = REQ_DEBITMEMO_SEL
    Case eDocumentType.dtCreditMemo
        ls_Request = REQ_CREDITMEMO_SEL
    Case eDocumentType.dtReturn
        ls_Request = REQ_RETURN_SEL
    Case eDocumentType.dtAdminCustomer
        ls_Request = REQ_ADMINCUSTOMER_SEL
    Case eDocumentType.dtOfficeInvoice
        ls_Request = REQ_OFFICEINVOICE_SEL
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    
    ls_Request = ReplacePlaceHolder(ls_Request, "$Id$", SQLStr(as_DocId))
    ls_Request = ReplacePlaceHolder(ls_Request, "$PageNr$", al_PageNr)
    lc_Cursor = OpenSQLSafe(mo_Db, ls_Request)
    If mo_Db.RowCount(lc_Cursor) = 1 Then
        lo_Document.ID = mo_Db.GetFields(lc_Cursor, "Id")
        lo_Document.PageId = mo_Db.GetFields(lc_Cursor, "PageId")
        lo_Document.PageNr = mo_Db.GetFields(lc_Cursor, "PageNr")
        lo_Document.Number = mo_Db.GetFields(lc_Cursor, "Number")
        lo_Document.CCU_CapKey = mo_Db.GetFields(lc_Cursor, "CCU_Capkey")
        lo_Document.CUST_Code = mo_Db.GetFields(lc_Cursor, "CUST_Code")
    End If
    Call mo_Db.Close(lc_Cursor)
    GetDocument = lo_Document
    Exit Function
ErrHandler:
    Call mo_Db.Close(lc_Cursor)
    Call ErrorHandler("GetDocument")
End Function

Private Function GetDocumentPageCount(ByVal ae_DocumentType As eDocumentType, ByVal al_ZipTableIndex As Long) As Long
Const REQ_PRICEREQUESTPAGE_COUNT  As String = "exec EAS_PriceRequestPage_cnt $ZipTableIndex$"
Const REQ_SALESORDERPAGE_COUNT  As String = "exec EAS_SalesOrderPage_cnt $ZipTableIndex$"
Const REQ_DEBITMEMOPAGE_COUNT  As String = "exec EAS_DebitMemoPage_cnt $ZipTableIndex$"
Const REQ_CREDITMEMOPAGE_COUNT  As String = "exec EAS_CreditMemoPage_cnt $ZipTableIndex$"
Const REQ_RETURNPAGE_COUNT  As String = "exec EAS_ReturnPage_cnt $ZipTableIndex$"
Const REQ_OFFICEINVOICEPAGE_COUNT  As String = "exec EAS_OfficeInvoicePage_cnt $ZipTableIndex$"
Const REQ_ADMINCUSTOMERPAGE_COUNT  As String = "exec EAS_AdminCustomerPage_cnt $ZipTableIndex$"
On Error GoTo ErrHandler

    Dim ls_Request As String
    Dim lc_Cursor As Long
    
    Select Case ae_DocumentType
    Case eDocumentType.dtPriceRequest
        ls_Request = REQ_PRICEREQUESTPAGE_COUNT
    Case eDocumentType.dtSalesOrder
        ls_Request = REQ_SALESORDERPAGE_COUNT
    Case eDocumentType.dtDebitMemo
        ls_Request = REQ_DEBITMEMOPAGE_COUNT
    Case eDocumentType.dtCreditMemo
        ls_Request = REQ_CREDITMEMOPAGE_COUNT
    Case eDocumentType.dtReturn
        ls_Request = REQ_RETURNPAGE_COUNT
    Case eDocumentType.dtOfficeInvoice
        ls_Request = REQ_OFFICEINVOICEPAGE_COUNT
    Case eDocumentType.dtAdminCustomer
        ls_Request = REQ_ADMINCUSTOMERPAGE_COUNT
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    
    ls_Request = ReplacePlaceHolder(ls_Request, "$ZipTableIndex$", al_ZipTableIndex)
    lc_Cursor = OpenSQLSafe(mo_Db, ls_Request, 1)
    GetDocumentPageCount = mo_Db.GetFields(lc_Cursor, 0)
    Call mo_Db.Close(lc_Cursor)
    Exit Function
ErrHandler:
    Call mo_Db.Close(lc_Cursor)
    Call ErrorHandler("GetDocumentPageCount")
End Function

Private Function GetDocumentZipTableIndexMax(ByVal ae_DocumentType As eDocumentType) As Long
Const REQ_PRICEREQUESTPAGE_MAX  As String = "exec EAS_PriceRequestPage_max"
Const REQ_SALESORDERPAGE_MAX  As String = "exec EAS_SalesOrderPage_max"
Const REQ_DEBITMEMOPAGE_MAX  As String = "exec EAS_DebitMemoPage_max"
Const REQ_CREDITMEMOPAGE_MAX  As String = "exec EAS_CreditMemoPage_max"
Const REQ_RETURNPAGE_MAX  As String = "exec EAS_ReturnPage_max"
Const REQ_OFFICEINVOICEPAGE_MAX  As String = "exec EAS_OfficeInvoicePage_max"
Const REQ_ADMINCUSTOMERPAGE_MAX  As String = "exec EAS_AdminCustomerPage_max"
On Error GoTo ErrHandler

    Dim ls_Request As String
    Dim lc_Cursor As Long
    Dim ll_Index As Long
    
    Select Case ae_DocumentType
    Case eDocumentType.dtPriceRequest
        ls_Request = REQ_PRICEREQUESTPAGE_MAX
    Case eDocumentType.dtSalesOrder
        ls_Request = REQ_SALESORDERPAGE_MAX
    Case eDocumentType.dtDebitMemo
        ls_Request = REQ_DEBITMEMOPAGE_MAX
    Case eDocumentType.dtCreditMemo
        ls_Request = REQ_CREDITMEMOPAGE_MAX
    Case eDocumentType.dtReturn
        ls_Request = REQ_RETURNPAGE_MAX
    Case eDocumentType.dtOfficeInvoice
        ls_Request = REQ_OFFICEINVOICEPAGE_MAX
    Case eDocumentType.dtAdminCustomer
        ls_Request = REQ_ADMINCUSTOMERPAGE_MAX
    Case Else
        Err.Raise ArmErr.CompFncFailed, "ae_DocumentType", "Unknown document type : " & ae_DocumentType
    End Select
    
    lc_Cursor = OpenSQLSafe(mo_Db, ls_Request, 1)
    ll_Index = mo_Db.GetFields(lc_Cursor, 0)
    If ll_Index = 0 Then ll_Index = 1
    GetDocumentZipTableIndexMax = ll_Index
    Call mo_Db.Close(lc_Cursor)
    Exit Function
ErrHandler:
    Call mo_Db.Close(lc_Cursor)
    Call ErrorHandler("GetDocumentZipTableIndexMax")
End Function

Private Function GetClaimCustomer(ByVal as_CUST_Code As String) As Variant
Const REQ_CLAIMCUST_SEL  As String = "exec Claim_Customer_sel4 $CUST_Code$"
On Error GoTo ErrHandler

    Dim ls_Request As String
    Dim lc_Cursor As Long
    
    GetClaimCustomer = Empty
    
    ls_Request = REQ_CLAIMCUST_SEL
    ls_Request = ReplacePlaceHolder(ls_Request, "$CUST_Code$", SQLStr(as_CUST_Code))
    lc_Cursor = OpenSQLSafe(mo_Db, ls_Request)
    If mo_Db.RowCount(lc_Cursor) = 1 Then
        GetClaimCustomer = Array(mo_Db.GetFields(lc_Cursor, "CCU_Capkey"), mo_Db.GetFields(lc_Cursor, "CCU_Desc"), mo_Db.GetFields(lc_Cursor, "CT_Code"))
    End If
    Call mo_Db.Close(lc_Cursor)
    Exit Function
ErrHandler:
    Call mo_Db.Close(lc_Cursor)
    Call ErrorHandler("GetClaimCustomer")
End Function

Public Sub Resize()
On Error GoTo ErrHandler
    
    'resize form
    If Me.Width > 10000 And Me.Height > 5000 Then
        fra_Detail.Top = Me.Height - fra_Detail.Height - 800
        
        lvw_RecentDocument.Top = Me.Height - lvw_RecentDocument.Height - 800
        lvw_RecentDocument.Width = Me.Width - lvw_RecentDocument.Left - 200
        
        lvw_PDF_Files.Height = fra_Detail.Top - lvw_PDF_Files.Top
        fra_PDFView.Height = fra_Detail.Top - fra_PDFView.Top
        
        fra_PDFControl.Width = Me.Width - fra_PDFControl.Left - 200
        fra_PDFView.Width = Me.Width - fra_PDFView.Left - 200
        
        mo_Pdf.Height = fra_PDFView.Height
        mo_Pdf.Width = fra_PDFView.Width
    
        fra_RecentPDF.Width = 2 * (fra_PDFView.Width / 3)
        fra_RecentPDF.Height = 2 * (fra_PDFView.Height / 3)
        fra_RecentPDF.Left = (fra_PDFView.Left + fra_PDFView.Width) - fra_RecentPDF.Width
        fra_RecentPDF.Top = (fra_PDFView.Top + fra_PDFView.Height) - fra_RecentPDF.Height
        fra_RecentPDFView.Width = fra_RecentPDF.Width
        fra_RecentPDFView.Height = fra_RecentPDF.Height - fra_RecentPDFView.Top
        
        cmd_CloseRecentPDF.Top = cmd_AddRecentPdf.Top
        cmd_CloseRecentPDF.Left = fra_RecentPDF.Width - cmd_CloseRecentPDF.Width - cmd_AddRecentPdf.Left
        
        mo_RecentPdf.Width = fra_RecentPDFView.Width
        mo_RecentPdf.Height = fra_RecentPDFView.Height
        
        cmd_Quit.Left = fra_PDFControl.Width - cmd_Quit.Width
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("Resize")
End Sub

Private Sub lst_DirectoryList_Change()
On Error GoTo ErrHandler
    
    If mb_InternalInit Then Exit Sub
    Call LockScreen(True)
    Call ReadFileList(lst_DirectoryList.Path)
    fra_RecentPDF.Visible = False
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("lst_DirectoryList_Change")
End Sub

Private Sub cbo_DriveList_ComboItemSelected()
On Error GoTo ErrHandler

Dim lo_Drive As Object

    If mb_InternalInit Then Exit Sub
    If Len(cbo_DriveList.Text) = 2 Then
        Set lo_Drive = mo_FSO.GetDrive(cbo_DriveList.Text)
        If Not lo_Drive.IsReady Then
            Exit Sub
        End If
    Else
        If Not mo_FSO.FolderExists(cbo_DriveList.Text) Then
            Exit Sub
        End If
    End If
    lst_DirectoryList.Path = cbo_DriveList.Text
    fra_RecentPDF.Visible = False
    Exit Sub
ErrHandler:
    Call ErrorMessage("cbo_DriveList_ComboItemSelected")
End Sub

Private Sub ReadFileList(ByVal as_Path As String)
On Error GoTo ErrHandler

    Dim ls_File As String
    Dim lo_item As ListItem
    Dim lo_File As Object
    
    Call lvw_PDF_Files.ListItems.Clear
    If right(as_Path, 1) <> "\" Then as_Path = as_Path & "\"
    
    ls_File = Dir$(as_Path & "*.PDF")
    Do While ls_File <> ""
        Set lo_File = mo_FSO.GetFile(as_Path & ls_File)
        Set lo_item = lvw_PDF_Files.ListItems.Add(, , ls_File)
        Call lo_item.ListSubItems.Add(, , Format(lo_File.DateCreated, "yyyy\/mm\/dd hh:mm"))
        lo_item.Tag = as_Path & ls_File
        ls_File = Dir$
    Loop
    Call lvw_PDF_Files_Click
    Exit Sub
ErrHandler:
    Call ErrorHandler("ReadFileList")
End Sub

Private Sub lvw_PDF_Files_Click()
On Error GoTo ErrHandler

    Dim ls_FileName As String
    If mb_InternalInit Then Exit Sub
    
    Call LockScreen(True)
    fra_SAP_Detail.Visible = False
    fra_RecentPDF.Visible = False
    
    Call mo_Pdf.LoadFile("")
    mo_Pdf.Visible = False
    If Not lvw_PDF_Files.SelectedItem Is Nothing Then
        ls_FileName = lst_DirectoryList.Path
        If right(ls_FileName, 1) <> "\" Then
            ls_FileName = ls_FileName & "\"
        End If
        ls_FileName = ls_FileName & lvw_PDF_Files.SelectedItem.Text
        If mo_FSO.FileExists(ls_FileName) Then
            Call mo_Pdf.LoadFile(ls_FileName)
            Call mo_Pdf.setShowToolbar(False)
            Call mo_Pdf.setLayoutMode("SinglePage")
            Call mo_Pdf.setPageMode("none")
            If ms_ZoomViewPdf = "" Then
                Call mo_Pdf.SetView("fitH")
            ElseIf isNumeric(ms_ZoomViewPdf) Then
                Call mo_Pdf.setZoom(Val(ms_ZoomViewPdf))
            Else
                Call mo_Pdf.SetView(ms_ZoomViewPdf)
            End If
            mo_Pdf.Visible = True
        Else
            mo_Pdf.Visible = False
        End If
    Else
        mo_Pdf.Visible = False
    End If
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("lvw_PDF_Files_Click")
End Sub

Private Sub lvw_RecentDocument_Click()
On Error GoTo ErrHandler
    
    Dim ls_FileName As String
    Dim ls_RecentFileServer As String
    Dim ls_RecentFileTemp As String
    Dim ls_TempDir As String
    
    Call LockScreen(True)
    fra_SAP_Detail.Visible = False
    If (lvw_RecentDocument.SelectedItem Is Nothing) Then
        Call LockScreen(False)
        Exit Sub
    End If
    
    ls_FileName = Dir$(lvw_RecentDocument.SelectedItem.Tag)
    If ls_FileName = "" Then
        Call LockScreen(False)
        Exit Sub
    Else
        ls_TempDir = GetTempDir & "\"
        If Not mo_FSO.FolderExists(ls_TempDir) Then
            Call mo_FSO.CreateFolder(ls_TempDir)
        End If
        ls_RecentFileServer = ms_DocumentServerDir & ls_FileName
        ls_RecentFileTemp = ls_TempDir & ls_FileName
        If Not mo_FSO.FileExists(ls_RecentFileTemp) Then
            Call mo_FSO.CopyFile(ls_RecentFileServer, ls_TempDir)
        End If
    End If
    
    If mo_FSO.FileExists(ls_RecentFileTemp) Then
        Call mo_RecentPdf.LoadFile(ls_RecentFileTemp)
        Call mo_RecentPdf.setShowToolbar(False)
        Call mo_RecentPdf.setLayoutMode("SinglePage")
        Call mo_RecentPdf.setPageMode("none")
        Call mo_RecentPdf.SetView("fitH")
        txt_RecentNumber.Text = lvw_RecentDocument.SelectedItem.Text & " \ " & lvw_RecentDocument.SelectedItem.ListSubItems(1).Text
        fra_RecentPDFView.Visible = True
    Else
        fra_RecentPDFView.Visible = False
        txt_RecentNumber.Text = ""
    End If
    
    fra_RecentPDF.Visible = True
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("lvw_RecentDocument_Click")
End Sub

Private Sub txt_CustomerNumber_KeyDown(KeyCode As Integer, Shift As Integer)
On Error GoTo ErrHandler
    Dim lv_ClaimCustomer As Variant
    
    If KeyCode = 13 Then
        Call LockScreen(True)
        txt_CustomerName.Text = ""
        lv_ClaimCustomer = GetClaimCustomer(Trim(txt_CustomerNumber.Text))
        If IsArray(lv_ClaimCustomer) Then
            txt_CustomerName.Text = lv_ClaimCustomer(1)
        End If
        Call LockScreen(False)
    End If
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage("txt_CustomerNumber_KeyDown")
End Sub

Private Function GetMACAddress() As String
On Error GoTo ErrHandler

    Dim ls_Query As String
    Dim lo_WMIService As Object
    Dim lo_Items As Object
    Dim lo_item As Object
' We're interested in MAC addresses of physical adapters only
    ls_Query = "SELECT * " & _
                "FROM Win32_NetworkAdapter " & _
                "WHERE ConfigManagerErrorCode=0 AND " & _
                "NetConnectionID > '' AND " & _
                "(NetConnectionStatus=2 OR NetConnectionStatus=9)"

    Set lo_WMIService = GetObject("winmgmts://./root/CIMV2")
    Set lo_Items = lo_WMIService.ExecQuery(ls_Query, "WQL", 48)

    For Each lo_item In lo_Items
        If lo_item.MACAddress <> "" Then
            GetMACAddress = Replace(lo_item.MACAddress, ":", "", , , vbTextCompare)
            Exit Function
        End If
    Next
    GetMACAddress = ""
    Exit Function
ErrHandler:
    Call ErrorHandler("GetMACAddress")
End Function

Private Function GetSAPCustomerDetail(ByVal as_CUST_Code As String, ByRef at_SAPCustomerDetail As SAPCustomerDetail) As Boolean
On Error GoTo ErrHandler

    Dim ls_retContent   As String
    Dim ls_retHeader    As String
    Dim lo_XMLParam     As New SvcXMLParam
    
    GetSAPCustomerDetail = False
    as_CUST_Code = right("0000000000" & as_CUST_Code, 10)
    If Not mo_Sys.CallWebservice(ms_UrlCustomerDetail, C_SERVICE_USER, C_SERVICE_PASSW, "_custNB=" & as_CUST_Code, "application/x-www-form-urlencoded", "", ls_retContent, ls_retHeader) Then
        ' no service
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "No service"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 12, ms_Language_Code, "#SAP customer service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    If Not lo_XMLParam.CheckHTTPResponse(ls_retHeader) Then
        ' no 200 response
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "No response"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 12, ms_Language_Code, "#SAP customer service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    
    If Not lo_XMLParam.TestContentType(ls_retHeader, "text/xml") Then
        ' unexpected return type
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "Unexpected content type"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 12, ms_Language_Code, "#SAP customer service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    
    Dim lo_retXML As Object
    Set lo_retXML = CreateObject("MSXML2.DOMDocument")
    If Not lo_retXML.loadXML(ls_retContent) Then
        ' unexpected return type
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "Error in reading XML"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 12, ms_Language_Code, "#SAP customer service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If


    ' display sales order data data
    Dim lo_XMLItem As Object
    
    Set lo_XMLItem = lo_retXML.selectSingleNode("/Return/RETURN")
    If (lo_XMLItem Is Nothing) Then
        Exit Function
    Else
        If StrComp("E", lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "TYPE"), vbTextCompare) = 0 Then
            Exit Function
        End If
    End If
    
    Set lo_XMLItem = lo_retXML.selectSingleNode("/Return/PE_COMPANYDATA")
    
    If Not (lo_XMLItem Is Nothing) Then
        at_SAPCustomerDetail.CustomerNumber = as_CUST_Code
        at_SAPCustomerDetail.Name = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "NAME")
        at_SAPCustomerDetail.City = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "CITY")
        at_SAPCustomerDetail.Street = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "STREET")
        at_SAPCustomerDetail.PostalCode = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "POSTL_COD1")
        at_SAPCustomerDetail.Phone = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "TEL1_NUMBR")
        at_SAPCustomerDetail.Fax = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "FAX_NUMBER")
        at_SAPCustomerDetail.CT_Code = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "COUNTRYISO")
        GetSAPCustomerDetail = True
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("GetSAPCustomerDetail")
End Function

Private Function GetSAPDocumentDetail(ByVal as_DocumentNumber As String, ByRef at_SAPDocumentDetail As SAPDocumentDetail) As Boolean
On Error GoTo ErrHandler
    
    Dim ls_retContent   As String
    Dim ls_retHeader    As String
    Dim lo_XMLParam     As New SvcXMLParam
    
    GetSAPDocumentDetail = False
    as_DocumentNumber = right("0000000000" & as_DocumentNumber, 10)
    If Not mo_Sys.CallWebservice(ms_UrlSalesOrder, C_SERVICE_USER, C_SERVICE_PASSW, "_orderNB=" & as_DocumentNumber, "application/x-www-form-urlencoded", "", ls_retContent, ls_retHeader) Then
        ' no service
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "No service"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 13, ms_Language_Code, "#SAP sales document service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    
    If Not lo_XMLParam.CheckHTTPResponse(ls_retHeader) Then
        ' no 200 response
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "No response"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 13, ms_Language_Code, "#SAP sales document service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    
    If Not lo_XMLParam.TestContentType(ls_retHeader, "text/xml") Then
        ' unexpected return type
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "Unexpected content type"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 13, ms_Language_Code, "#SAP sales document service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If
    
    Dim lo_retXML As Object
    Set lo_retXML = CreateObject("MSXML2.DOMDocument")
    If Not lo_retXML.loadXML(ls_retContent) Then
        ReDim ms_MsgInfo(0, 1)
        ms_MsgInfo(0, 0) = "$ErrorMsg$"
        ms_MsgInfo(0, 1) = "Error in reading XML"
        Call MsgBox(MsgText(C_MSG_ID_BASE + 13, ms_Language_Code, "#SAP sales order service call failed with error: $ErrorMsg$", ms_MsgInfo))
        Exit Function
    End If

    ' display sales order data data
    Dim lo_XMLItem As Object
    Set lo_XMLItem = lo_retXML.selectSingleNode("/Return/SALES_ORDERS/ROW")
    If Not (lo_XMLItem Is Nothing) Then
        at_SAPDocumentDetail.DocumentNumber = as_DocumentNumber
        at_SAPDocumentDetail.DocumentType = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "AUART")
        at_SAPDocumentDetail.DocumentDate = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "AUDAT")
        at_SAPDocumentDetail.CustomerNumber = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "KUNNR")
        at_SAPDocumentDetail.CreationDate = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "ERDAT")
        at_SAPDocumentDetail.CreationTime = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "ERZET")
        at_SAPDocumentDetail.DocumentCategory = lo_XMLParam.GetXMLNodeValue(lo_XMLItem, "VBTYP")
        GetSAPDocumentDetail = True
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("GetSAPDocumentDetail")
End Function

' Return the result of a SQL request
' Convert SQL runtime errors and process errors to VB Error
#If ENV = LIVE Then
Private Function OpenSQLSafe(ByVal ao_DB As Object, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#Else
Private Function OpenSQLSafe(ByVal ao_DB As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#End If

On Error GoTo ErrHandler

    Dim lc_Data As Long
    lc_Data = ao_DB.OpenSQL(as_Request)
    
    If lc_Data = 0 Then
        Err.Raise ArmErr.SQLFailure, "SQL : " & as_Request, Join(ao_DB.SQLErrorCodes, SEP2) & SEP1 & Join(ao_DB.SQLErrorMessages, SEP2)
    End If
    
    If al_RowExpectedCount <> -1 Then
        ' Then check the rowcount
        If ao_DB.RowCount(lc_Data) <> al_RowExpectedCount Then
            Err.Raise ArmErr.SQLBadRowExpectedCount, "SQL : " & as_Request, al_RowExpectedCount & "<>" & ao_DB.RowCount(lc_Data)
        End If
    End If

    OpenSQLSafe = lc_Data

    Exit Function

ErrHandler:

    Call ErrorHandler("OpenSQLSafe")

End Function


' Execute a SQL request returning no data
' Convert SQL runtime errors and process errors to VB Error
' Params:
' ao_Db (Object)
' as_Request (String)
' al_RowAffectedCount (String)
#If ENV = LIVE Then
Private Sub ExecuteSQLSafe(ByVal ao_DB As Object, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#Else
Private Sub ExecuteSQLSafe(ByVal ao_DB As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1, Optional ab_DuplicityCheck As Boolean = False)
#End If
On Error GoTo ErrHandler

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

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

    Exit Sub

ErrHandler:
    Call ErrorHandler("ExecuteSQLSafe")
End Sub

Private Function GetDbError(ByVal lo_Db As ARMSYSCOMLib.ArmDb) As String
On Error GoTo ErrHandler
    
    If IsArray(lo_Db.SQLErrorMessages) Then
        Debug.Assert (IsArray(mo_Db.SQLErrorCodes))
        ' Display errors msgBox
        GetDbError = Join(lo_Db.SQLErrorCodes, ",") & vbCrLf & Join(lo_Db.SQLErrorMessages, vbCrLf)
    Else
        ' ExecuteSQL failed but no error message?
        GetDbError = "Unknown error"
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("GetDbError()")
End Function
' Standard error handler
Private Sub ErrorHandler(ByVal as_Fct As String)
  
    Call Err.Raise(Err.Number, as_Fct & SEP1 & Err.Source, Err.Description)
End Sub

' display standard error message
Private Sub ErrorMessage(ByVal as_Fct As String)
    Dim ls_ErrSource As String
    Dim ls_ErrDescription As String
    ls_ErrSource = as_Fct & SEP1 & Err.Source
    ls_ErrDescription = Err.Description
    
    Call LogMessage(SCREEN_NAME & " exception raised. Err.Number:" & Err.Number & ", Err.Source:" & ls_ErrSource & ", Err.Description " & ls_ErrDescription & ".", "E", False)
    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

' logs message to database
Private Sub LogMessage(ByVal as_logMsg As String, Optional ByVal as_logType As String = "E", Optional ab_ExitOnException As Boolean = False)
    Dim ll_errNumber As Long
    Dim ls_ErrDescription As String, ls_ErrSource As String
    
    ll_errNumber = Err.Number
    ls_ErrDescription = Err.Description
    ls_ErrSource = Err.Source

On Error GoTo ErrHandler

Const LOG_REQUEST As String = "EXEC A_log_ins $UCODE$,$LOGTYPE$,$MSG$,$APP$"
    Dim ls_Req As String
    Dim ll_Cursor As Long
    Dim ls_Source As String, ls_Msg As String
    
    ls_Source = SCREEN_NAME & " " & App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    ls_Msg = as_logMsg
    
    ls_Req = ReplacePlaceHolder(LOG_REQUEST, "$UCODE$", CStr(ml_U_code))
    ls_Req = ReplacePlaceHolder(ls_Req, "$LOGTYPE$", SQLStr(as_logType))
    ls_Req = ReplacePlaceHolder(ls_Req, "$MSG$", Left(Trim(SQLStr(ls_Msg)), 4000))
    ls_Req = ReplacePlaceHolder(ls_Req, "$APP$", Left(Trim(SQLStr(ls_Source)), 50))
    
    Call ExecuteSQLSafe(mo_Db, ls_Req)
    
    Err.Number = ll_errNumber
    Err.Description = ls_ErrDescription
    Err.Source = ls_ErrSource
    Exit Sub
    
ErrHandler:
    If ab_ExitOnException Then
        Call MsgBox("A fatal error occured. Unable to log error into database, the application will be close. Please report the following message to your IT support: " & vbCrLf & _
            "Number:" & Err.Number & vbCrLf & "Description:" & Err.Description, vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
        End
    End If
    Err.Number = ll_errNumber
    Err.Description = ls_ErrDescription
    Err.Source = ls_ErrSource
End Sub


' procedure save/restore err object
Private Sub UpdateError(Optional ab_saveError As Boolean = False)
Static ls_ErrDesc As String
Static ls_ErrSource As String
Static ll_errnum As Long
    
    If ab_saveError Then
        ls_ErrDesc = Err.Description
        ls_ErrSource = Err.Source
        ll_errnum = Err.Number
    Else
        Err.Description = ls_ErrDesc
        Err.Source = ls_ErrSource
        Err.Number = ll_errnum
    End If
End Sub

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

Private Function BeginTran(as_Tran As String) As Boolean

On Error GoTo ErrHandler
    BeginTran = False
    ExecuteSQLSafe mo_Db, "BEGIN TRANSACTION " & as_Tran

    BeginTran = True
    Exit Function
    
ErrHandler:
    'try to log error
    Call ErrorMessage("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", vbCritical, 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
    ExecuteSQLSafe mo_Db, "COMMIT TRANSACTION " & as_Tran

    CommitTran = True
    Exit Function
    
ErrHandler:
    'try to log error
    Call ErrorMessage("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", vbCritical, 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
    
    ExecuteSQLSafe mo_Db, "ROLLBACK TRANSACTION " & as_Tran


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

    RollbackTran = True
    Exit Function
    
ErrHandler:
    'try to log error
    Call ErrorMessage("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", vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    End
End Function

Private Function SqlInt(ByVal av_Data As Variant) As String
On Error GoTo ErrHandler

    SqlInt = "NULL"
    If IsNull(av_Data) Then av_Data = ""
    If Trim(CStr(av_Data)) <> "" Then
        SqlInt = CStr(av_Data)
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("SqlInt")
End Function

Private Function SqlDbl(ByVal av_Data As Variant) As String
On Error GoTo ErrHandler

    SqlDbl = "NULL"
    If IsNull(av_Data) Then av_Data = ""
    If Trim(CStr(av_Data)) <> "" Then
        SqlDbl = Str(av_Data)
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("SqlDbl")
End Function

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

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

Private Function SQLDateTime(ByVal av_Data As Variant) As String
On Error GoTo ErrHandler

    SQLDateTime = "NULL"
    If IsNull(av_Data) Then av_Data = ""
    If (Trim(CStr(av_Data)) <> "") And (CStr(av_Data) <> "0") Then
        SQLDateTime = "'" & Format(av_Data, "yyyy-mm-dd hh:mm:ss") & "'"
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("SqlDateTime")
End Function

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

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

Private Function GetComboKey(ByVal ao_Combo As ArmCombobox) As String
On Error GoTo ErrHandler

    GetComboKey = ""
    If Not (ao_Combo.SelectedItem Is Nothing) Then
        GetComboKey = Trim(CStr(ao_Combo.SelectedItem.Key))
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("GetComboKey")
End Function

Private Function ReplacePlaceHolder(ByVal as_Request As String, ByVal as_PlaceHolder As String, ByVal as_DefaultValue As String) As String
On Error GoTo ErrHandler
    
    ReplacePlaceHolder = Replace(as_Request, as_PlaceHolder, as_DefaultValue, , , vbTextCompare)
    Exit Function
ErrHandler:
    Call ErrorHandler("ReplacePlaceholder")
End Function


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

Private Function GetCodePageFromLanguage(ByRef ao_Armdb As Object, ByVal as_Language As String) As Long
On Error GoTo ErrHandler
Const C_REQ As String = "SELECT Code_Page FROM Language WHERE Language_Code = '$Language_Code$'"
    Dim ls_Req As String
    Dim ll_Cursor As Long
    Dim ll_codePage As Long
    
    ls_Req = ReplacePlaceHolder(C_REQ, "$Language_Code$", as_Language)

    ll_Cursor = OpenSQLSafe(ao_Armdb, ls_Req)
    Debug.Assert (ll_Cursor <> 0)
    
    ll_codePage = CLng(ao_Armdb.GetFields(ll_Cursor, "Code_Page"))
    Call ao_Armdb.Close(ll_Cursor)
    GetCodePageFromLanguage = ll_codePage
    Exit Function
    
ErrHandler:
    If ll_Cursor <> 0 Then Call ao_Armdb.Close(ll_Cursor)
    Call ErrorHandler("GetCodePageFromLanguage()")
End Function

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

On Error GoTo ErrHandler

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

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

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

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

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

CleanUp:

End Function

Private Function GetLabel(ByVal as_FieldName As String, ByVal as_Default As String) As String
On Error GoTo ErrHandler

    If mo_Db.Find(mc_ScreenLabels, "FIELD_NAME", as_FieldName, , 1) >= 0 Then
        GetLabel = mo_Db.GetFields(mc_ScreenLabels, "LOCAL_TEXT")
    Else
        GetLabel = as_Default
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler("ChangeCharset")
End Function

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

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

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

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

    MsgText = ""
    
    Dim lRequest As String
    lRequest = ReplacePlaceHolder(DB_REQ, "$id$", aID)
    lRequest = ReplacePlaceHolder(lRequest, "$lang$", aLang)
    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.", vbCritical, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision)
    MsgText = aDefault
End Function

Private Function GetSequenceCode(as_SequenceName As String) As Long
On Error GoTo ErrHandler

Dim ls_Sequence As String
Dim ls_Message As String
Dim lv_SqlCodes As Variant, lv_SqlMessages As Variant

    'get new sequence number
    ls_Sequence = mo_Db.SQLNextID(as_SequenceName)
    If ls_Sequence = "" Then
        lv_SqlCodes = mo_Db.SQLErrorCodes
        lv_SqlMessages = mo_Db.SQLErrorMessages
        If IsArray(lv_SqlMessages) Then
            ls_Message = Join(lv_SqlMessages, ",")
        End If
        Err.Raise ArmErr.CompFncFailed, "SQLNextID", ls_Message & " - " & as_SequenceName
    End If
    GetSequenceCode = Val(ls_Sequence)
    Exit Function
ErrHandler:
    Call ErrorHandler("GetSequenceCode")
End Function

Private Function TestVersion(ByVal as_version As String) As Boolean
On Error GoTo ErrHandler
    
    TestVersion = (GetAConfigData(mo_Db, "EAS_Version") = as_version)
    Exit Function
ErrHandler:
    Call ErrorHandler("TestVersion")
End Function

Private Function GetU_Code(ByVal as_LoginName As String) As Long
On Error GoTo ErrHandler
    Dim lc_Cursor As Long
    Dim ls_Request As String
    
    GetU_Code = 0
    ls_Request = "SELECT U_Code FROM gen_systems_users WHERE U_login_name = $LoginName$"
    ls_Request = ReplacePlaceHolder(ls_Request, "$LoginName$", SQLStr(as_LoginName))
    lc_Cursor = OpenSQLSafe(mo_Db, ls_Request)
    If mo_Db.RowCount(lc_Cursor) = 1 Then
        GetU_Code = mo_Db.GetFields(lc_Cursor, "U_Code")
    End If
    Call mo_Db.Close(lc_Cursor)
    Exit Function
ErrHandler:
    Call mo_Db.Close(lc_Cursor)
    Call ErrorHandler("GetU_Code")
End Function

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

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

Private Function GetAConfigData(ByRef ao_DB As ArmDb, ByVal as_Key As String) As String
On Error GoTo ErrHandler
    
    Const C_REQ As String = "SELECT CFG_Value FROM A_Config WHERE CFG_Key='$KEY$'"
    Dim ll_Cursor As Long
    
    ll_Cursor = OpenSQLSafe(ao_DB, Replace(C_REQ, "$KEY$", as_Key, , , vbTextCompare))
    
    If ao_DB.RowCount(ll_Cursor) = 1 Then
        GetAConfigData = ao_DB.GetFields(ll_Cursor, "CFG_Value")
    Else
        Call ao_DB.Close(ll_Cursor)
        Err.Raise ArmErr.CompFncFailed, "OpenSQLSafe", "A_Config value missing : " & as_Key
    End If
    Call ao_DB.Close(ll_Cursor)
    
    Exit Function
ErrHandler:
    Call ao_DB.Close(ll_Cursor)
    Call ErrorHandler("GetAConfigData")
End Function

Private Function GetTempDir() As String
On Error GoTo ErrHandler

Dim ls_Buff As String, ll_Count As Long

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

Private Sub DeleteTemporaryFiles()
On Error GoTo ErrHandler

  ' delete all subfolders and files in one go
  Call mo_FSO.DeleteFolder(GetTempDir, True)
  Exit Sub
ErrHandler:
  'do nothing this is not critical error, because some of the temp files can be still open
  'by user, it will be delete next time dfa start
End Sub


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

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

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

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


