VERSION 5.00
Begin VB.UserControl SRM_Task 
   ClientHeight    =   11595
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   14610
   ScaleHeight     =   11595
   ScaleWidth      =   14610
   Begin VB.Frame fra_Detail 
      Height          =   10695
      Left            =   60
      TabIndex        =   11
      Tag             =   "fra_Detail"
      Top             =   810
      Width           =   13425
      Begin VB.TextBox txt_SV_City 
         Height          =   300
         Left            =   12960
         TabIndex        =   62
         Top             =   2640
         Visible         =   0   'False
         Width           =   315
      End
      Begin VB.Frame fra_manipulation 
         Caption         =   "#Manipulation"
         Height          =   1590
         Left            =   6720
         TabIndex        =   48
         Tag             =   "frm_maintenance"
         Top             =   510
         Width           =   6570
         Begin VB.CheckBox chk_dropped 
            Caption         =   "#Dropped"
            Height          =   255
            Left            =   3870
            TabIndex        =   54
            Tag             =   "chk_dropped"
            Top             =   1170
            Width           =   1515
         End
         Begin VB.TextBox txt_dropDate 
            Alignment       =   2  'Center
            Enabled         =   0   'False
            Height          =   330
            Left            =   1740
            TabIndex        =   53
            Tag             =   "txt_dropDate"
            Text            =   "02/02/2001"
            Top             =   1132
            Width           =   1095
         End
         Begin VB.TextBox txt_updUser 
            Enabled         =   0   'False
            Height          =   330
            Left            =   3870
            TabIndex        =   52
            Tag             =   "txt_updUser"
            Text            =   "L. Cockayne"
            Top             =   742
            Width           =   2415
         End
         Begin VB.TextBox txt_lastUpd 
            Alignment       =   2  'Center
            Enabled         =   0   'False
            Height          =   330
            Left            =   1740
            TabIndex        =   51
            Tag             =   "txt_lastUpd"
            Text            =   "02/02/2001"
            Top             =   742
            Width           =   1095
         End
         Begin VB.TextBox txt_creator 
            Enabled         =   0   'False
            Height          =   330
            Left            =   3870
            TabIndex        =   50
            Tag             =   "txt_creator"
            Text            =   "L. Cockayne"
            Top             =   322
            Width           =   2415
         End
         Begin VB.TextBox txt_Date 
            Alignment       =   2  'Center
            Enabled         =   0   'False
            Height          =   330
            Left            =   1740
            TabIndex        =   49
            Tag             =   "txt_Date"
            Text            =   "02/02/2001"
            Top             =   322
            Width           =   1095
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Drop date"
            Height          =   255
            Index           =   15
            Left            =   150
            TabIndex        =   59
            Tag             =   "lbl_dropDate"
            Top             =   1170
            Width           =   1530
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#By"
            Height          =   255
            Index           =   14
            Left            =   3150
            TabIndex        =   58
            Tag             =   "lbl_By"
            Top             =   720
            Width           =   690
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Last updade"
            Height          =   255
            Index           =   13
            Left            =   150
            TabIndex        =   57
            Tag             =   "lbl_dateUpd"
            Top             =   780
            Width           =   1530
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#By"
            Height          =   255
            Index           =   12
            Left            =   3150
            TabIndex        =   56
            Tag             =   "lbl_By"
            Top             =   360
            Width           =   690
         End
         Begin VB.Label lbl_labels 
            Caption         =   "#Creation date"
            Height          =   255
            Index           =   11
            Left            =   150
            TabIndex        =   55
            Tag             =   "lbl_date"
            Top             =   360
            Width           =   1530
         End
      End
      Begin VB.TextBox txt_User_Owned_Code 
         Height          =   300
         Left            =   11055
         TabIndex        =   47
         Top             =   225
         Visible         =   0   'False
         Width           =   315
      End
      Begin VB.TextBox txt_User_Owned 
         Height          =   300
         Left            =   8625
         TabIndex        =   2
         Top             =   180
         Width           =   2595
      End
      Begin VB.TextBox txt_Date_Comp 
         Height          =   300
         Left            =   4410
         TabIndex        =   46
         Top             =   1410
         Visible         =   0   'False
         Width           =   630
      End
      Begin VB.TextBox txt_SRTS_Id 
         Height          =   300
         Left            =   3795
         TabIndex        =   45
         Top             =   1365
         Visible         =   0   'False
         Width           =   330
      End
      Begin VB.Frame fra_Action 
         Caption         =   "#Actions"
         Height          =   2190
         Left            =   135
         TabIndex        =   42
         Tag             =   "fra_Actions"
         Top             =   8415
         Width           =   13200
         Begin Project1.ToolbarControl tlb_Action 
            Height          =   1890
            Left            =   12405
            TabIndex        =   26
            Top             =   135
            Width           =   690
            _ExtentX        =   1217
            _ExtentY        =   3334
         End
         Begin Project1.ArmGrid grd_Action 
            Height          =   1815
            Left            =   45
            TabIndex        =   25
            Top             =   255
            Width           =   12240
            _ExtentX        =   21590
            _ExtentY        =   3201
         End
      End
      Begin VB.TextBox txt_Desc 
         Height          =   960
         Left            =   105
         MaxLength       =   1000
         TabIndex        =   22
         Top             =   7425
         Width           =   6915
      End
      Begin VB.Frame fra_Attachment 
         Caption         =   "#Attachments"
         Height          =   2805
         Left            =   7155
         TabIndex        =   41
         Tag             =   "fra_Attachments"
         Top             =   5580
         Width           =   6135
         Begin Project1.ToolbarControl tlb_Attachment 
            Height          =   2475
            Left            =   5325
            TabIndex        =   24
            Top             =   195
            Width           =   690
            _ExtentX        =   1217
            _ExtentY        =   4366
         End
         Begin Project1.ArmGrid grd_Attachment 
            Height          =   2445
            Left            =   45
            TabIndex        =   23
            Tag             =   "grd_Attachment"
            Top             =   240
            Width           =   5190
            _ExtentX        =   9155
            _ExtentY        =   4313
         End
      End
      Begin VB.TextBox txt_SRT_Summary 
         Height          =   300
         Left            =   2130
         MaxLength       =   80
         TabIndex        =   21
         Top             =   7065
         Width           =   4845
      End
      Begin VB.TextBox txt_actCostOther 
         Height          =   300
         Left            =   5805
         MaxLength       =   15
         TabIndex        =   18
         Top             =   5910
         Width           =   1170
      End
      Begin VB.TextBox txt_est_costOther 
         Height          =   300
         Left            =   5805
         MaxLength       =   15
         TabIndex        =   16
         Top             =   5550
         Width           =   1170
      End
      Begin VB.TextBox txt_actCost 
         Height          =   300
         Left            =   2130
         MaxLength       =   15
         TabIndex        =   17
         Top             =   5910
         Width           =   1185
      End
      Begin VB.TextBox txt_estCost 
         Height          =   300
         Left            =   2130
         MaxLength       =   15
         TabIndex        =   15
         Top             =   5550
         Width           =   1185
      End
      Begin Project1.ArmPicker pck_vendor 
         Height          =   300
         Left            =   9150
         TabIndex        =   10
         Top             =   2220
         Width           =   4110
         _ExtentX        =   7250
         _ExtentY        =   529
      End
      Begin VB.TextBox txt_Status 
         Height          =   300
         Left            =   1785
         TabIndex        =   8
         Top             =   2220
         Width           =   1800
      End
      Begin VB.TextBox txt_Reference2 
         Height          =   300
         Left            =   1785
         MaxLength       =   30
         TabIndex        =   7
         Top             =   1785
         Width           =   1800
      End
      Begin VB.TextBox txt_Reference1 
         Height          =   300
         Left            =   1785
         MaxLength       =   30
         TabIndex        =   6
         Top             =   1410
         Width           =   1800
      End
      Begin VB.TextBox txt_Key 
         Height          =   330
         Left            =   11505
         TabIndex        =   3
         Top             =   180
         Width           =   1785
      End
      Begin Project1.ArmCombobox cbo_Plant 
         Height          =   345
         Left            =   1785
         TabIndex        =   1
         Top             =   180
         Width           =   4455
         _ExtentX        =   7858
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Priority 
         Height          =   345
         Left            =   5085
         TabIndex        =   9
         Top             =   2205
         Width           =   1875
         _ExtentX        =   3307
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Reason 
         Height          =   345
         Left            =   1785
         TabIndex        =   5
         Top             =   960
         Width           =   4455
         _ExtentX        =   7858
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Action 
         Height          =   345
         Left            =   2130
         TabIndex        =   20
         Top             =   6645
         Width           =   4725
         _ExtentX        =   8334
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_currency 
         Height          =   345
         Left            =   2130
         TabIndex        =   19
         Top             =   6255
         Width           =   4725
         _ExtentX        =   8334
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_result 
         Height          =   345
         Left            =   1770
         TabIndex        =   12
         Top             =   2625
         Width           =   4560
         _ExtentX        =   8043
         _ExtentY        =   609
      End
      Begin VB.Frame fra_Product 
         Caption         =   "#Products"
         Height          =   2190
         Left            =   105
         TabIndex        =   34
         Tag             =   "fra_Products"
         Top             =   3285
         Width           =   13185
         Begin Project1.ToolbarControl tlb_Product 
            Height          =   1890
            Left            =   12390
            TabIndex        =   14
            Top             =   180
            Width           =   690
            _ExtentX        =   1217
            _ExtentY        =   3334
         End
         Begin Project1.ArmGrid grd_product 
            Height          =   1815
            Left            =   45
            TabIndex        =   13
            Top             =   255
            Width           =   12270
            _ExtentX        =   21643
            _ExtentY        =   3201
         End
         Begin VB.Label lbl_Label 
            Caption         =   "#Products Grid"
            Height          =   240
            Index           =   17
            Left            =   120
            TabIndex        =   63
            Tag             =   "lbl_Products"
            Top             =   0
            Visible         =   0   'False
            Width           =   1665
         End
      End
      Begin Project1.ArmPicker pck_assignedTo 
         Height          =   300
         Left            =   1800
         TabIndex        =   4
         Top             =   600
         Width           =   4455
         _ExtentX        =   7858
         _ExtentY        =   529
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#User_Owned"
         Height          =   240
         Index           =   2
         Left            =   6675
         TabIndex        =   61
         Tag             =   "lbl_UserOwned"
         Top             =   225
         Width           =   1935
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Result"
         Height          =   240
         Index           =   1
         Left            =   90
         TabIndex        =   60
         Tag             =   "lbl_Result"
         Top             =   2670
         Width           =   1605
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Vendor"
         Height          =   240
         Index           =   8
         Left            =   7410
         TabIndex        =   33
         Tag             =   "lbl_Vendor"
         Top             =   2235
         Width           =   1725
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Currency"
         Height          =   240
         Index           =   16
         Left            =   105
         TabIndex        =   44
         Tag             =   "lbl_currency"
         Top             =   6330
         Width           =   1770
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Assigned to"
         Height          =   240
         Index           =   15
         Left            =   90
         TabIndex        =   43
         Tag             =   "lbl_AssignedTo"
         Top             =   675
         Width           =   1665
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Summary"
         Height          =   240
         Index           =   14
         Left            =   105
         TabIndex        =   40
         Tag             =   "lbl_Summary"
         Top             =   7035
         Width           =   1725
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Action"
         Height          =   240
         Index           =   13
         Left            =   105
         TabIndex        =   39
         Tag             =   "lbl_action"
         Top             =   6705
         Width           =   1770
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Actual other cost"
         Height          =   240
         Index           =   12
         Left            =   3660
         TabIndex        =   38
         Tag             =   "lbl_ActOtherCosts"
         Top             =   5940
         Width           =   1725
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Estimated other cost"
         Height          =   240
         Index           =   11
         Left            =   3660
         TabIndex        =   37
         Tag             =   "lbl_EstOtherCosts"
         Top             =   5655
         Width           =   1725
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Actual material cost"
         Height          =   240
         Index           =   10
         Left            =   105
         TabIndex        =   36
         Tag             =   "lbl_ActMatCosts"
         Top             =   5940
         Width           =   1725
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Estimated material cost"
         Height          =   240
         Index           =   9
         Left            =   105
         TabIndex        =   35
         Tag             =   "lbl_EstMatCosts"
         Top             =   5580
         Width           =   1725
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Status"
         Height          =   240
         Index           =   7
         Left            =   90
         TabIndex        =   32
         Tag             =   "lbl_Status"
         Top             =   2235
         Width           =   1605
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Reference 2"
         Height          =   240
         Index           =   6
         Left            =   90
         TabIndex        =   31
         Tag             =   "lbl_Ref2"
         Top             =   1815
         Width           =   1665
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Reference 1"
         Height          =   240
         Index           =   5
         Left            =   90
         TabIndex        =   30
         Tag             =   "lbl_Ref1"
         Top             =   1440
         Width           =   1665
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Reason"
         Height          =   240
         Index           =   4
         Left            =   90
         TabIndex        =   29
         Tag             =   "lbl_Reason"
         Top             =   1005
         Width           =   1665
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Priority"
         Height          =   240
         Index           =   3
         Left            =   3735
         TabIndex        =   28
         Tag             =   "lbl_Priority"
         Top             =   2235
         Width           =   1290
      End
      Begin VB.Label lbl_Label 
         Caption         =   "#Plant "
         Height          =   240
         Index           =   0
         Left            =   90
         TabIndex        =   27
         Tag             =   "lbl_Plant"
         Top             =   315
         Width           =   1665
      End
   End
   Begin Project1.ToolbarControl tlb_main 
      Height          =   690
      Left            =   75
      TabIndex        =   0
      Top             =   60
      Width           =   6885
      _ExtentX        =   12144
      _ExtentY        =   1217
   End
End
Attribute VB_Name = "SRM_Task"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

' **************************************************************************************************
' ************************************* EXTERNAL DECLARATIONS **************************************
' **************************************************************************************************
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) 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 Function LockWindowUpdate Lib "user32" (ByVal hwnd As Long) As Long
' **************************************************************************************************

' **************************************************************************************************
' **************************************** TOOL CONSTANTS ******************************************
' **************************************************************************************************
Private Const LOCALE_USER_DEFAULT = &H400
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 SEP1 As String = "®"
Private Const SEP2 As String = "©"
Private Const SEP As String = SEP1 + SEP2
Private Const C_APPNAME As String = "SRM_TASK"              ' for error log
Private Const C_SCREENNAME As String = "SRM_Task"           ' for loading screen constants
Private Const C_SCREENMODE_STACK_SIZE As Long = 5           ' size of stack for active screens
Private Const C_TOOLBARFACE_ITEM_VIEW As String = "0"
Private Const C_TOOLBARFACE_ITEM_ADD As String = "1"
Private Const C_TOOLBARFACE_ITEM_UPD As String = "2"
Private Const C_TOOLBARFACE_ITEM_DEL As String = "3"
Private Const SIFYB_CM_ERROR_MESSAGE = 2400                 ' const for base of error messages ids
Private Const C_ID_KEY = "SRM_Task"                         ' A_ID entry for new record
Private Const C_ID_KEY_TP = "SRM_TaskProduct"               ' A_ID entry for new record
Private Const C_ID_KEY_AT = "SRM_Attachement"               ' A_ID entry for new record
Private Const C_ID_KEY_AC = "SRM_Action"                    ' A_ID entry for new record
' ****************************************** TOOL CONSTANTS ***************************************

' **************************************************************************************************
' **************************************** USER DEFINED ERRORS *************************************
' **************************************************************************************************
Private Enum ArmErr
    DBCnxFailed = vbObjectError + 1             ' Unable to connect to the database
    CPTAlreadyInitialized = vbObjectError + 2   ' We try to initialize a component that is already initialized
    CPTNotInitialized = vbObjectError + 3       ' We try to use or free that is not initialized yet
    InvalidArgument = vbObjectError + 4
    PropertyNotSet = vbObjectError + 5
    CompFncFailed = vbObjectError + 6           ' when component function fail
    QuietException = vbObjectError + 7          ' do not display error message
    WarMsgSelectRow = vbObjectError + 8
    SQLBadRowAffectedCount = vbObjectError + 9  ' A SQL request has not affected the expected rowcount (ex: one Update do nothing)
    SQLBadRowExpectedCount = vbObjectError + 10 ' A SQL request does not return the expected rowcount : select an item return nothing...
End Enum

Private Enum ErrMsg
    ErrMsgNone = 0
    ErrMsgMandatoryAreEmpty = SIFYB_CM_ERROR_MESSAGE + 1
    ErrMsgDuplicateOrder = SIFYB_CM_ERROR_MESSAGE + 2
    ErrMsgDuplicateLevel = SIFYB_CM_ERROR_MESSAGE + 3
    ErrMsgMissingLevel = SIFYB_CM_ERROR_MESSAGE + 4
    ErrMsgNumericRequired = SIFYB_CM_ERROR_MESSAGE + 5
    ErrMsgItemIsDeleted = SIFYB_CM_ERROR_MESSAGE + 19
    ErrMsgPlanNotSelected = SIFYB_CM_ERROR_MESSAGE + 20
    ErrMsgItemAlreadyInGrid = SIFYB_CM_ERROR_MESSAGE + 21
    ErrMsgActionInProgress = SIFYB_CM_ERROR_MESSAGE + 22
    ErrMsgActionIsCompleted = SIFYB_CM_ERROR_MESSAGE + 23
    QueMsgActionIsCompleted = SIFYB_CM_ERROR_MESSAGE + 24
    ErrMsgVendorNotSelected = SIFYB_CM_ERROR_MESSAGE + 25
    QueMsgUpdateCompletedTask = SIFYB_CM_ERROR_MESSAGE + 26
    ErrMsgUpdateDeletedTask = SIFYB_CM_ERROR_MESSAGE + 27
End Enum

' *************************************** USER DEFINED ERRORS **************************************

' **************************************************************************************************
' *************************************** CONTROL MEMBERS ******************************************
' **************************************************************************************************
Dim ml_U_Code As Long                   ' if this is user loging app, needed to log errors into A_Log
Dim ms_LoginName As String
Dim ms_Language_Code As String
Dim mb_Initialized As Boolean           ' True if the component is already initialized
Dim mb_Initializing As Boolean          ' Flag of initializing
Dim mua_ActiveMode() As ArmScreenMode
Dim ms_Title As String                  ' title of user control - can be assigned as Caption to the parent form or title for printing
Dim ml_iConcurrency As Long             ' iconc of the record curently loaded
Dim ms_DecimalSeparator As String       ' decimal separator obtained from local settings
Dim ms_ThousandSeparator As String      'locale thousand separator

Dim moa_ListFieldsMandatory As Variant  ' all mandatory controls
Dim moa_ListFieldsNumeric As Variant    ' all numeric controls
Dim moa_ListFieldsToDisable() As Control            ' common disabled control

Dim ms_MFGP_CODE    As String
Dim ms_MFGP_name    As String
Dim ms_CurrentUser_Name As String

Private WithEvents mo_SRM_TaskProduct   As SRM_TaskProduct
Attribute mo_SRM_TaskProduct.VB_VarHelpID = -1
Private WithEvents mo_SRM_Action        As SRM_Action
Attribute mo_SRM_Action.VB_VarHelpID = -1
Private WithEvents mo_SRM_Attachment    As SRM_Attachment
Attribute mo_SRM_Attachment.VB_VarHelpID = -1

Private Enum ArmScreenMode
    smRefreshOnly
    smMain
    smAdd
    smUpdate
    smDelete
    smView
    smSubProduct
    smSubAttachement
    smSubAction
End Enum

Const C_ACTION_STATUS_COMPLETED As Long = 1

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

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

' *************************************** CONTROL MEMBERS ******************************************
Public Event OnExit()
Public Event OnItemAdd(ByVal av_Key As Variant, ByVal as_SrzFields As String, ByVal as_SzProductGrid As String)
Public Event OnItemUpdate(ByVal av_Key As Variant, ByVal as_SrzFields As String, ByVal as_SzProductGrid As String)
Public Event OnItemDelete(ByVal av_Key As Variant)
Public Event OnItemNext()
Public Event OnItemPrevious()
Public Event OnPrint(ByVal av_Key As Variant)


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


' mb_Initialized is a read-only property, indicates the status of the component
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 Let Visible(ByVal aVisible As Boolean)
    UserControl.Extender.Visible = aVisible
End Property
Public Property Get Initialized() As Boolean
    Initialized = mb_Initialized
End Property
Public Sub Zorder()
  Call UserControl.Extender.Zorder
End Sub
Public Property Let U_Code(ByVal al_U_Code As Long)
On Error GoTo ErrHandler
    
    If Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    
    ml_U_Code = al_U_Code
    Exit Property
ErrHandler:
    Call ErrorHandler(Extender.Name & ".U_Code(Let)")
End Property

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

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

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

Public Property Get Title() As String
    Title = ms_Title
End Property

Public Sub Run(ByVal ae_ScrMode As SRM_Mode, ByVal av_Key As Variant)
On Error GoTo ErrHandler

    Debug.Assert (mb_Initialized = True)
    
    Call LockScreen(True)       'JN: i am not sure if this is necessary if called from other control which already locked the screen
    
    Select Case ae_ScrMode
        Case SRM_Mode.emView
            Call Item_ViewInit(av_Key)
        Case SRM_Mode.emAdd
            Call Item_AddInit
        Case SRM_Mode.emUpdate
            Call Item_UpdateInit(av_Key)
        Case SRM_Mode.emDelete
            Call Item_DeleteInit(av_Key)
            
    End Select
    
    Call LockScreen(False)
    
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage(Extender.Name & ".Run")
End Sub

Public Sub Load_A_COM()
Dim lo_Control As Object
On Error GoTo ErrHandler
    If Initialized Then Call Err.Raise(ArmErr.CPTAlreadyInitialized)
    If mo_Db Is Nothing Then Call Err.Raise(ArmErr.PropertyNotSet, "", "mo_Db")
    If Len(ms_Language_Code) < 1 Then Call Err.Raise(ArmErr.PropertyNotSet, "", "ms_Language_Code")
    
    ' get decimal separator for conversion from string to double
    ms_DecimalSeparator = Format(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

    ' Set Db
    ' Call Load_A_Com
    ' Initialize toolbars
    Debug.Assert (Not mo_Db Is Nothing)
    
    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
            lo_Control.Locked = True
        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
    
    Set mo_FSO = CreateObject("Scripting.FileSystemObject")
    
    ms_MFGP_CODE = ""
    ms_MFGP_name = ""
    ms_CurrentUser_Name = ""
    Call LoadUserInfo(mo_Db, ml_U_Code)
    
    ReDim Preserve mua_ActiveMode(0)
    mua_ActiveMode(UBound(mua_ActiveMode)) = ArmScreenMode.smMain

    ' init controls
    Call Components_Settings
    
    ReDim moa_ListFieldsMandatory(0 To 7) As Variant
    moa_ListFieldsMandatory(0) = Array(cbo_Plant, 0)
    moa_ListFieldsMandatory(1) = Array(cbo_Reason, 4)
    moa_ListFieldsMandatory(2) = Array(cbo_Priority, 3)
    moa_ListFieldsMandatory(3) = Array(cbo_Action, 13)
    moa_ListFieldsMandatory(4) = Array(txt_SRT_Summary, 14)
    moa_ListFieldsMandatory(5) = Array(pck_vendor, 8)
    moa_ListFieldsMandatory(6) = Array(cbo_currency, 16)
    moa_ListFieldsMandatory(7) = Array(grd_product, 17)
'    moa_ListFieldsMandatory(8) = Array(txt_assignedTo, 15)
    
    ReDim moa_ListFieldsNumeric(0 To 3) As Variant
    moa_ListFieldsNumeric(0) = Array(txt_estCost, 9)
    moa_ListFieldsNumeric(1) = Array(txt_est_costOther, 11)
    moa_ListFieldsNumeric(2) = Array(txt_actCost, 10)
    moa_ListFieldsNumeric(3) = Array(txt_actCostOther, 12)
    
    InitMandatoryLabels (moa_ListFieldsMandatory)
    fra_Product.Font.Bold = True

    Call FillControlArray(moa_ListFieldsToDisable, Array(txt_Key, pck_assignedTo, txt_User_Owned, txt_Status, txt_Date, txt_creator, txt_lastUpd, txt_updUser, txt_dropDate, chk_dropped))
    
    Call InitComponents
    
    Call LoadLabels(UserControl.Controls, C_SCREENNAME, ms_Language_Code)
    Call ChangeCharset(UserControl.Controls, GetCodePageFromLanguage(mo_Db, ms_Language_Code))
    
    ' set layout
    Call InitCtrlSize
    
    mb_Initialized = True

    ' display starting face
    Call UpdateUI(ArmScreenMode.smMain)
    
    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".Load_A_Com()")
End Sub

' init plant ....
Private Sub LoadUserInfo(ByRef ao_Armdb As Object, ByVal al_U_Code As Long)
On Error GoTo ErrHandler
Const C_REQ As String = "SELECT TOP 1 GP.P_First_Name + ' ' + GP.P_Name AS P_USER_NAME, MFGP.MFGP_Code, MFGP.MFGP_name FROM Gen_Systems_Users GSU INNER JOIN Gen_People GP ON GP.P_Code=GSU.P_Code INNER JOIN Plants MFGP ON MFGP.U_Code=GSU.U_CODE AND MFGP.Language_Code='$Language_Code$' WHERE GSU.U_Code=$U_Code$"

Dim ls_req As String
Dim ll_cursor As Long
    
    ls_req = ReplacePlaceHolder(C_REQ, "$U_Code$", al_U_Code)
    ls_req = ReplacePlaceHolder(ls_req, "$Language_Code$", ms_Language_Code)
    ll_cursor = OpenSQLSafe(ao_Armdb, ls_req)
    ms_MFGP_CODE = ao_Armdb.GetFields(ll_cursor, "MFGP_CODE")
    ms_MFGP_name = ao_Armdb.GetFields(ll_cursor, "MFGP_name")
    ms_CurrentUser_Name = ao_Armdb.GetFields(ll_cursor, "P_USER_NAME")
    Call ao_Armdb.Close(ll_cursor)
    Exit Sub
    
ErrHandler:
    If ll_cursor <> 0 Then Call ao_Armdb.Close(ll_cursor)
    Call ErrorHandler("LoadUserInfo()")
End Sub

Private Sub FillControlArray(ByRef ao_ctrlArray() As Control, ByRef ao_array As Variant)
On Error GoTo ErrHandler
    Dim ll_i As Long
    If Not IsArray(ao_array) Then
        Exit Sub
    End If
    
    ReDim ao_ctrlArray(LBound(ao_array) To UBound(ao_array)) As Control
    
    For ll_i = LBound(ao_array) To UBound(ao_array)
        Set ao_ctrlArray(ll_i) = ao_array(ll_i)
    Next

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

Public Sub Unload_A_COM()
Dim lo_Control As Object
On Error GoTo ErrHandler
    If Not Initialized Then Call Err.Raise(ArmErr.CPTNotInitialized)
    
    For Each lo_Control In UserControl.Controls
        Select Case UCase(TypeName(lo_Control))
        Case "ARMCOMBOBOX", "TOOLBARCONTROL", "ARMGRID", "ARMTREEVIEW", "ARMCHECKVIEW", "ARMPICKER", "SRM_TASKPRODUCT", "SRM_ACTION", "SRM_ATTACHMENT"
            Call lo_Control.Unload_A_COM
        End Select
    Next
    
    If Not mo_SRM_Action Is Nothing Then
        Call mo_SRM_Action.Unload_A_COM
        Set mo_SRM_Action = Nothing
    End If
    If Not mo_SRM_Attachment Is Nothing Then
        Call mo_SRM_Attachment.Unload_A_COM
        Set mo_SRM_Attachment = Nothing
    End If
    If Not mo_SRM_TaskProduct Is Nothing Then
        Call mo_SRM_TaskProduct.Unload_A_COM
        Set mo_SRM_TaskProduct = Nothing
    End If
    
    Set mo_Db = Nothing
    Set mo_FSO = Nothing

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".Unload_A_Com()")
End Sub

Private Sub Components_Settings()
On Error GoTo ErrHandler

    Call Component_SetUp(txt_Key, "SRT_Id" & SEP & "Num")
    
    Call Component_SetUp(cbo_Plant, "MFGP_code" & SEP & "MFGP_name")
    Call Component_SetUp(cbo_Priority, "SRTP_Id" & SEP & "SRTP_Desc")
    Call Component_SetUp(cbo_Reason, "SRE_Id" & SEP & "SRE_Desc")
    Call Component_SetUp(cbo_Action, "Action_ARef" & SEP & "Action_type")
    Call Component_SetUp(cbo_currency, "CURR_Code" & SEP & "CURR_Desc")
    Call Component_SetUp(cbo_result, "SRR_Id" & SEP & "SRR_Desc")
    
    
    Call Component_SetUp(txt_User_Owned, "User_Owned_Name" & SEP & "Text")
    Call Component_SetUp(pck_assignedTo, "User_Assigned" & SEP & "User_Assigned_Name")
    Call Component_SetUp(txt_Reference1, "Ref1" & SEP & "Text")
    Call Component_SetUp(txt_Reference2, "Ref2" & SEP & "Text")
    
    Call Component_SetUp(txt_Status, "SRTS_Desc" & SEP & "Text")
    Call Component_SetUp(pck_vendor, "SV_Id" & SEP & "SV_Name")
    Call Component_SetUp(txt_estCost, "Est_cost" & SEP & "Num")
    Call Component_SetUp(txt_est_costOther, "Est_costother" & SEP & "Num")
    Call Component_SetUp(txt_actCost, "Act_cost" & SEP & "Num")
    Call Component_SetUp(txt_actCostOther, "Act_costother" & SEP & "Num")
    Call Component_SetUp(txt_SRT_Summary, "SRT_Summary" & SEP & "Text")
    Call Component_SetUp(txt_Desc, "SRT_Description" & SEP & "Text")
    
    ' system controls
    Call Component_SetUp(txt_Date, "Z_Creation" & SEP & "Date")
    Call Component_SetUp(txt_lastUpd, "Z_Last_Upd" & SEP & "Date")
    Call Component_SetUp(txt_dropDate, "Drop_Date" & SEP & "Date")
    Call Component_SetUp(txt_creator, "Z_Creator_Name" & SEP & "Text")
    Call Component_SetUp(txt_updUser, "Z_Last_Upd_User_Name" & SEP & "Text")
    Call Component_SetUp(chk_dropped, "Drop_flag")
    
    'invisible textboxses
    Call Component_SetUp(txt_User_Owned_Code, "User_Owned" & SEP & "Num")
    Call Component_SetUp(txt_Date_Comp, "Date_comp" & SEP & "Date")
    Call Component_SetUp(txt_SRTS_Id, "SRTS_Id" & SEP & "Num")
    Call Component_SetUp(txt_SV_City, "SV_City" & SEP & "Text")
    
    
'---------------
    Call Component_SetUp(grd_product, "grd_product")
    Call Component_SetUp(grd_Attachment, "grd_Attachment")
    Call Component_SetUp(grd_Action, "grd_Action")
    
 '--------------
 
    Exit Sub
    
ErrHandler:
    Call ErrorHandler("Components_Settings")
End Sub

Private Sub Component_SetUp(ByVal ao_cpt As Object, ByVal as_Tag As String)

On Error GoTo ErrHandler
    
    ao_cpt.Tag = as_Tag
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("Component_SetUp")
End Sub

Private Sub InitTaskProduct()
On Error GoTo ErrHandler
    If mo_SRM_TaskProduct Is Nothing Then
        Set mo_SRM_TaskProduct = UserControl.Controls.Add(SRM_C_ProgID & ".SRM_TaskProduct", "mo_SRM_TaskProduct", Me)
        mo_SRM_TaskProduct.Visible = False
        Call mo_SRM_TaskProduct.Move(0, 0, Extender.Width, Extender.Height)
        
        mo_SRM_TaskProduct.Language_Code = ms_Language_Code
        mo_SRM_TaskProduct.U_Code = ml_U_Code
        mo_SRM_TaskProduct.LoginName = ms_LoginName
        Set mo_SRM_TaskProduct.DB = mo_Db
        
        Call mo_SRM_TaskProduct.Load_A_COM
        If Not mo_SRM_TaskProduct.Initialized Then
            Call Err.Raise(ArmErr.CompFncFailed, "mo_SRM_TaskProduct.Initialized", "SRM_TaskProduct cannot was not initialised")
        End If
        mo_SRM_TaskProduct.Zorder
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".InitTaskProduct")
End Sub

Private Sub InitTaskAttachment()
On Error GoTo ErrHandler
    If mo_SRM_Attachment Is Nothing Then
        Set mo_SRM_Attachment = UserControl.Controls.Add(SRM_C_ProgID & ".SRM_Attachment", "mo_SRM_Attachment", Me)
        mo_SRM_Attachment.Visible = False
        Call mo_SRM_Attachment.Move(0, 0, Extender.Width, Extender.Height)
        
        mo_SRM_Attachment.Language_Code = ms_Language_Code
        mo_SRM_Attachment.U_Code = ml_U_Code
        mo_SRM_Attachment.LoginName = ms_LoginName
        Set mo_SRM_Attachment.DB = mo_Db
        
        Call mo_SRM_Attachment.Load_A_COM
        If Not mo_SRM_Attachment.Initialized Then
            Call Err.Raise(ArmErr.CompFncFailed, "mo_SRM_Attachment.Initialized", "SRM_Attachment cannot was not initialised")
        End If
        mo_SRM_Attachment.Zorder
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".InitTaskAttachment")
End Sub

Private Sub InitTaskAction()
On Error GoTo ErrHandler
    If mo_SRM_Action Is Nothing Then
        Set mo_SRM_Action = UserControl.Controls.Add(SRM_C_ProgID & ".SRM_Action", "mo_SRM_Action", Me)
        mo_SRM_Action.Visible = False
        Call mo_SRM_Action.Move(0, 0, Extender.Width, Extender.Height)
        
        mo_SRM_Action.Language_Code = ms_Language_Code
        mo_SRM_Action.U_Code = ml_U_Code
        mo_SRM_Action.LoginName = ms_LoginName
        Set mo_SRM_Action.DB = mo_Db
        
        Call mo_SRM_Action.Load_A_COM
        If Not mo_SRM_Action.Initialized Then
            Call Err.Raise(ArmErr.CompFncFailed, "mo_SRM_Action.Initialized", "SRM_Action cannot was not initialised")
        End If
        mo_SRM_Action.Zorder
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".InitTaskAction")
End Sub

Private Function UpdateUISubDetail(Optional ByVal au_Mode As ArmScreenMode = ArmScreenMode.smRefreshOnly) As ArmScreenMode
On Error GoTo ErrHandler
    Static lu_lastScreen As ArmScreenMode
    
    If au_Mode = smRefreshOnly Then au_Mode = lu_lastScreen

    fra_detail.Visible = False
    tlb_Main.Visible = False
    If Not mo_SRM_TaskProduct Is Nothing Then mo_SRM_TaskProduct.Visible = False
    If Not mo_SRM_Attachment Is Nothing Then mo_SRM_Attachment.Visible = False
    If Not mo_SRM_Action Is Nothing Then mo_SRM_Action.Visible = False

    Select Case au_Mode
        Case smMain
            fra_detail.Visible = True
            tlb_Main.Visible = True
        Case smSubProduct
            If Not mo_SRM_TaskProduct Is Nothing Then mo_SRM_TaskProduct.Visible = True
        Case smSubAttachement
            If Not mo_SRM_Attachment Is Nothing Then mo_SRM_Attachment.Visible = True
        Case smSubAction
            If Not mo_SRM_Action Is Nothing Then mo_SRM_Action.Visible = True
        Case Else
            Debug.Assert (False)
    End Select
    
    UpdateUISubDetail = lu_lastScreen
    lu_lastScreen = au_Mode
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".UpdateUISubDetail")
End Function

Private Sub UpdateUI(Optional ByVal au_Mode As ArmScreenMode = ArmScreenMode.smRefreshOnly)
On Error GoTo ErrHandler

    ' set active face
    If au_Mode <> smRefreshOnly Then
        Call pushScreenMode(au_Mode)
    End If

    tlb_Main.Redraw = False

    ' hide all frames
    fra_detail.Visible = False
    tlb_Main.Visible = False

    ' we have clean screen we can display proper controls
    Select Case activeScreenMode
        Case smMain
        Case smAdd
            fra_detail.Visible = True
            tlb_Main.Visible = True
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_ADD)
            tlb_Product.Visible = True
            Call tlb_Product.DisplayFace("0")
            tlb_Action.Visible = True
            Call tlb_Action.DisplayFace("0")
            tlb_Attachment.Visible = True
            Call tlb_Attachment.DisplayFace("0")
        Case smUpdate
            fra_detail.Visible = True
            tlb_Main.Visible = True
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_UPD)
            tlb_Product.Visible = True
            Call tlb_Product.DisplayFace("0")
            tlb_Action.Visible = True
            Call tlb_Action.DisplayFace("0")
            tlb_Attachment.Visible = True
            Call tlb_Attachment.DisplayFace("0")
        Case smView
            fra_detail.Visible = True
            tlb_Main.Visible = True
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_VIEW)
            tlb_Product.Visible = False
            tlb_Action.Visible = False
            tlb_Attachment.Visible = True
            Call tlb_Attachment.DisplayFace("1")
        Case smDelete
            fra_detail.Visible = True
            tlb_Main.Visible = True
            Call tlb_Main.DisplayFace(C_TOOLBARFACE_ITEM_DEL)
            tlb_Product.Visible = False
            tlb_Action.Visible = False
            tlb_Attachment.Visible = False
        Case Else
            Debug.Assert (False)
    End Select
    
    ' apply rights on toolbar
    Call UpdateActionSubToolbar
    Call UpdateMainToolbar
    
    tlb_Main.Redraw = True

    ' to display face immidiatelly
    UserControl.Refresh
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".UpdateUI()")
End Sub

' ************************************************************************************
' **************************** FRAMEWORK FUNCTIONS ***********************************
' ************************************************************************************
Private Sub pushScreenMode(ByVal au_Mode As ArmScreenMode)
On Error GoTo ErrHandler
    If UBound(mua_ActiveMode) = C_SCREENMODE_STACK_SIZE - 1 Then
        ' move array left
        Debug.Print ("Stack is too small. Increase C_SCREENMODE_STACK_SIZE constant please.")
        Dim ll_Index As Long
        For ll_Index = 1 To UBound(mua_ActiveMode)
            mua_ActiveMode(ll_Index - 1) = mua_ActiveMode(ll_Index)
        Next
    Else
        ' allocate one more item
        ReDim Preserve mua_ActiveMode(UBound(mua_ActiveMode) + 1)
    End If
    mua_ActiveMode(UBound(mua_ActiveMode)) = au_Mode
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".pushScreenMode")
End Sub

Private Property Get activeScreenMode(Optional ByVal al_fromTop As Long = 0) As ArmScreenMode
On Error GoTo ErrHandler
    Debug.Assert (IsArray(mua_ActiveMode))
    activeScreenMode = mua_ActiveMode(UBound(mua_ActiveMode) - al_fromTop)
    Exit Property
ErrHandler:
     Call ErrorHandler(Extender.Name & ".activeScreenMode(Get)")
End Property

Private Sub popScreenMode()
On Error GoTo ErrHandler
    Debug.Assert (UBound(mua_ActiveMode) >= 1)
    ReDim Preserve mua_ActiveMode(UBound(mua_ActiveMode) - 1)
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".popScreenMode")
End Sub

Private Sub popScreenModeUntil(ByVal ae_goTo As ArmScreenMode)
On Error GoTo ErrHandler
    While activeScreenMode <> ae_goTo
        Call popScreenMode
    Wend
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".popScreenModeUntil")
End Sub


Private Sub InitComponents()
'Const CL_REQUEST_TB As String = "SELECT Info FROM Toolbars_Definitions WHERE ID=$id$"
Const CL_REQUEST_TB As String = "A_ToolbarDef_sel 1, 2421, 2808, $id$"

On Error GoTo ErrHandler
    Dim lo_ctrl As Object
    Dim ll_cursor As Long
    Dim ll_i As Long
    
    ' main toolbar
    ll_cursor = OpenSQLSafe(mo_Db, Replace(CL_REQUEST_TB, "$id$", "NULL"))
    If mo_Db.Find(ll_cursor, "id", TLB_SRM_TASK_ID) >= 0 Then
        Call tlb_Main.SetToolbarInfoStringParameters(mo_Db.GetFields(ll_cursor, "info"), Left(mo_Db.GetFields(ll_cursor, "info"), 3))
    Else
        Call Err.Raise(ArmErr.InvalidArgument, "mo_Db.Find", "Toolbar id(" & TLB_SRM_TASK_ID & ") not found in DB")
    End If
    ' product sub toolbar
    If mo_Db.Find(ll_cursor, "id", TLB_SRM_TASK_SUB_PRODUCT_ID) >= 0 Then
        Call tlb_Product.SetToolbarInfoStringParameters(mo_Db.GetFields(ll_cursor, "info"), Left(mo_Db.GetFields(ll_cursor, "info"), 3))
    Else
        Call Err.Raise(ArmErr.InvalidArgument, "mo_Db.Find", "Toolbar id(" & TLB_SRM_TASK_SUB_PRODUCT_ID & ") not found in DB")
    End If
    
    ' attachment sub toolbar
    If mo_Db.Find(ll_cursor, "id", TLB_SRM_TASK_SUB_ATTACHMENTS_ID) >= 0 Then
        Call tlb_Attachment.SetToolbarInfoStringParameters(mo_Db.GetFields(ll_cursor, "info"), Left(mo_Db.GetFields(ll_cursor, "info"), 3))
    Else
        Call Err.Raise(ArmErr.InvalidArgument, "mo_Db.Find", "Toolbar id(" & TLB_SRM_TASK_SUB_ATTACHMENTS_ID & ") not found in DB")
    End If
    
    ' action sub toolbar
    If mo_Db.Find(ll_cursor, "id", TLB_SRM_TASK_SUB_ACTION_ID) >= 0 Then
        Call tlb_Action.SetToolbarInfoStringParameters(mo_Db.GetFields(ll_cursor, "info"), Left(mo_Db.GetFields(ll_cursor, "info"), 3))
    Else
        Call Err.Raise(ArmErr.InvalidArgument, "mo_Db.Find", "Toolbar id(" & TLB_SRM_TASK_SUB_ACTION_ID & ") not found in DB")
    End If
    
    Call mo_Db.Close(ll_cursor)
    ll_cursor = 0
    
    cbo_Plant.FirstBlankItem = False
    cbo_Plant.Request = ReplaceCommonPlaceholders(REQ_SELECT_PLANTS_CBO)
    
    cbo_Reason.FirstBlankItem = False
    cbo_Reason.Request = ReplaceCommonPlaceholders(REQ_SELECT_REASON_CBO)
    
    cbo_Priority.FirstBlankItem = False
    cbo_Priority.Request = ReplaceCommonPlaceholders(REQ_SELECT_PRIORITY_CBO)
    
    cbo_Action.FirstBlankItem = False
    cbo_Action.Request = ReplaceCommonPlaceholders(REQ_SELECT_ACTION_TYPE_CBO)
    
    cbo_currency.FirstBlankItem = False
    cbo_currency.Request = ReplaceCommonPlaceholders(REQ_SELECT_CURRENIES_CBO)
    
    cbo_result.FirstBlankItem = True
    cbo_result.Request = ReplaceCommonPlaceholders(REQ_SELECT_RESULT_CBO)
    
    Call grd_product.SetColumns(Array( _
          Join(Array("STP_Id", 0, 1, "STP_Id", ""), SEP) _
        , Join(Array("SP_Id", 0, 0, "SP_Id", ""), SEP) _
        , Join(Array("SP_Ref", 1000, 0, "SP_Ref", "#Product", "String", "", "Left"), SEP) _
        , Join(Array("Product_Desc", 1500, 0, "Product_Desc", "#Description", "String", "", "Left"), SEP) _
        , Join(Array("Quantity", 1500, 0, "Quantity", "#Quantity", "Number", "", "Left"), SEP) _
        , Join(Array("UM_code", 0, 0, "UM_code", "", "String", "", "Left"), SEP) _
        , Join(Array("UM_desc", 1500, 0, "UM_desc", "#UoM", "String", "", "Left"), SEP) _
        , Join(Array("Batch_id", 1500, 0, "Batch_id", "#Batch", "String", "", "Left"), SEP) _
        , Join(Array("Material_Blocked", 0, 0, "Material_Blocked", "", "String", "", "Left"), SEP) _
        , Join(Array("Z_Creation", 0, 0, "Z_Creation", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("iConcurrency", 0, 0, "iConcurrency", "", "Number", "", "Left"), SEP) _
        , Join(Array("Z_Last_Upd", 0, 0, "Z_Last_Upd", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("Drop_Date", 0, 0, "Drop_Date", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("Z_Last_Upd_User_Name", 0, 0, "Z_Last_Upd_User_Name", "", "String", "", "Left"), SEP) _
        , Join(Array("Z_Creator_Name", 0, 0, "Z_Creator_Name", "", "String", "", "Left"), SEP) _
        , Join(Array("change", 0, 0, "change", "", "String", "", "Left"), SEP) _
        ))
    
    Call grd_Attachment.SetColumns(Array( _
          Join(Array("SRAA_Id", 0, 1, "SRAA_Id", ""), SEP) _
        , Join(Array("SAL_Desc", 1000, 0, "SAL_Desc", "#Description", "String", "", "Left"), SEP) _
        , Join(Array("Z_Creator_Name", 1500, 0, "Z_Creator_Name", "#User", "String", "", "Left"), SEP) _
        , Join(Array("Z_Creation", 1500, 0, "Z_Creation", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("iConcurrency", 0, 0, "iConcurrency", "", "Number", "", "Left"), SEP) _
        , Join(Array("Z_Last_Upd", 0, 0, "Z_Last_Upd", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("Drop_Date", 0, 0, "Drop_Date", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("Z_Last_Upd_User_Name", 0, 0, "Z_Last_Upd_User_Name", "", "String", "", "Left"), SEP) _
        , Join(Array("change", 0, 0, "change", "", "String", "", "Left"), SEP) _
        ))
    
    grd_Action.AllowSort = False
    Call grd_Action.SetColumns(Array( _
          Join(Array("SRA_Id", 0, 1, "SRA_Id", "", "String"), SEP) _
        , Join(Array("User_Assigned", 0, 0, "User_Assigned", "", "Number", "", "Left"), SEP) _
        , Join(Array("User_Assigned_Name", 1500, 0, "User_Assigned_Name", "#Operator", "String", "", "Left"), SEP) _
        , Join(Array("Z_Creation", 1500, 0, "Z_Creation", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("SRAS_Id", 0, 0, "SRAS_Id", "", "Number", "", "Left"), SEP) _
        , Join(Array("SRAS_Desc", 1500, 0, "SRAS_Desc", "#Status", "String", "", "Left"), SEP) _
        , Join(Array("SRA_Comment", 1500, 0, "SRA_Comment", "#Comment", "String", "", "Left"), SEP) _
        , Join(Array("SVC_Id", 0, 0, "SVC_Id", "", "Number", "", "Left"), SEP) _
        , Join(Array("VC_Name", 0, 0, "VC_Name", "", "String", "", "Left"), SEP) _
        , Join(Array("iConcurrency", 0, 0, "iConcurrency", "", "Number", "", "Left"), SEP) _
        , Join(Array("Z_Last_Upd", 0, 0, "Z_Last_Upd", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("Drop_Date", 0, 0, "Drop_Date", "#Date", "Date", "", "Left"), SEP) _
        , Join(Array("Z_Last_Upd_User_Name", 0, 0, "Z_Last_Upd_User_Name", "", "String", "", "Left"), SEP) _
        , Join(Array("Z_Creator_Name", 0, 0, "Z_Creator_Name", "", "String", "", "Left"), SEP) _
        , Join(Array("change", 0, 0, "change", "", "String", "", "Left"), SEP) _
        , Join(Array("U_Email_Armstrong", 0, 0, "U_Email_Armstrong", "", "String", "", "Left"), SEP) _
        ))
    
    
    Exit Sub
ErrHandler:
    If ll_cursor <> 0 Then
        Call mo_Db.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".InitComponents()")
End Sub

Private Sub InitMandatoryLabels(ByRef av_ListFieldsMandatory As Variant)
On Error GoTo ErrHandler

Dim ll_Index As Long
Dim lo_Label As Label

    For ll_Index = 0 To UBound(av_ListFieldsMandatory)
        If av_ListFieldsMandatory(ll_Index)(1) >= 0 Then
            Set lo_Label = lbl_Label(av_ListFieldsMandatory(ll_Index)(1))
            lo_Label.FontBold = True
        End If
    Next
    Exit Sub
ErrHandler:
    Call ErrorHandler("InitMandatoryLabels")
End Sub

Private Function ReplaceCommonPlaceholders(ByVal as_Request As String) As String
On Error GoTo ErrHandler

    as_Request = ReplacePlaceHolder(as_Request, "$language_code$", SQLStr(ms_Language_Code))
    as_Request = ReplacePlaceHolder(as_Request, "$Z_Creator$", SqlInt(ml_U_Code))
    as_Request = ReplacePlaceHolder(as_Request, "$U_Code$", SqlInt(ml_U_Code))
    as_Request = ReplacePlaceHolder(as_Request, "$Z_Last_Upd_User$", SqlInt(ml_U_Code))
    ReplaceCommonPlaceholders = as_Request
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".ReplaceCommonPlaceholders")
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(Extender.Name & ".ReplacePlaceholder")
End Function
Private Sub InitCtrlSize()
On Error GoTo ErrHandler
Const c_margin As Long = 60
    ' ??????????
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".InitCtrlSize()")
End Sub

Private Sub LoadDataToForm(ByVal ac_Cursor As Long, ByRef aControls As Variant, ByRef aContainer As Object)
On Error GoTo ErrHandler
   
    Dim lIdx As Long, lCount As Long
    Dim lControl As Control
    Dim lValues As Variant
    Dim ls_TempTag As String
    
        lCount = aControls.Count - 1
    
        For lIdx = 0 To lCount
            Set lControl = aControls.Item(lIdx)
            If HasContainer(lControl, aContainer) Then
                Select Case UCase(TypeName(lControl))
                    Case "TEXTBOX"
                            ls_TempTag = lControl.Tag & SEP
                            lValues = Split(ls_TempTag, SEP)
                            If mo_Db.GetFieldIndex(ac_Cursor, lValues(0)) >= 0 Then
                                Select Case lValues(1)
                                    Case "Text"
                                        lControl.Text = mo_Db.GetFields(ac_Cursor, lValues(0))
                                    Case "Num"
                                        lControl.Text = Replace(mo_Db.GetFields(ac_Cursor, lValues(0)), ms_DecimalSeparator, ".", , , vbTextCompare)
                                    Case "Date"
                                        If mo_Db.GetFields(ac_Cursor, lValues(0)) = 0 Then
                                            lControl.Text = ""
                                        Else
                                            lControl.Text = Format(mo_Db.GetFields(ac_Cursor, lValues(0)), "dd\/mm\/yyyy")
                                        End If
                                End Select
                            End If
                    
                    Case "ARMCOMBOBOX"
                        ls_TempTag = lControl.Tag & SEP
                        lValues = Split(ls_TempTag, SEP)
                        If mo_Db.GetFieldIndex(ac_Cursor, lValues(0)) >= 0 Then
                            If mo_Db.GetFields(ac_Cursor, lValues(0)) = 0 Or mo_Db.GetFields(ac_Cursor, lValues(0)) = "" Then
                                Set lControl.SelectedItem = Nothing
                            Else
                                If lControl.SearchItem(mo_Db.GetFields(ac_Cursor, lValues(0)), 0, 0, True) = False Then
                                    If lControl.AddItem(Array(mo_Db.GetFields(ac_Cursor, lValues(0)), mo_Db.GetFields(ac_Cursor, lValues(1))), True) Is Nothing Then
                                        Err.Raise 2222, "", ""
                                    End If
                                End If
                            End If
                        End If
                        
                    Case "OPTIONBUTTON"
                        lValues = Split(lControl.Tag, SEP)
                        If mo_Db.GetFieldIndex(ac_Cursor, lValues(0)) >= 0 Then
                            If UCase(lValues(2)) Like UCase(mo_Db.GetFields(ac_Cursor, lValues(0))) Then
                                lControl.Value = True
                            End If
                        End If
                        
                    Case "CHECKBOX"
                        If mo_Db.GetFieldIndex(ac_Cursor, lControl.Tag) >= 0 Then
                            If UCase(mo_Db.GetFields(ac_Cursor, lControl.Tag)) Like "X" Then
                                lControl.Value = vbChecked
                            Else
                                lControl.Value = vbUnchecked
                            End If
                        End If
                        
                    Case "A_CALOCX"
                        lControl.date_courte = mo_Db.GetFields(ac_Cursor, lControl.Tag)
                        
                    Case "LABEL", "FRAME", "DIRLISTBOX", "FILELISTBOX", "DRIVELISTBOX", "TOOLBARCONTROL"
                        'Do Nothing
                    
                    Case "ARMGRID"
                        ' LOAD GRID
                    Case "ARMPICKER"
                        ls_TempTag = lControl.Tag & SEP
                        lValues = Split(ls_TempTag, SEP)
                        If mo_Db.GetFieldIndex(ac_Cursor, lValues(0)) >= 0 Then
                            lControl.ItemCode = mo_Db.GetFields(ac_Cursor, lValues(0))
                            lControl.ItemDescription = mo_Db.GetFields(ac_Cursor, lValues(1))
                            If lControl.ItemCode = "0" And lControl.ItemDescription = "" Then lControl.ItemCode = ""
                        End If
                    
                    Case Else
                        Debug.Print "LoadDataToForm  -> " & UCase(TypeName(lControl))
                End Select
            End If
            Set lControl = Nothing
        Next

    Exit Sub

ErrHandler:
    If Not lControl Is Nothing Then Set lControl = Nothing
    Call ErrorHandler("LoadDataToForm")

End Sub

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

On Error GoTo ErrHandler

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

    Call mo_Db.Close(lLabels)

    Exit Sub

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

Private Function GetContainedControlsChain(ByVal ao_parent As Object) As Collection
On Error GoTo ErrHandler
    Dim lo_retCollection As New Collection
    Dim lo_Control As Object
    
    For Each lo_Control In Controls
        If Not TypeOf lo_Control.Container Is SRM_Task Then
            If ao_parent.hwnd = lo_Control.Container.hwnd Then
                If TypeOf lo_Control Is Frame Then
                    Dim lo_aux_collection As New Collection
                    Dim ll_i As Long
                    Set lo_aux_collection = GetContainedControlsChain(lo_Control)
                    For ll_i = 1 To lo_aux_collection.Count
                        lo_retCollection.Add (lo_aux_collection.Item(ll_i))
                    Next
                Else
                    Call lo_retCollection.Add(lo_Control)
                End If
            End If
        End If
    Next
    Set GetContainedControlsChain = lo_retCollection
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".GetContainedControlsChain()")
End Function

' as_Name equals to Tag definition string

Private Function GetControl(ByVal ao_array As Object, ByVal as_Name As String) As Object
On Error GoTo ErrHandler
    Dim lo_ctrl As Object
    For Each lo_ctrl In ao_array
        If StrComp(lo_ctrl.Tag, as_Name, vbTextCompare) = 0 Then
            Set GetControl = lo_ctrl
            Exit For
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".GetControl()")
End Function

Private Sub SetEnabled(ByVal ao_srcCtrl As Object, ByVal ab_Value As Boolean)
On Error GoTo ErrHandler
    Dim lo_ctrl As Object
    For Each lo_ctrl In ao_srcCtrl
        Call SetEnabledCtrl(lo_ctrl, ab_Value)
    Next
    Exit Sub
ErrHandler:
     Call ErrorHandler(Extender.Name & ".SetEnabled()")
End Sub

Private Sub SetEnabledCtrl(ByRef ao_ctrl As Control, ByVal ab_Value As Boolean)
On Error GoTo ErrHandler
        Select Case UCase(TypeName(ao_ctrl))
        Case "TEXTBOX"
            ao_ctrl.Locked = Not ab_Value
            ao_ctrl.BackColor = IIf(ab_Value, CL_COLOR_ENABLED, CL_COLOR_DISABLED)
        Case "TABSTRIP", "A_CALOCX", "ARMCOMBOBOX", "FRAME", "DIRLISTBOX", "DRIVELISTBOX", "FILELISTBOX", "OPTIONBUTTON", "ARMTREEVIEW", "COMMANDBUTTON", "PICTUREBOX", "CHECKBOX", "IMAGECOMBO"
            ao_ctrl.Enabled = ab_Value
        Case "ARMPICKER"
            ao_ctrl.Enabled = ab_Value
        Case "ARMGRID"
        End Select
    Exit Sub
ErrHandler:
     Call ErrorHandler(Extender.Name & ".SetEnabledCtrl()")
End Sub


' loads values from cursor into form. if cursor=0 then reset whole detail
Private Sub Item_LoadValues(ByVal as_Key As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    Dim ll_cursor As Long
    mb_Initializing = True
    If as_Key <> "" Then
        Debug.Assert (isNumeric(as_Key))
        
        ' load main record
        ls_req = Replace(ReplaceCommonPlaceholders(REQ_SELECT_TASK), "$SRT_Id$", as_Key, , , vbTextCompare)
        ll_cursor = OpenSQLSafe(mo_Db, ls_req)
        
        txt_Key.Text = as_Key
        
        Call LoadDataToForm(ll_cursor, UserControl.Controls, Me)
        
        If Not grd_product.Load(Replace(ReplaceCommonPlaceholders(REQ_SELECT_TASK_PRODUCT_GRID), "$SRT_Id$", as_Key, , , vbTextCompare), True, , , False) Then
            Call Err.Raise(ArmErr.CompFncFailed, "grd_product.Load", "Loading grid of products failed!")
        End If

        If Not grd_Attachment.Load(Replace(ReplaceCommonPlaceholders(REQ_SELECT_TASK_ATTACHMENT_GRID), "$SRT_Id$", as_Key, , , vbTextCompare), True, , , False) Then
            Call Err.Raise(ArmErr.CompFncFailed, "grd_Attachment.Load", "Loading grid of attachements failed!")
        End If

        If Not grd_Action.Load(Replace(ReplaceCommonPlaceholders(REQ_SELECT_TASK_ACTION_GRID), "$SRT_Id$", as_Key, , , vbTextCompare), True, , , False) Then
            Call Err.Raise(ArmErr.CompFncFailed, "grd_Action.Load", "Loading grid of actions failed!")
        End If

        ml_iConcurrency = mo_Db.GetFields(ll_cursor, "iConcurrency")
        
        Call mo_Db.Close(ll_cursor)
        ll_cursor = 0
        
    Else
        ' load default values
        txt_Key.Text = "NEW"
        txt_SRTS_Id.Text = eSRM_TaskStatus.SRTS_New
        txt_Status.Text = GetSRMStatusDesc(eSRM_TaskStatus.SRTS_New)
        txt_Date.Text = Format(Now, "DD/MM/YYYY")
        txt_creator.Text = ms_LoginName
        grd_product.Requests = ""
        grd_Attachment.Requests = ""
        grd_Action.Requests = ""
        
        If ms_MFGP_CODE <> "" Then
            Call SetComboBoxText(cbo_Plant, ms_MFGP_CODE, ms_MFGP_name)
            txt_User_Owned = ms_LoginName
            txt_User_Owned_Code = ml_U_Code
        End If
        txt_estCost.Text = "0.00"
        txt_est_costOther.Text = "0.00"
        txt_actCost.Text = "0.00"
        txt_actCostOther.Text = "0.00"
        
        If Not cbo_Priority.SearchItem(SRM_Priority.SRTP_Medium) Then
            Call cbo_Priority.Load
            Call cbo_Priority.SearchItem(SRM_Priority.SRTP_Medium)
        End If
        
    End If
    
    ' business logic B1
    If grd_product.Rows > 0 And cbo_Plant.Enabled Then
        Call SetEnabledCtrl(cbo_Plant, False)
    End If
    
    mb_Initializing = False

    Exit Sub
ErrHandler:
    If ll_cursor > 0 Then
        Call mo_Db.Close(ll_cursor)
        ll_cursor = 0
    End If
    Call ErrorHandler(Extender.Name & ".Item_LoadValues")
End Sub

Private Function GetSRMStatusDesc(ByVal al_SRTS_Id As eSRM_TaskStatus) As String
On Error GoTo ErrHandler
Const C_REQ As String = "SELECT SRTS_Desc FROM SRM_TaskStatus WHERE SRTS_Id=$SRTS_Id$ AND Language_Code=$Language_Code$"
    Dim ll_cursor As Long
    Dim ls_req As String
    
    ls_req = ReplaceCommonPlaceholders(C_REQ)
    ls_req = ReplacePlaceHolder(ls_req, "$SRTS_Id$", al_SRTS_Id)
    ll_cursor = OpenSQLSafe(mo_Db, ls_req, 1)
    
    GetSRMStatusDesc = mo_Db.GetFields(ll_cursor, "SRTS_Desc")
    Call mo_Db.Close(ll_cursor)
    
    Exit Function
ErrHandler:
    If ll_cursor > 0 Then
        Call mo_Db.Close(ll_cursor)
    End If
    Call ErrorHandler(Extender.Name & ".GetSRMStatusDesc")
End Function

' free resources
Private Sub Item_Cleanup()
On Error GoTo ErrHandler
    mb_Initializing = True
    Call ClearGridToDb(grd_Attachment, REQ_DELETE_ATTACHMENT)   ' only this grid contanint data to be cleaned
    mb_Initializing = False
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_Cleanup")
End Sub

' clear all controls values
Private Sub Item_Clear()
On Error GoTo ErrHandler
    mb_Initializing = True
    Call ClearForm(UserControl.Controls, fra_detail)
    mb_Initializing = False
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_Clear")
End Sub

' initialize view mode
Private Sub Item_ViewInit(ByVal as_detailKey As Variant)
On Error GoTo ErrHandler
    
    Call ResetScreen(ArmScreenMode.smView)
    Call Item_Clear
    
    ' loading values
    Call Item_LoadValues(CStr(as_detailKey(0)))
    
    Call UpdateUI(ArmScreenMode.smView)
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_ViewInit")
End Sub

' initialize delete mode
Private Sub Item_DeleteInit(ByVal as_detailKey As Variant)
On Error GoTo ErrHandler
    
    Call ResetScreen(ArmScreenMode.smDelete)
    Call Item_Clear
        
    Call Item_LoadValues(CStr(as_detailKey(0)))
    
    Call UpdateUI(ArmScreenMode.smDelete)
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_DeleteInit")
End Sub


' initialize update mode
Private Sub Item_AddInit()
On Error GoTo ErrHandler
    ' clearing form
    Call ResetScreen(ArmScreenMode.smAdd)
    Call Item_Clear
        
    Call Item_LoadValues("")
    
    Call UpdateUI(ArmScreenMode.smAdd)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_AddInit")
End Sub

' initialize update mode
Private Sub Item_UpdateInit(ByVal as_detailKey As Variant)
On Error GoTo ErrHandler
    ' clearing form
    Call ResetScreen(ArmScreenMode.smUpdate)
    Call Item_Clear
        
    Call Item_LoadValues(CStr(as_detailKey(0)))
    
    Call UpdateUI(ArmScreenMode.smUpdate)
    
    If txt_SRTS_Id.Text = eSRM_TaskStatus.SRTS_Completed Then
        If MsgBox(MsgText(QueMsgUpdateCompletedTask, ms_Language_Code, "#Do you want to update already completed task?"), vbYesNo) = vbNo Then
            ' move to view mode
            Call popScreenMode
            Call ResetScreen(ArmScreenMode.smView)
            Call UpdateUI(ArmScreenMode.smView)
        End If
    End If
    
    If chk_dropped.Value = vbChecked Then
        ' deleted task cannot by edited
        Call MsgBox(MsgText(ErrMsgUpdateDeletedTask, ms_Language_Code, "#It is not possible to update already deleted task!"), vbInformation)
        ' move to view mode
        Call popScreenMode
        Call ResetScreen(ArmScreenMode.smView)
        Call UpdateUI(ArmScreenMode.smView)
    End If
    
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_UpdateInit")
End Sub

' deletes item
Private Function Item_Delete(ByVal av_oldKey As Variant) As Variant
On Error GoTo ErrHandler
    
    If SendMessage("Delete record ?", vbQuestion + vbYesNo) = vbYes Then
    
        Call Item_DeleteDB(av_oldKey(0))
    
        RaiseEvent OnItemDelete(av_oldKey)

        Call Item_Exit
        
        Item_Delete = av_oldKey
    End If
    Exit Function
ErrHandler:
   If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        Call MsgBox(MsgText(ErrMsgDuplicateLevel, ms_Language_Code, "#Someone changed detail of this record and detail screen will be reloaded."), vbInformation)
        Call Item_Restore(av_oldKey)
        Exit Function
    End If
    Call ErrorHandler(Extender.Name & ".Item_Delete")
End Function

' workw with smView, smUpdate and smDelete mode
Private Sub Item_Restore(ByVal as_detailKey As Variant)
On Error GoTo ErrHandler
    ' clearing form
    Call ResetScreen(activeScreenMode)
    Call Item_Clear
    
    Call Item_LoadValues(CStr(as_detailKey(0)))
    Call UpdateUI
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_Restore")
End Sub

' adds current edited item
Private Function Item_Add() As Variant
On Error GoTo ErrHandler
Dim lb_InTran As Boolean
    lb_InTran = False

    ' check values and throw message if neccessary
    If Not Item_Check() Then
        Exit Function
    End If
    
    Dim ls_newCode As String
    ' get new code
    ls_newCode = mo_Db.SQLNextID(C_ID_KEY)
    txt_Key.Text = ls_newCode
    
    ' get new codes for new grid items
    Call SQLNextIDToGrid(grd_product, C_ID_KEY_TP)
    Call SQLNextIDToGrid(grd_Attachment, C_ID_KEY_AT)
    Call SQLNextIDToGrid(grd_Action, C_ID_KEY_AC)
    
    Dim ls_prdString As String
    ls_prdString = Build_SrzStringFromGrid(grd_product)
    
    
    Call ExecuteSQLSafe(mo_Db, "BEGIN TRAN Item_Add")
    lb_InTran = True
    
    Call Item_AddDB(ls_newCode)

    Call ExecuteSQLSafe(mo_Db, "COMMIT TRAN Item_Add")
    lb_InTran = False
    
    Call SendActionNotification(Build_SrzString(UserControl.Controls, Me), grd_Action)

    ' add SRA_Comment
    Dim ls_SRA_Comment As String    ' last action comment
    If grd_Action.Rows > 0 Then ls_SRA_Comment = grd_Action.Data(0, "SRA_Comment")
    RaiseEvent OnItemAdd(CVar(Array(ls_newCode)), Build_SrzString(UserControl.Controls, Me) & "SRA_Comment" & SEP1 & ls_SRA_Comment, _
                                                  ls_prdString)

    Call Item_Exit
    
    Item_Add = CVar(Array(ls_newCode))
    Exit Function
ErrHandler:
    If lb_InTran Then
        Call mo_Db.ExecuteSQL("ROLLBACK TRAN Item_Add")
        lb_InTran = False
    End If
    If Err.Number = SQLBadRowAffectedCount Then
        Call MsgBox("Error occured while inserting record, please contact IT")
        Exit Function
    End If

    Call ErrorHandler(Extender.Name & ".Item_Add")
End Function

' update current edited item
Private Function Item_Update(ByVal av_oldKey As Variant) As Variant
On Error GoTo ErrHandler
Dim lb_InTran As Boolean
    lb_InTran = False
    If Not Item_Check() Then
        Exit Function
    End If
    
    ' get new codes for new grid items
    Call SQLNextIDToGrid(grd_product, C_ID_KEY_TP)
    Call SQLNextIDToGrid(grd_Attachment, C_ID_KEY_AT)
    Call SQLNextIDToGrid(grd_Action, C_ID_KEY_AC)
    
    Dim ls_prdString As String
    ls_prdString = Build_SrzStringFromGrid(grd_product)
    
    Call ExecuteSQLSafe(mo_Db, "BEGIN TRAN Item_Upd")
    lb_InTran = True
    
    Call Item_UpdateDB(av_oldKey(0))
    
    Call ExecuteSQLSafe(mo_Db, "COMMIT TRAN Item_Upd")
    lb_InTran = False
    
    Call SendActionNotification(Build_SrzString(UserControl.Controls, Me), grd_Action)
    
    Dim ls_SRA_Comment As String    ' last action comment
    If grd_Action.Rows > 0 Then ls_SRA_Comment = grd_Action.Data(0, "SRA_Comment")
    RaiseEvent OnItemUpdate(av_oldKey, Build_SrzString(UserControl.Controls, Me) & "SRA_Comment" & SEP1 & ls_SRA_Comment, _
                                       ls_prdString)

    Call Item_Exit

    Item_Update = CVar(Array(av_oldKey(0)))

    Exit Function
ErrHandler:
    If lb_InTran Then
        Call mo_Db.ExecuteSQL("ROLLBACK TRAN Item_Upd")
        lb_InTran = False
    End If
    If Err.Number = SQLBadRowAffectedCount Then
        Err.Clear
        Call MsgBox(MsgText(ErrMsgDuplicateLevel, ms_Language_Code, "#Someone changed detail of this record and detail screen will be reloaded."), vbInformation)
        Call Item_Cleanup
        Call Item_Restore(av_oldKey)
        Exit Function
    End If
    Call ErrorHandler(Extender.Name & ".Item_Update")
End Function

Private Sub Item_AddDB(ByVal as_Code As Long)
On Error GoTo ErrHandler
    Dim ls_req As String

    ' common placeholders
    ls_req = ReplaceCommonPlaceholders(REQ_INSERT_TASK)
    ls_req = Item_ReplacePlaceholders(ls_req)
    
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)

    'save grids
    Call SaveGridToDb(grd_product, REQ_INSERT_TASK_PRODUCT, REQ_UPDATE_TASK_PRODUCT, REQ_DELETE_TASK_PRODUCT)
    
    Call SaveGridToDb(grd_Attachment, REQ_INSERT_ATTACHMENT_LINK, REQ_UPDATE_ATTACHMENT_LINK, REQ_DELETE_ATTACHMENT_LINK)
        
    Call SaveGridToDb(grd_Action, REQ_INSERT_ACTION, REQ_UPDATE_ACTION, REQ_DELETE_ACTION, False)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_AddDb")
End Sub

Private Function GetGridKeyColumnFieldName(ByRef ao_grid As ArmGrid) As String
On Error GoTo ErrHandler
    Dim ll_Col As Long
    
    GetGridKeyColumnFieldName = ""
    For ll_Col = 0 To ao_grid.Cols - 1
        If ao_grid.Columns(ll_Col).Key Then
            ' we have key
            GetGridKeyColumnFieldName = ao_grid.Columns(ll_Col).FieldName
            Exit For
        End If
    Next

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

Private Sub SQLNextIDToGrid(ByRef ao_grid As ArmGrid, ByVal as_A_ID_KEY As String)
On Error GoTo ErrHandler
    Dim ll_Row As Long, ll_Col As Long
    Dim ls_keyColField As String
    Dim lo_Column  As ArmColumn

    ' find key column
    ls_keyColField = GetGridKeyColumnFieldName(ao_grid)
    If ls_keyColField = "" Then
        Call Err.Raise(ArmErr.InvalidArgument, "ao_grid", "Grid does not containt key column")
    End If
    
    ' iterate grid and create new ID
    For ll_Row = 0 To ao_grid.Rows - 1
        ' determine if row is new
        If ao_grid.Data(ll_Row, ls_keyColField) Like "NEW*" Then
            ao_grid.Data(ll_Row, ls_keyColField) = mo_Db.SQLNextID(as_A_ID_KEY)
        End If
    Next
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SQLNextIDToGrid")
End Sub

' works only for one key column grids
Private Sub SaveGridToDb(ByRef ao_grid As ArmGrid, ByVal as_addReq As String, ByVal as_updReq As String, ByVal as_delReq As String, Optional ab_ClearChangeRow As Boolean = True)
On Error GoTo ErrHandler
    Dim ll_Row As Long
    Dim ls_req  As String

    ' iterate grid and insert/update
    as_addReq = ReplaceCommonPlaceholders(as_addReq)
    as_updReq = ReplaceCommonPlaceholders(as_updReq)
    as_delReq = ReplaceCommonPlaceholders(as_delReq)
    
    For ll_Row = ao_grid.Rows - 1 To 0 Step -1
        Select Case ao_grid.Data(ll_Row, "change")
        Case "A"
            ls_req = ReplacePlaceholderByGridRow(as_addReq, ao_grid, ll_Row)
            ls_req = ReplaceRequestByFrameData(ls_req, fra_detail)
            Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        Case "U"
            ls_req = ReplacePlaceholderByGridRow(as_updReq, ao_grid, ll_Row)
            ls_req = ReplaceRequestByFrameData(ls_req, fra_detail)
            Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        Case "D"
            ls_req = ReplacePlaceholderByGridRow(as_delReq, ao_grid, ll_Row)
            ls_req = ReplaceRequestByFrameData(ls_req, fra_detail)
            Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        End Select
        If ab_ClearChangeRow = True Then
            ao_grid.Data(ll_Row, "change") = ""
        End If
    Next
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SaveGridToDb")
End Sub

' works only for one key column grids
Private Sub ClearGridToDb(ByRef ao_grid As ArmGrid, ByVal as_delReq As String)
On Error GoTo ErrHandler
    Dim ll_Row As Long
    Dim ls_req  As String

    ' iterate grid and insert/update
    as_delReq = ReplaceCommonPlaceholders(as_delReq)
    
    For ll_Row = 0 To ao_grid.Rows - 1
        Select Case ao_grid.Data(ll_Row, "change")
        Case "A"
            ls_req = ReplacePlaceholderByGridRow(as_delReq, ao_grid, ll_Row)
            Call ExecuteSQLSafe(mo_Db, ls_req, 1)
        Case "U", "D"
        End Select
    Next
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".ClearGridToDb")
End Sub

Private Sub Item_UpdateDB(ByVal as_Code As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = ReplaceCommonPlaceholders(REQ_UPDATE_TASK)
    ls_req = Item_ReplacePlaceholders(ls_req)
    
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    'save grids
    Call SaveGridToDb(grd_product, REQ_INSERT_TASK_PRODUCT, REQ_UPDATE_TASK_PRODUCT, REQ_DELETE_TASK_PRODUCT)
    
    Call SaveGridToDb(grd_Attachment, REQ_INSERT_ATTACHMENT_LINK, REQ_UPDATE_ATTACHMENT_LINK, REQ_DELETE_ATTACHMENT_LINK)
        
    Call SaveGridToDb(grd_Action, REQ_INSERT_ACTION, REQ_UPDATE_ACTION, REQ_DELETE_ACTION, False)

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

Private Sub Item_DeleteDB(ByVal as_Code As String)
On Error GoTo ErrHandler
    Dim ls_req As String
    
    ' common placeholders
    ls_req = ReplaceCommonPlaceholders(REQ_DELETE_TASK)
    ls_req = Item_ReplacePlaceholders(ls_req)
    
    Call ExecuteSQLSafe(mo_Db, ls_req, 1)
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_DeleteDb")
End Sub

' specia type od serialized string filed1_name sep1 data1 sep1 data2 sep field2_name ....
Private Function Build_SrzStringFromGrid(ByRef ao_grid As Control) As String
On Error GoTo ErrHandler
    Dim ls_ret As String
    Dim ls_Data As String
    Dim ll_Row As Long
    Build_SrzStringFromGrid = ""
    
    Dim ll_Col As Long
    Dim lo_Column As ArmColumn
    
    For ll_Col = 0 To ao_grid.Cols - 1
        Set lo_Column = ao_grid.Columns(ll_Col)
        ls_Data = ""
        For ll_Row = 0 To ao_grid.Rows - 1
            ls_Data = IIf(ll_Row = 0, "", ls_Data & SEP1) & lo_Column.GetData(ll_Row)
        Next
        ls_ret = IIf(ll_Col = 0, "", ls_ret & SEP) & lo_Column.FieldName & SEP1 & ls_Data
    Next
    
    Build_SrzStringFromGrid = ls_ret
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Build_SrzStringFromGrid")
End Function

Private Function Build_SrzStringFromGridLine(ByRef ao_grid As Control, Optional ByVal al_Row As Long = -1) As String
On Error GoTo ErrHandler
    Dim ls_ret As String
    Build_SrzStringFromGridLine = ""
    If al_Row = -1 Then
        If ao_grid.SelectedCount > 0 Then
            al_Row = ao_grid.Row
        Else
            Call Err.Raise(ArmErr.InvalidArgument, "", "No row selected in grid.")
        End If
    End If
    
    Dim ll_Col As Long
    Dim lo_Column As ArmColumn
    
    For ll_Col = 0 To ao_grid.Cols - 1
        Set lo_Column = ao_grid.Columns(ll_Col)
        ls_ret = IIf(ll_Col = 0, "", ls_ret & SEP) & lo_Column.FieldName & SEP1 & lo_Column.GetData(al_Row)
    Next
    
    Build_SrzStringFromGridLine = ls_ret
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Build_SrzStringFromGridLine")
End Function

Private Function Build_SrzStringFromControl(ByRef aControl As Control) As String
On Error GoTo ErrHandler
    Dim ls_SrzString As String
    Dim lValues As Variant
    Dim ls_TempTag As String
    Dim ls_Str As String

    Build_SrzStringFromControl = ""
    If aControl.Tag = "" Then Exit Function

    ls_TempTag = aControl.Tag & SEP
    lValues = Split(ls_TempTag, SEP)
    
    Select Case UCase(TypeName(aControl))
        Case "TEXTBOX"
                Select Case lValues(1)
                    Case "Text", "Date"
                        ls_SrzString = ls_SrzString & lValues(0) & SEP1 & aControl.Text
                    Case "Num"
                        ls_Str = Replace(aControl.Text, ms_ThousandSeparator, "")
                        ls_Str = Replace(ls_Str, ms_DecimalSeparator, ".")
                        ls_SrzString = ls_SrzString & lValues(0) & SEP1 & ls_Str
               End Select
        
        Case "ARMCOMBOBOX"
            If Not aControl.SelectedItem Is Nothing Then
                ls_SrzString = ls_SrzString & lValues(0) & SEP1 & aControl.SelectedItem.Key & SEP
                ls_SrzString = ls_SrzString & lValues(1) & SEP1 & aControl.SelectedItem.GetData(1)
            Else
                ls_SrzString = ls_SrzString & lValues(0) & SEP1 & "NULL" & SEP
                ls_SrzString = ls_SrzString & lValues(1) & SEP1 & "" & SEP
            End If
        Case "OPTIONBUTTON"
            
        Case "CHECKBOX"
            ls_SrzString = ls_SrzString & lValues(0) & SEP1 & IIf(aControl.Value = vbChecked, "X", "") & SEP
        
        Case "A_CALOCX"
            ls_SrzString = ls_SrzString & lValues(0) & SEP1 & aControl.date_courte
            
            
        Case "LABEL", "FRAME", "DIRLISTBOX", "FILELISTBOX", "DRIVELISTBOX", "TOOLBARCONTROL"
            'Do Nothing
        
        Case "ARMGRID"
            ' do nothing
'            If aControl.SelectedCount > 0 Then
'                ls_SrzString = ls_SrzString & Build_SrzStringFromGridLine(aControl)
'            End If
        Case "ARMPICKER"
            ls_SrzString = ls_SrzString & lValues(0) & SEP1 & aControl.ItemCode & SEP
            ls_SrzString = ls_SrzString & lValues(1) & SEP1 & aControl.ItemDescription
        
        Case Else
            Debug.Print "Build_SrzStringFromControl  -> " & UCase(TypeName(aControl))
    End Select

    Build_SrzStringFromControl = ls_SrzString
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Build_SrzStringFromControl")
End Function


Private Function Build_SrzString(ByRef aControls As Variant, ByRef aContainer As Object) As String
On Error GoTo ErrHandler
    Dim ls_SrzString As String
    Dim lo_Control As CheckBox
    Dim lIdx As Long, lCount As Long
    
    Dim ls_Str As String
    Dim lControl As Control
   
    
        lCount = aControls.Count - 1
        ls_SrzString = ""
    
        For lIdx = 0 To lCount
            Set lControl = aControls.Item(lIdx)
            If HasContainer(lControl, aContainer) Then
                ls_Str = Build_SrzStringFromControl(lControl)
                If ls_Str <> "" Then
                    ls_SrzString = ls_SrzString & ls_Str & SEP
                End If
                
            End If
            Set lControl = Nothing
        Next

    ls_SrzString = Trim(ls_SrzString)
    Build_SrzString = ls_SrzString
    
    Exit Function
    
ErrHandler:
    Call ErrorHandler("Build_SrzString")
End Function

Private Sub FillDataSrcArray(ByRef ao_dataSrc As Dictionary, ByVal as_SrzFields As String)
On Error GoTo ErrHandler
    
    Dim ll_i As Long
    Dim lsa_DataFields() As String
    Dim lv_Values As Variant
    lsa_DataFields = Split(as_SrzFields, SEP)
    
    For ll_i = LBound(lsa_DataFields) To UBound(lsa_DataFields)
        lv_Values = Split(lsa_DataFields(ll_i), SEP1)
        If UBound(lv_Values) >= 1 Then
            Call ao_dataSrc.Add(lv_Values(0), lv_Values(1))
        End If
    Next
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("FillDataSrcArray")
End Sub

Private Function IsInArray(ByVal as_val As String, ByRef av_Array As Variant) As Boolean
On Error GoTo ErrHandler
    Dim ll_i As Long
    IsInArray = False
    For ll_i = LBound(av_Array) To UBound(av_Array)
        If StrComp(av_Array(ll_i), as_val, vbTextCompare) <> 0 Then Exit Function
    Next
    IsInArray = True
    Exit Function
ErrHandler:
    Call ErrorHandler("IsInArray")
End Function

' return number of realy deleted lines .. not the number of lines marked to be deleted
Private Function DeleteLineToGrid(ByVal ao_grid As ArmGrid, ByVal av_KeyFields As Variant, ByVal al_KeyVal As Variant) As Long
On Error GoTo ErrHandler
    DeleteLineToGrid = 0
    
    Dim ll_retVal As Long
    Dim ll_Col As Long
    Dim lo_Column As ArmColumn
    Dim lba_bckKeys() As Boolean
    Dim lv_bckKey As Variant
    ReDim lba_bckKeys(0 To ao_grid.Cols - 1)
    
    ll_retVal = 0

    ' backup keys
    lv_bckKey = ao_grid.CurrentKey
    For ll_Col = 0 To ao_grid.Cols - 1
        Set lo_Column = ao_grid.Columns(ll_Col)
        lba_bckKeys(ll_Col) = lo_Column.Key
        lo_Column.Key = IsInArray(lo_Column.FieldName, av_KeyFields)
    Next

    ' delete all lines
    ao_grid.FirstLine
    Do While ao_grid.SearchKey(False, al_KeyVal)
        If ao_grid.CurrentLine("change") = "A" Then
            ' if line is new then delete line
            If ao_grid.DeleteLine Then
                ll_retVal = ll_retVal + 1
            End If
            
        Else
            ' line is not realy deletable
            ao_grid.CurrentLine("change") = "D"
            ao_grid.LineColor(ao_grid.Row) = SRM_COLOR_DELLINE
            If Not ao_grid.NextLine Then
                Exit Do
            End If
        End If
    Loop
    
    ' restore keys
    For ll_Col = 0 To ao_grid.Cols - 1
        ao_grid.Columns(ll_Col).Key = lba_bckKeys(ll_Col)
    Next
    Call ao_grid.SearchKey(True, lv_bckKey)
    
    DeleteLineToGrid = ll_retVal

    Exit Function
ErrHandler:
    Call ErrorHandler("DeleteLineToGrid")
End Function

Private Function IsKeyRow(ByVal ao_grid As ArmGrid, ByVal al_Row As Long, ByVal av_keyCols As Variant, ByRef ao_dataSrc As Dictionary) As Boolean
On Error GoTo ErrHandler
    IsKeyRow = False
    Dim ll_i As Long
    For ll_i = LBound(av_keyCols) To UBound(av_keyCols)
        If StrComp(ao_grid.Data(al_Row, av_keyCols(ll_i)), ao_dataSrc(av_keyCols(ll_i)), vbTextCompare) <> 0 Then
            Exit Function
        End If
    Next
    IsKeyRow = True
    Exit Function
ErrHandler:
    Call ErrorHandler("IsKeyRow")
End Function

Private Sub UpdateLineToGrid(ByVal ao_grid As ArmGrid, ByRef ao_dataSrc As Dictionary, ByVal av_keyCols As Variant)
On Error GoTo ErrHandler

    Debug.Assert (ao_grid.Cols > 0)
    Dim ll_Row As Long, ll_RowCount As Long, ll_Col As Long
    Dim lo_Column As ArmColumn
    
    ll_RowCount = ao_grid.Rows - 1
    For ll_Row = 0 To ll_RowCount
        If IsKeyRow(ao_grid, ll_Row, av_keyCols, ao_dataSrc) Then
            For ll_Col = 0 To ao_grid.Cols - 1
                Set lo_Column = ao_grid.Columns(ll_Col)
                If ao_dataSrc.Exists(lo_Column.FieldName) Then
                    Call lo_Column.SetData(ll_Row, ao_dataSrc(lo_Column.FieldName))
                End If
            Next
            ao_grid.LineColor(ll_Row) = SRM_COLOR_UPDLINE
        End If
    Next

    Exit Sub
ErrHandler:
    Call ErrorHandler("UpdateLineToGrid")
End Sub

Private Sub AddLineToGrid(ByVal ao_grid As ArmGrid, ByRef ao_dataSrc As Dictionary, Optional ByVal ab_insertAtBeginning As Boolean = False)
On Error GoTo ErrHandler
    
    ' insert row at the end of grid
    Debug.Assert (ao_grid.Cols > 0)
    Dim lo_Column As ArmColumn
    Dim ll_Index As Long
    Dim lsa_newRow() As String
    ReDim lsa_newRow(0 To ao_grid.Cols - 1)
    
    Call ao_grid.DeselectRow
    
    For ll_Index = 0 To ao_grid.Cols - 1
        Set lo_Column = ao_grid.Columns(ll_Index)
        If ao_dataSrc.Exists(lo_Column.FieldName) Then
            lsa_newRow(ll_Index) = ao_dataSrc.Item(lo_Column.FieldName)
        Else
            lsa_newRow(ll_Index) = "TODO:"
        End If
    Next
    
    If ab_insertAtBeginning Then
        Call ao_grid.InsertLine(0, lsa_newRow)
        Call ao_grid.FirstLine
    Else
        Call ao_grid.AddLine(lsa_newRow)
    End If
    ao_grid.LineColor(ao_grid.Row) = SRM_COLOR_ADDLINE
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("AddLineToGrid")
End Sub
Private Function GetFieldValueFromSrz(ByVal as_SrzFields As String, ByVal as_Param As String) As String
On Error GoTo ErrHandler
    
    Dim lv_SrzFields As Variant
    Dim lv_Values
    Dim ll_Count As Long
    Dim ll_Nb As Long
       
    If right(as_SrzFields, 2) <> SEP Then as_SrzFields = as_SrzFields & SEP
       
    lv_SrzFields = Split(as_SrzFields, SEP)
    ll_Nb = UBound(lv_SrzFields) - 1

    For ll_Count = 0 To ll_Nb
        lv_Values = Split(lv_SrzFields(ll_Count), SEP1)
         If UCase(as_Param) = UCase(lv_Values(0)) Then
           GetFieldValueFromSrz = lv_Values(1)
           Exit For
         End If
    Next ll_Count
    
    Exit Function
ErrHandler:
    Call ErrorHandler("GetFieldValueFromSrz")
End Function

Private Sub SetCheckBoxDB(ByVal al_cursor As Long, ByVal as_keyField As String, ByRef ao_CheckBox As VB.CheckBox, Optional ByVal as_checked As String = "X")
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_cursor, as_keyField)
    If Not IsEmpty(lv_val) Then
        ao_CheckBox.Value = IIf(lv_val = as_checked, vbChecked, vbUnchecked)
    Else
        ao_CheckBox.Value = vbUnchecked
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SetCheckBoxDB")
End Sub


Private Sub SetComboBoxTextDB(ByVal al_cursor As Long, ByVal as_keyField As String, ByVal as_DescField As String, ByRef ao_Combobox As ArmCombobox, Optional ByVal ab_clearIfNotExists As Boolean = True)
On Error GoTo ErrHandler
    Dim lv_val As Variant
    lv_val = mo_Db.GetFields(al_cursor, CVar(Array(as_keyField, as_DescField)))
    If Not IsEmpty(lv_val) Then
        Debug.Assert (UBound(lv_val) = 1)
        Call SetComboBoxText(ao_Combobox, CStr(lv_val(0)), CStr(lv_val(1)))
    Else
        If ab_clearIfNotExists Or mo_Db.GetFieldIndex(al_cursor, as_keyField) <> -1 Then
            Call ao_Combobox.Clear
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SetComboBoxTextDB")
End Sub

' Sets combobox selected item
' Params:
' ao_ComboBox (ArmCombobox)
' as_Key (String)
' as_Desc (String)
Private Sub SetComboBoxText(ByRef ao_Combobox As ArmCombobox, ByVal as_Key As String, ByVal as_Desc As String)
On Error GoTo ErrHandler
    If Not ao_Combobox.SearchItem(as_Key) Then
        ' key not found ... set value from parameter
        If as_Key = "" Or as_Key = "0" Then     ' zero or empty string is not valid key
            Set ao_Combobox.SelectedItem = Nothing
        Else
            Call ao_Combobox.AddItem(Array(as_Key, as_Desc), True)
            ' to make vb raise event
            Call ao_Combobox.SearchItem(as_Key)
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SetComboBoxText")
End Sub

Private Function Item_ReplacePlaceholders(ByVal as_Request As String) As String
On Error GoTo ErrHandler
    ' general
    Dim ls_ret As String
    ls_ret = ReplaceRequestByFrameData(as_Request, fra_detail)
    
    ' default
    ls_ret = ReplacePlaceHolder(ls_ret, "$iConcurrency$", ml_iConcurrency)
    ls_ret = ReplacePlaceHolder(ls_ret, "$EMail_Created_Sent$", "NULL")
    ls_ret = ReplacePlaceHolder(ls_ret, "$EMail_Completed_Sent$", "NULL")
    ls_ret = ReplacePlaceHolder(ls_ret, "$EMail_Created$", "''")
    ls_ret = ReplacePlaceHolder(ls_ret, "$EMail_Completed$", "''")
    
    Item_ReplacePlaceholders = ls_ret
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_ReplacePlaceholders")
End Function

' exits mode to main
Private Sub Item_Exit()
On Error GoTo ErrHandler
    
    ' pop last item in screen mode stack
    Call popScreenModeUntil(smMain)
    
    Call ResetScreen(activeScreenMode)
    Call UpdateUI
    
    RaiseEvent OnExit
    
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".Item_Exit")
End Sub

Private Function Item_Check() As Boolean
On Error GoTo ErrHandler
        
    Dim lv_MsgReplaceInfo(0, 1) As String
    Dim lo_Control As Object
    Dim ls_LabelCaption As String
    Dim ll_CtrlIndex As Long
    Dim lb_Found As Boolean
    Dim lo_mandatoryField As Variant
    
    If IsArray(moa_ListFieldsMandatory) Then
    
        For Each lo_mandatoryField In moa_ListFieldsMandatory
            Set lo_Control = lo_mandatoryField(0)
            If lo_mandatoryField(1) >= 0 Then
                ls_LabelCaption = lbl_Label(lo_mandatoryField(1)).Caption
            Else
                ls_LabelCaption = ""
            End If
            Select Case UCase(TypeName(lo_Control))
                Case "FRAME", "LABEL", "MSFLEXGRID", "TOOLBARCONTROL"
                    ' Do nothing !
                
                Case "TEXTBOX"
                    If lo_Control.Visible And (lo_Control.Text = "") Then
                        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                        lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                        Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                        lo_Control.SetFocus
                        Exit Function
                    End If
                Case "ARMCHECKVIEW"
                     If lo_Control.Visible And (lo_Control.RoleList("EDIT").CheckedCount = 0) Then
                        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                        lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                        Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                        Call lo_Control.SetFocus
                        Exit Function
                      End If
                Case "ARMGRID"
                    ' at least one non deleted row must be in grid
                    If lo_Control.Visible And GetGridNonDeletedRows(lo_Control) = 0 Then
                        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                        lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                        Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                        Exit Function
                    End If
                Case "ARMCHECKVIEW", "COMMANDBUTTON", "A_CALOCX", "ARMTREEVIEW", "LISTBOX", "PICTUREBOX", "TABSTRIP"
                
                Case "OPTIONBUTTON", "CHECKBOX"
                    'probably array of controls
                Case "OBJECT"
                    lb_Found = False
                    For ll_CtrlIndex = 0 To lo_Control.Count - 1
                        If UCase(TypeName(lo_Control(ll_CtrlIndex))) = "CHECKBOX" Then
                            If lo_Control(ll_CtrlIndex).Value = vbChecked Then
                                lb_Found = True
                                Exit For
                            End If
                        ElseIf UCase(TypeName(lo_Control(ll_CtrlIndex))) = "OPTIONBUTTON" Then
                            If lo_Control(ll_CtrlIndex).Value Then
                                lb_Found = True
                                Exit For
                            End If
                        Else
                            ' unknown array ???
                            lb_Found = True
                            Exit For
                        End If
                    Next
                    If Not lb_Found Then
                        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                        lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                        Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                        Exit Function
                    End If
                Case "ARMCOMBOBOX"
                    If lo_Control.Visible And (lo_Control.SelectedItem Is Nothing) Then
                        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                        lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                        Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                        Call lo_Control.SetFocus
                        Exit Function
                    End If
                Case "ARMPICKER"
                    If lo_Control.Visible And (CStr(lo_Control.ItemCode) = "") Then
                        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                        lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                        Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                        lo_Control.SetFocus
                        Exit Function
                    End If
                Case "LISTVIEW"
                     If lo_Control.Visible And (GetCheckedCount(lo_Control) = 0) Then
                        lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                        lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                        Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                        Call lo_Control.SetFocus
                        Exit Function
                      End If
                Case Else
                    Debug.Print "Item_CheckMandatory " & UCase(TypeName(lo_Control))
            End Select
        Next
    End If
    
    ' check all numeric fields on detail
    If Not IsArray(moa_ListFieldsNumeric) Then
        Item_Check = True
        Exit Function
    End If
    
    Dim lValues As Variant
    Dim ls_Str As String, ls_TempTag As String

    For Each lo_mandatoryField In moa_ListFieldsNumeric
        Set lo_Control = lo_mandatoryField(0)
        If lo_mandatoryField(1) >= 0 Then
            ls_LabelCaption = lbl_Label(lo_mandatoryField(1)).Caption
        Else
            ls_LabelCaption = ""
        End If
        
        ls_TempTag = lo_Control.Tag & SEP
        lValues = Split(ls_TempTag, SEP)
        Select Case UCase(TypeName(lo_Control))
            Case "TEXTBOX"
                 Select Case lValues(1)
                     Case "Text"     ' no chceck needed
                     Case "Date"
                         If lo_Control.Visible And Not IsDate(lo_Control.Text) Then
                             lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                             lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                             Call MsgBox(MsgText(2120, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                             lo_Control.SetFocus
                             Exit Function
                         End If
                     Case "Num"
                        ls_Str = Replace(lo_Control.Text, ".", ms_DecimalSeparator, , , vbTextCompare)
                        If lo_Control.Visible And Not isNumeric(ls_Str) Then
                             lv_MsgReplaceInfo(0, 0) = "$LabelCaption$"
                             lv_MsgReplaceInfo(0, 1) = ls_LabelCaption
                             Call MsgBox(MsgText(2131, ms_Language_Code, "The field " & lv_MsgReplaceInfo(0, 1) & " is mandatory.", lv_MsgReplaceInfo), vbInformation)
                             lo_Control.SetFocus
                             Exit Function
                         End If
                End Select
            
            Case "ARMCOMBOBOX", "OPTIONBUTTON", "CHECKBOX", "A_CALOCX", "LABEL", "FRAME", "DIRLISTBOX", "FILELISTBOX", "DRIVELISTBOX", "TOOLBARCONTROL", "ARMGRID", "ARMPICKER"
                ' do nothing
            
            Case Else
                Debug.Print "Item_Check  -> " & UCase(TypeName(lo_Control))
        End Select
    Next


    Item_Check = True

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

Private Function GetCheckedCount(ByRef ao_ListView As MSComctlLib.ListView) As Long
On Error GoTo ErrHandler

Dim lo_item As MSComctlLib.ListItem
Dim ll_Count As Long

    ll_Count = 0
    For Each lo_item In ao_ListView.ListItems
        If lo_item.Checked Then ll_Count = ll_Count + 1
    Next
    GetCheckedCount = ll_Count
    Exit Function
ErrHandler:
    Call ErrorHandler("GetCheckedCount")
End Function

Private Sub SetFocusToCtrl(ByRef ao_ctrl As Object)
On Error GoTo ErrHandler
    If ao_ctrl.Visible Then
        ao_ctrl.SetFocus
    End If
    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".SetFocusToCtrl")
End Sub

Private Sub LockScreen(ByVal ab_lock As Boolean)

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

On Error GoTo ErrHandler
    Static ll_Count As Long
    Static ll_Mousepointer As Long
    Static lb_Locked As Boolean
      
    ll_Count = ll_Count + IIf(ab_lock, 1, -1)
    Debug.Assert (ll_Count >= 0)
    
    ' First lock
    If Not lb_Locked And ab_lock Then
        ll_Mousepointer = Screen.MousePointer
        Screen.MousePointer = vbHourglass
        LockWindowUpdate UserControl.hwnd
        lb_Locked = True
    End If
    
    ' Unlock
    If ll_Count = 0 Then
        DoEvents ' Flush events
        LockWindowUpdate 0
        UserControl.Refresh ' 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(Extender.Name & ".LockScreen")
End Sub

Private Sub ResetScreen(ByVal au_Mode As ArmScreenMode)
On Error GoTo ErrHandler
    ' apply face
    Dim lo_ctrl As Object

    Select Case au_Mode
        Case smMain
            ' enable filtering a browsing
            Call SetEnabled(GetContainedControlsChain(fra_detail), False)
            
        Case smUpdate, smAdd
            ' we are in Update section
            Call SetEnabled(GetContainedControlsChain(fra_detail), True)
            
            
            Dim lIdx As Long, lCount As Long
            
            If IsArray(moa_ListFieldsToDisable) Then
                lCount = UBound(moa_ListFieldsToDisable)
            
                For lIdx = 0 To lCount
                    Call SetEnabledCtrl(moa_ListFieldsToDisable(lIdx), False)
                Next
            End If
            
            ' bug339 disable plant cbo in update mode
            If au_Mode = smUpdate Then
                Call SetEnabledCtrl(cbo_Plant, False)
            End If
            
            
        Case smDelete, smView
            ' we are in PreView section
            Call SetEnabled(GetContainedControlsChain(fra_detail), False)
        Case Else
            Debug.Assert (False)
    End Select

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


Private Function HasContainer(ByRef aControl As Control, ByRef aContainer As Object) As Boolean
    HasContainer = False
    Dim lControl As Control
 
    Set lControl = aControl
    While Not (lControl Is Nothing)
        On Error GoTo NotFound
        If lControl.Container Is aContainer Then
            Set lControl = Nothing
            HasContainer = True
            Exit Function
        End If
        Set lControl = lControl.Container
    Wend
 
NotFound:
    Set lControl = Nothing
    HasContainer = False
End Function
 
Private Function IsSub(ByVal av_Name As Object, ByRef aav_Names As Variant)
On Error GoTo ErrHandler
    IsSub = False
    
    Dim ll_Idx As Long
    For ll_Idx = LBound(aav_Names) To UBound(aav_Names)
    
        If av_Name Is aav_Names(ll_Idx) Then
            IsSub = True
            Exit Function
        End If
    Next ll_Idx
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".IsSub")
End Function

' Clear values for each control to not initiliazed
Private Sub ClearForm(ByRef aControls As Variant, ByRef aContainer As Object, Optional ByRef aav_Except As Variant)
On Error GoTo ErrHandler
 
    'mb_internal = True
 
    Dim lIdx As Long, lCount As Long, lControl As Object
    lCount = aControls.Count - 1
    For lIdx = 0 To lCount
        Dim lb_Process As Boolean
        lb_Process = True
        Set lControl = aControls.Item(lIdx)
        If Not IsMissing(aav_Except) Then
            If IsSub(lControl, aav_Except) Then
                lb_Process = False
            End If
        End If
        If HasContainer(lControl, aContainer) And lb_Process Then
            Select Case UCase(TypeName(lControl))
                Case "TEXTBOX"
                    lControl.Text = ""
                Case "ARMCOMBOBOX"
'                    Set lControl.SelectedItem = Nothing
                    Call lControl.Clear
                Case "A_CALOCX"
                    lControl.reinit_cal
                Case "CHECKBOX"
                    lControl.Value = vbUnchecked
                Case "ARMCHECKVIEW"
                    lControl.UnCheckAll lControl.GetVisibleList
                    Dim ll_Idx As Long
                    For ll_Idx = 1 To lControl.RoleCount
                        lControl.RoleList(ll_Idx).ClearList
                    Next
                    lControl.SetVisibleList lControl.GetVisibleList
                    
                Case "FRAME", "LABEL", "TOOLBARCONTROL", "PICTUREBOX", "COMMANDBUTTON"
 
                Case "ARMGRID"
                    lControl.ClearGrid
                Case "LISTBOX"
                    lControl.ListIndex = -1
                Case "OPTIONBUTTON"
                    lControl.Value = False
                Case "TABSTRIP", "DRIVELISTBOX", "DIRLISTBOX", "FILELISTBOX", "TOOLBARCONTROL", "LINE"
                
                Case "ARMPICKER"
                    Call lControl.Clear
                
                Case Else
                    Debug.Print "ClearForm " & UCase(TypeName(lControl))
            End Select
        End If
 
        Set lControl = Nothing
    Next
 
   ' mb_internal = False
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".ClearForm")
End Sub

' ************************************************************************************
' **************************** DB-ACCESS FUNCTIONS ***********************************
' ************************************************************************************
#If LIVE = 1 Then
Private Sub ExecuteSQLSafe(ByVal ao_DB As Object, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1)
#Else
Private Sub ExecuteSQLSafe(ByVal ao_DB As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowAffectedCount = -1)
#End If
On Error GoTo ErrHandler
    ' First execute the request
    If Not ao_DB.ExecuteSQL(as_Request) Then
        Call Err.Raise(CompFncFailed, "ao_Db.ExecuteSQL - " & "SQL : " & as_Request, "SQL Error: " & GetDbError(ao_DB))
    End If

    If al_RowAffectedCount <> -1 Then
        ' Then check the rowcount
        If ao_DB.SQLRowsAffected <> al_RowAffectedCount Then
            Call Err.Raise(SQLBadRowAffectedCount, "SQL : " & as_Request, al_RowAffectedCount & "<>" & ao_DB.SQLRowsAffected)
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".ExecuteSQLSafe")
End Sub

#If LIVE = 1 Then
Private Function OpenSQLSafe(ByVal ao_DB As Object, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#Else
Private Function OpenSQLSafe(ByVal ao_DB As ARMSYSCOMLib.ArmDb, ByVal as_Request As String, Optional ByVal al_RowExpectedCount = -1) As Long
#End If
On Error GoTo ErrHandler
    Dim lc_Data As Long
    lc_Data = ao_DB.OpenSQL(as_Request)
    If lc_Data = 0 Then
        Call Err.Raise(CompFncFailed, "ao_Db.OpenSQL - " & "SQL : " & as_Request, "SQL Error: " & GetDbError(ao_DB))
    End If
    
    If al_RowExpectedCount <> -1 Then
        ' Then check the rowcount
        If ao_DB.RowCount(lc_Data) <> al_RowExpectedCount Then
            Call Err.Raise(SQLBadRowExpectedCount, "SQL : " & as_Request, al_RowExpectedCount & "<>" & ao_DB.RowCount(lc_Data))
        End If
    End If
    OpenSQLSafe = lc_Data
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".OpenSQLSafe")
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 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(Extender.Name & ".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(Extender.Name & ".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(Extender.Name & ".SqlDate")
End Function

Private Function SQLStr(ByVal as_str As String, Optional ByVal al_MaxLen As Long = 8000) As String
On Error GoTo ErrHandler
    SQLStr = "'" & Replace(Left(as_str, IIf(Len(as_str) <= al_MaxLen, Len(as_str), al_MaxLen)), "'", "''") & "'"
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SqlStr")
End Function

' safe retieving selected item from combobox
Private Function SQLComboBoxValue(ByRef ao_Combobox As ArmCombobox, Optional ByVal as_DefaultValue As String = "NULL", Optional ByVal ab_KeyTitle As Boolean = True) As String
On Error GoTo ErrHandler
    If IsComboboxSelected(ao_Combobox) Then
        SQLComboBoxValue = "'" & IIf(ab_KeyTitle, ao_Combobox.SelectedItem.Key, ao_Combobox.SelectedItem.DisplayText) & "'"
    Else
        SQLComboBoxValue = as_DefaultValue
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SQLComboBoxValue")
End Function

Private Function SQLOptionButtonValue(ByRef ao_options As Object) As String
On Error GoTo ErrHandler
    SQLOptionButtonValue = ""
    Dim opt_obj As OptionButton
    For Each opt_obj In ao_options
        If opt_obj.Value Then
            SQLOptionButtonValue = opt_obj.Tag
            Exit For
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SQLOptionButtonValue")
End Function

Private Function IsComboboxSelected(ByRef as_combo As ArmCombobox) As Boolean
On Error GoTo ErrHandler
    IsComboboxSelected = False
    If Not as_combo.SelectedItem Is Nothing Then
        If Not IsEmpty(as_combo.SelectedItem.Key) Then
            IsComboboxSelected = True
        End If
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".IsComboboxSelected")
End Function

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

' ************************************************************************************
' **************************** REDIM FUNCTION ****************************************
' ************************************************************************************
Sub SafeRedimString(ByRef as_Array() As String, al_NumElements As Long)

On Error GoTo ErrHandler

  If al_NumElements = 0 Then
          ReDim as_Array(-1 To -1)
  Else
          'MS REDIMM
          Call SafeRedimPreserve(as_Array, al_NumElements - 1)
  End If
  Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SafeRedimString()")
End Sub

Sub SafeRedim(ByRef av_Array() As Variant, al_NumElements As Long)

On Error GoTo ErrHandler

  If al_NumElements = 0 Then
          ReDim av_Array(-1 To -1)
  Else
          'MS REDIMM
          Call SafeRedimPreserve(av_Array, al_NumElements - 1)
  End If
  Exit Sub
ErrHandler:
    Call ErrorHandler(Extender.Name & ".SafeRedim()")
End Sub
' **************************** REDIM FUNCTION ****************************************

' ************************************************************************************
' ********************** ERROR-HANDLING SUPPORT FUNCTIONS ****************************
' ************************************************************************************
#If LIVE = 1 Then
Private Function GetDbError(ByVal lo_Db As Object) As String
#Else
Private Function GetDbError(ByVal lo_Db As ARMSYSCOMLib.ArmDb) As String
#End If
On Error GoTo ErrHandler
    If IsArray(lo_Db.SQLErrorMessages) Then
        Debug.Assert (IsArray(lo_Db.SQLErrorCodes))
        ' Display errors msgBox
        GetDbError = Join(lo_Db.SQLErrorCodes, ",") & vbCrLf & Join(lo_Db.SQLErrorMessages, vbCrLf)
    Else
        ' ExecuteSQL failed but no error message?
        GetDbError = "Unknown error"
    End If
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".GetDbError()")
End Function

' Standard error handler
Private Sub ErrorHandler(ByVal as_Fct As String)
    Call Err.Raise(Err.Number, as_Fct & SEP1 & Err.Source, Err.Description)
End Sub

' display standard error message
Private Sub ErrorMessage(ByVal as_Fct As String)
    If Err.Number = QuietException Then Exit Sub
    Dim ll_oldMP As MousePointerConstants
    
    'save mouse pointer
    ll_oldMP = Screen.MousePointer
    Screen.MousePointer = vbDefault
    
    Dim ls_ErrSource As String
    Dim ls_errDescription As String
    ls_ErrSource = as_Fct & SEP1 & Err.Source
    ls_errDescription = Err.Description
    
    Call LogMessage(App.ProductName & " exception raised. Err.Number:" & Err.Number & ", Err.Source:" & ls_ErrSource & ", Err.Description " & ls_errDescription & ".", "E", False)
    Call MsgBox("Error occured, please contact IT" & vbCrLf & ls_ErrSource & vbCrLf & "Description: " & ls_errDescription, , "Error message: " & as_Fct)
    
    'restore mouse pointer
    Screen.MousePointer = ll_oldMP
End Sub

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.")
    MsgText = aDefault
End Function

Private Sub LogMessage(ByVal as_logMsg As String, Optional ByVal as_logType As String = "I", Optional ab_throwException As Boolean = True)
On Error GoTo ErrHandler
Const InsertReq As String = "EXEC A_log_ins $UCODE$, $LOGTYPE$, $MSG$, $APP$"
    Dim ls_req As String
    Dim ll_cursor As Long
    
    ls_req = Replace(InsertReq, "$UCODE$", CStr(ml_U_Code))
    ls_req = Replace(ls_req, "$APP$", SQLStr(C_APPNAME & " " & App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision, 50))
    ls_req = Replace(ls_req, "$MSG$", SQLStr(as_logMsg, 4000))
    ls_req = Replace(ls_req, "$LOGTYPE$", SQLStr(as_logType), 1)
    
    Call ExecuteSQLSafe(mo_Db, ls_req)
    
    Exit Sub
ErrHandler:
    If ab_throwException Then Call ErrorHandler(Extender.Name & ".LogMessage()")
End Sub

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

Private Function SendMessage(ByVal as_msg As String, Optional Buttons As VbMsgBoxStyle = vbOKOnly) As VbMsgBoxResult
On Error GoTo ErrHandler
    Call LockScreen(True)
    SendMessage = MsgBox(as_msg, Buttons)
    Call LockScreen(False)
    Exit Function
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage(Extender.Name & ".SendMessage")
End Function

' function return original container
Private Function MoveControlToFront(ByRef ao_ctrl As Object) As Object
On Error GoTo ErrHandler
    Set MoveControlToFront = ao_ctrl.Container
    ao_ctrl.Top = ao_ctrl.Container.Top + ao_ctrl.Top
    ao_ctrl.Left = ao_ctrl.Container.Left + ao_ctrl.Left
    Set ao_ctrl.Container = ao_ctrl.Container.Container
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".MoveControlToFront")
End Function

' recalculate position correctly only in case of one level hierachical change
Private Function MoveControlToFrame(ByRef ao_ctrl As Object, ByRef ao_Frame As VB.Frame) As Object
On Error GoTo ErrHandler
    Set MoveControlToFrame = ao_ctrl.Container
    Set ao_ctrl.Container = ao_Frame
    ao_ctrl.Top = ao_ctrl.Top - ao_Frame.Top
    ao_ctrl.Left = ao_ctrl.Left - ao_Frame.Left
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".MoveControlToFrame")
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"
            lc_Control.Font.Name = "Arial"
            lc_Control.Font.Charset = ll_Charset
        Case "A_SEEK", "A_SRCHTXT"
            lc_Control.Charset = ll_Charset
        End Select
    Next
    
    Exit Sub

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

Private Function ReplacePlaceholderByGridRow(ByVal as_Request As String, ByRef ao_grid As ArmGrid, ByVal al_Row As Long) As String
On Error GoTo ErrHandler
    Dim ll_Col As Long
    Dim lo_Column As ArmColumn
    
    For ll_Col = 0 To ao_grid.Cols - 1
        Set lo_Column = ao_grid.Columns(ll_Col)
        Select Case lo_Column.FieldType
            Case DBTYPE_DATE
                as_Request = ReplacePlaceHolder(as_Request, "$" & lo_Column.FieldName & "$", SqlDate(lo_Column.GetData(al_Row)))
            Case DBTYPE_STR, DBTYPE_BSTR
                as_Request = ReplacePlaceHolder(as_Request, "$" & lo_Column.FieldName & "$", SQLStr(lo_Column.GetData(al_Row)))
            Case DBTYPE_I4
                as_Request = ReplacePlaceHolder(as_Request, "$" & lo_Column.FieldName & "$", SqlInt(lo_Column.GetData(al_Row)))
            Case DBTYPE_R4, DBTYPE_R8
                as_Request = ReplacePlaceHolder(as_Request, "$" & lo_Column.FieldName & "$", SqlDbl(lo_Column.GetData(al_Row)))
            Case Else
                as_Request = ReplacePlaceHolder(as_Request, "$" & lo_Column.FieldName & "$", lo_Column.GetData(al_Row))
        End Select
    Next

    ReplacePlaceholderByGridRow = as_Request
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".ChangeCharset")
End Function

Private Function ReplacePlaceholderByControlValue(ByVal as_Request As String, ByRef ao_Control As Object) As String
On Error GoTo ErrHandler

Dim lsa_Columns() As String

    If Trim(ao_Control.Tag) = "" Then
        ReplacePlaceholderByControlValue = as_Request
        Exit Function
    End If
    
    Select Case UCase(TypeName(ao_Control))
        Case "ARMCOMBOBOX"
            lsa_Columns = Split(ao_Control.Tag, SEP)
            
            If UBound(lsa_Columns) >= 0 Then
                If GetComboKey(ao_Control) = "" Then
                    as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", "NULL")
                Else
                    as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SQLStr(GetComboKey(ao_Control)))
                End If
            End If
            If UBound(lsa_Columns) >= 1 Then
                as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(1) & "$", SQLStr(ao_Control.Text))
            End If
        Case "ARMPICKER"
            lsa_Columns = Split(ao_Control.Tag, SEP)
            
            If UBound(lsa_Columns) >= 0 Then
                If (Trim(CStr(ao_Control.ItemCode)) = "") Or (CStr(ao_Control.ItemCode) = "0") Then
                    as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", "NULL")
                Else
                    as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SQLStr(Trim(CStr(ao_Control.ItemCode))))
                End If
            End If
            If UBound(lsa_Columns) >= 1 Then
                as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(1) & "$", SQLStr(Trim(ao_Control.ItemDescription)))
            End If
        Case "CHECKBOX"
            lsa_Columns = Split(ao_Control.Tag, SEP)
            If ao_Control.Value = vbChecked Then
                as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SQLStr("X"))
            Else
                as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SQLStr(""))
            End If
        Case "TEXTBOX"
            lsa_Columns = Split(ao_Control.Tag, SEP)
            If UBound(lsa_Columns) > 0 Then
                
                Select Case lsa_Columns(1)
                    Case "Text"
                        as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SQLStr(ao_Control.Text))
                    Case "Num"
                        If ao_Control.Text = "" Then
                            as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", "NULL")
                        Else
                            Dim ls_number As String
                            ls_number = Replace(Trim(ao_Control.Text), ms_ThousandSeparator, "", , , vbTextCompare)
                            ls_number = Replace(ls_number, ms_DecimalSeparator, ".", , , vbTextCompare)
                            as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", ls_number)
                        End If
                    Case "Date"
                        If Not IsDate(ao_Control.Text) Then
                            as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", "NULL")
                        Else
                            as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SqlDate(CDate(ao_Control.Text)))
                        End If
                End Select
            Else
                as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SQLStr(ao_Control.Text))
            End If
        Case "A_CALOCX"
            lsa_Columns = Split(ao_Control.Tag, SEP)
            as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SqlDate(ao_Control.date_dt))
        Case "TABSTRIP"
            lsa_Columns = Split(ao_Control.Tag, SEP)
            If ao_Control.SelectedItem Is Nothing Then
                as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", "NULL")
            Else
                as_Request = ReplacePlaceHolder(as_Request, "$" & lsa_Columns(0) & "$", SQLStr(ao_Control.SelectedItem.Key))
            End If
    End Select
    ReplacePlaceholderByControlValue = as_Request
    Exit Function
ErrHandler:
    Call ErrorHandler("ReplacePlaceholderByControlValue")
End Function

Private Function ReplaceRequestByFrameData(ByVal as_Request As String, ByVal ao_Frame As Frame)
On Error GoTo ErrHandler

Dim lo_Control As Control
   
    For Each lo_Control In UserControl.Controls
        If HasContainer(lo_Control, ao_Frame) Then
            as_Request = ReplacePlaceholderByControlValue(as_Request, lo_Control)
        End If
    Next
    ReplaceRequestByFrameData = as_Request
    Exit Function
ErrHandler:
    Call ErrorHandler("ReplaceRequestByFrameData")
End Function

Private Sub cbo_Plant_ComboItemSelected()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call LockScreen(True)
    
    ' update txt_User_Owned ... User_Owned
    txt_User_Owned = cbo_Plant.SelectedItem.GetData(3)
    txt_User_Owned_Code = cbo_Plant.SelectedItem.GetData(2)
    
    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage(Extender.Name & ".cbo_Plant_ComboItemSelected")
End Sub

Private Sub grd_Action_DblClick()
On Error GoTo ErrHandler
    If grd_Action.SelectedCount > 0 Then
        If grd_Action.CurrentLine("change") <> "D" Then
            ' Want to View
            Call InitTaskAction
            ' load detail
            If Not mo_SRM_Action Is Nothing Then
                Call mo_SRM_Action.Run(SRM_Mode.emView, Join(Array( _
                                                                Build_SrzStringFromGridLine(grd_Action), _
                                                                Build_SrzString(UserControl.Controls, fra_detail), _
                                                                "PrevActionComment" & SEP1 & GetDataOfNextRow(grd_Action, grd_Action.Row, "SRA_Comment") _
                                                            ), SEP))
                Call mo_SRM_Action.ImportAttachmentGrid(grd_Attachment)
                Call UpdateUISubDetail(smSubAction)
            End If
        Else
            MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
        End If
    Else
        MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
    End If
    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".grd_Action_DblClick")
End Sub

Private Sub grd_Action_RowColChange()
On Error GoTo ErrHandler
    Call UpdateActionSubToolbar
    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".grd_Action_RowColChange")
End Sub

Private Sub grd_Attachment_DblClick()
On Error GoTo ErrHandler
    If grd_Attachment.SelectedCount > 0 Then
        If grd_Attachment.CurrentLine("change") <> "D" Then
            Call Download_File(grd_Attachment.CurrentLine("SRAA_Id"))
            Call Launch_File(grd_Attachment.CurrentLine("SRAA_Id"))
        End If
    End If
    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".grd_Attachment_DblClick")
End Sub

Private Sub mo_SRM_Action_GetNextFreeID(as_nextID As String)
On Error GoTo ErrHandler
    as_nextID = "NEW#" & (GetGridColMaxValue(grd_Action, "SRA_Id", "NEW#") + 1)
    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Action_GetNextFreeID")
End Sub

Private Sub mo_SRM_Action_OnExit()
On Error GoTo ErrHandler
    
    Call UpdateUISubDetail(smMain)

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Action_OnExit")
End Sub

Private Sub mo_SRM_Action_OnItemAdd(ByVal as_SrzFields As String)
On Error GoTo ErrHandler

    Dim lo_dataSrc As New Dictionary
    lo_dataSrc.CompareMode = TextCompare
    
    Call FillDataSrcArray(lo_dataSrc, as_SrzFields)
    
    ' take attachment grid from action
    Call mo_SRM_Action.ExportAttachmentGrid(grd_Attachment)

    Call AddLineToGrid(grd_Action, lo_dataSrc, True)
    
    ' change status of the task to "in progress"
    txt_SRTS_Id.Text = eSRM_TaskStatus.SRTS_InProgress
    txt_Status.Text = GetSRMStatusDesc(eSRM_TaskStatus.SRTS_InProgress)
    
    'update assigned_to
    pck_assignedTo.ItemCode = lo_dataSrc.Item("User_Assigned")
    pck_assignedTo.ItemDescription = lo_dataSrc.Item("User_Assigned_Name")

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Action_OnItemAdd")
End Sub

Private Sub mo_SRM_Action_OnItemDelete(ByVal av_Key As Variant)
On Error GoTo ErrHandler
    
    Call DeleteLineToGrid(grd_Action, Array("SRA_Id"), av_Key)

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Action_OnItemDelete")
End Sub

Private Sub mo_SRM_Action_OnItemUpdate(ByVal as_SrzFields As String, ByVal as_from As String, ByRef ab_retVal As Boolean)
On Error GoTo ErrHandler
    Dim lo_dataSrc As New Dictionary
    lo_dataSrc.CompareMode = TextCompare
    ab_retVal = True
    
    Call FillDataSrcArray(lo_dataSrc, as_SrzFields)
    
    ' take attachment grid from action
    Call mo_SRM_Action.ExportAttachmentGrid(grd_Attachment)
    
    Call UpdateLineToGrid(grd_Action, lo_dataSrc, Array("SRA_Id"))
    
    If as_from = "U" Then
        ' event is raised from update validation action
        ' status of the action is completed -> should task also be completed?
        If lo_dataSrc.Item("SRAS_Id") = eSRM_ActionStatus.SRAS_Completed Then
            If MsgBox(MsgText(QueMsgActionIsCompleted, ms_Language_Code, "#Action is completed, do you want to change status of the task as completed?."), vbInformation + vbYesNo, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision) = vbYes Then
                txt_SRTS_Id.Text = eSRM_TaskStatus.SRTS_Completed
                txt_Status.Text = GetSRMStatusDesc(eSRM_TaskStatus.SRTS_Completed)
            Else
                ab_retVal = False
            End If
        End If
    End If

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Action_OnItemUpdate")
End Sub


Private Sub mo_SRM_Attachment_OnExit()
On Error GoTo ErrHandler
    
    Call UpdateUISubDetail(smMain)

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Attachment_OnExit")
End Sub

Private Sub mo_SRM_Attachment_OnItemAdd(ByVal as_SrzFields As String)
On Error GoTo ErrHandler
    
    Dim lo_dataSrc As New Dictionary
    lo_dataSrc.CompareMode = TextCompare
    
    Call FillDataSrcArray(lo_dataSrc, as_SrzFields)
    
    Call AddLineToGrid(grd_Attachment, lo_dataSrc)

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Attachment_OnItemAdd")
End Sub

Private Sub mo_SRM_Attachment_OnItemDelete(ByVal av_Key As Variant)
On Error GoTo ErrHandler
    
    If DeleteLineToGrid(grd_Attachment, Array("SRAA_Id"), av_Key) > 0 Then
        ' line was realy deleted => it was not realy linked => remove data from db
        ' common placeholders
        Call ExecuteSQLSafe(mo_Db, ReplacePlaceHolder(REQ_DELETE_ATTACHMENT, "$SRAA_Id$", av_Key), 1)

    End If

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Attachment_OnItemDelete")
End Sub

Private Sub mo_SRM_Attachment_OnItemUpdate(ByVal as_SrzFields As String)
On Error GoTo ErrHandler
    Dim lo_dataSrc As New Dictionary
    lo_dataSrc.CompareMode = TextCompare
    
    Call FillDataSrcArray(lo_dataSrc, as_SrzFields)
    
    Call UpdateLineToGrid(grd_Attachment, lo_dataSrc, Array("SRAA_Id"))

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_Attachment_OnItemUpdate")
End Sub

Private Sub mo_SRM_TaskProduct_OnExit()
On Error GoTo ErrHandler
    
    Call UpdateUISubDetail(smMain)

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_TaskProduct_OnExit")
End Sub

Private Sub mo_SRM_TaskProduct_OnItemAdd(ByVal as_SrzFields As String)
On Error GoTo ErrHandler
    
    Dim lo_dataSrc As New Dictionary
    lo_dataSrc.CompareMode = TextCompare
    
    Call FillDataSrcArray(lo_dataSrc, as_SrzFields)
    
'    If Not TestGridContaintRow(grd_product, "SP_Id", lo_dataSrc("SP_Id"), True) Then
        Call AddLineToGrid(grd_product, lo_dataSrc)
        ' business logic B1
        Call SetEnabledCtrl(cbo_Plant, False)
'    Else
'        MsgBox MsgText(ErrMsgItemAlreadyInGrid, ms_Language_Code, "#Item is already in the grid."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
'    End If

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_TaskProduct_OnItemAdd")
End Sub

Private Sub mo_SRM_TaskProduct_OnItemDelete(ByVal av_Key As Variant)
On Error GoTo ErrHandler
    
    Call DeleteLineToGrid(grd_product, Array("STP_Id"), av_Key)
    
    ' business logic B1
    If GetGridNonDeletedRows(grd_product) = 0 Then
        Call SetEnabledCtrl(cbo_Plant, True)
    End If

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_TaskProduct_OnItemDelete")
End Sub

Private Sub mo_SRM_TaskProduct_OnItemUpdate(ByVal as_SrzFields As String)
On Error GoTo ErrHandler
    Dim lo_dataSrc As New Dictionary
    lo_dataSrc.CompareMode = TextCompare
    
    Call FillDataSrcArray(lo_dataSrc, as_SrzFields)
    
'    If Not TestGridContaintRow(grd_product, "SP_Id", lo_dataSrc("SP_Id"), False) Then
        Call UpdateLineToGrid(grd_product, lo_dataSrc, Array("STP_Id"))
'    Else
'        MsgBox MsgText(ErrMsgItemAlreadyInGrid, ms_Language_Code, "#Item is already in the grid."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
'    End If

    Exit Sub
ErrHandler:
    Call ErrorMessage(Extender.Name & ".mo_SRM_TaskProduct_OnItemUpdate")
End Sub

Private Sub pck_vendor_ItemPicked()
On Error GoTo ErrHandler
    If mb_Initializing Then Exit Sub
    Call LockScreen(True)
    
    Dim lo_searchFrm As frmSearchSRM
    
    Set lo_searchFrm = New frmSearchSRM
    
    lo_searchFrm.Language_Code = ms_Language_Code
    Set lo_searchFrm.ArmDb = mo_Db
    lo_searchFrm.SearchType = SRM_CompType.SRCT_Vendor
    
    lo_searchFrm.ExternalFilters = "EXCL_SUPERVENDORS" & SEP & "X" & SEP & "MFGP_CODE" & SEP & GetComboKey(cbo_Plant)
    lo_searchFrm.ExternalFiltersDesc = "Non Super vendors and Plant is " & cbo_Plant.Text

    
    Call lo_searchFrm.Load_A_COM

    Screen.MousePointer = vbDefault
    Call lo_searchFrm.show(vbModal)
    If lo_searchFrm.mb_SearchOK = True Then
        pck_vendor.ItemCode = lo_searchFrm.mo_search.SelectedItemCode
        pck_vendor.ItemDescription = lo_searchFrm.mo_search.SelectedItemDesc

        Dim lo_dataSrc As New Dictionary
        lo_dataSrc.CompareMode = TextCompare
        Call FillDataSrcArray(lo_dataSrc, lo_searchFrm.mo_search.SelectedItemFull)
        
        'todo
        Call SetComboBoxText(cbo_currency, lo_dataSrc.Item("CURR_Code"), lo_dataSrc.Item("CURR_Desc"))
        txt_SV_City.Text = lo_dataSrc.Item("SV_City")
        
        
        Set lo_dataSrc = Nothing

        
    End If
    Call lo_searchFrm.Unload_A_COM
    Set lo_searchFrm = Nothing

    Call LockScreen(False)
    Exit Sub
ErrHandler:
    Call LockScreen(False)
    Call ErrorMessage(Extender.Name & ".pck_vendor_ItemPicked")
End Sub

Private Sub tlb_Action_action(ByVal as_Role As String, as_Language As String)
On Error GoTo ErrHandler
    Static DoCheck As Boolean
    
    If DoCheck = True Then Exit Sub
    DoCheck = True
    
    Call LockScreen(True)
    tlb_Action.Enabled = False



    Select Case as_Role
        Case "A"
            ' Want to Add
            If pck_vendor.ItemCode <> "" Then
                If Not cbo_Plant.SelectedItem Is Nothing Then
                    ' vendor and plant is used on action screen
                    Call InitTaskAction
                    ' load detail
                    
                    If Not mo_SRM_Action Is Nothing Then
                        ' business rule B5
                        If TestGridNotContaintRow(grd_Action, "SRAS_Id", C_ACTION_STATUS_COMPLETED, True) Then
                            Call mo_SRM_Action.Run(SRM_Mode.emAdd, Join(Array( _
                                                                                Join(Array("SRA_Id", "NEW#" & (GetGridColMaxValue(grd_Action, "SRA_Id", "NEW#") + 1)), SEP1), _
                                                                                Join(Array("change", "A"), SEP1), _
                                                                                Build_SrzString(UserControl.Controls, fra_detail), _
                                                                                "PrevActionComment" & SEP1 & GetDataOfNextRow(grd_Action, -1, "SRA_Comment") _
                                                                            ), SEP))
                            Call mo_SRM_Action.ImportAttachmentGrid(grd_Attachment)
                            Call UpdateUISubDetail(smSubAction)
                        Else
                           MsgBox MsgText(ErrMsgActionInProgress, ms_Language_Code, "#Some action is in progress."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                        End If
                    End If
                Else
                    MsgBox MsgText(ErrMsgPlanNotSelected, ms_Language_Code, "#Plant is not selected."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(ErrMsgVendorNotSelected, ms_Language_Code, "#Vendor is not selected."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case "B"
            If grd_Action.SelectedCount > 0 Then
                If grd_Action.CurrentLine("change") <> "D" Then
                    If grd_Action.CurrentLine("SRAS_Id") <> C_ACTION_STATUS_COMPLETED Then
                        ' Want to Update
                        Call InitTaskAction
                        ' load detail
                        If Not mo_SRM_Action Is Nothing Then
                            Call mo_SRM_Action.Run(SRM_Mode.emUpdate, Join(Array( _
                                                                            Build_SrzStringFromGridLine(grd_Action), _
                                                                            Build_SrzString(UserControl.Controls, fra_detail), _
                                                                            "PrevActionComment" & SEP1 & GetDataOfNextRow(grd_Action, grd_Action.Row, "SRA_Comment") _
                                                                        ), SEP))
                            Call mo_SRM_Action.ImportAttachmentGrid(grd_Attachment)
                            Call UpdateUISubDetail(smSubAction)
                        End If
                    Else
                       MsgBox MsgText(ErrMsgActionIsCompleted, ms_Language_Code, "#This action is completed."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                    End If
                Else
                    MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case "C"
            If grd_Action.SelectedCount > 0 Then
                If grd_Action.CurrentLine("change") <> "D" Then
                    ' Want to delete
                    Call InitTaskAction
                    ' load detail
                    If Not mo_SRM_Action Is Nothing Then
                        Call mo_SRM_Action.Run(SRM_Mode.emDelete, Join(Array( _
                                                                        Build_SrzStringFromGridLine(grd_Action), _
                                                                        Build_SrzString(UserControl.Controls, fra_detail), _
                                                                        "PrevActionComment" & SEP1 & GetDataOfNextRow(grd_Action, grd_Action.Row, "SRA_Comment") _
                                                                    ), SEP))
                        Call mo_SRM_Action.ImportAttachmentGrid(grd_Attachment)
                        Call UpdateUISubDetail(smSubAction)
                    End If
                Else
                    MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case Else
            Err.Raise ArmErr.InvalidArgument, "tlb_Product_action", "Unknown main toolbar role as_Role=" & as_Role
    End Select

    tlb_Action.Enabled = True
    
    Call LockScreen(False)
    
    DoCheck = False

    Exit Sub

ErrHandler:
    
    DoCheck = False
    
    tlb_Action.Enabled = True
    Call LockScreen(False)
    
    Call LogMessage("tlb_Action_action: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E", False)
    Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)

    Exit Sub
End Sub

Private Function GetDataOfNextRow(ByRef ao_grid As ArmGrid, ByVal al_currentRow As Long, ByVal as_colName As String) As String
On Error GoTo ErrHandler
    GetDataOfNextRow = ""
    
    ' goto next row
    al_currentRow = al_currentRow + 1
    
    Do While al_currentRow < ao_grid.Rows
        If ao_grid.Data(al_currentRow, "change") <> "D" Then
            GetDataOfNextRow = ao_grid.Data(al_currentRow, as_colName)
            Exit Do
        End If
    Loop
    
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".GetDataOfNextRow")
End Function

Private Sub tlb_Attachment_action(ByVal as_Role As String, as_Language As String)
On Error GoTo ErrHandler
    Static DoCheck As Boolean
    
    If DoCheck = True Then Exit Sub
    DoCheck = True
    
    Call LockScreen(True)
    tlb_Attachment.Enabled = False


    Select Case as_Role
        Case "A"
            ' Want to Add
            Call InitTaskAttachment
            ' load detail
            
            If Not mo_SRM_Attachment Is Nothing Then
                Call mo_SRM_Attachment.Run(SRM_Mode.emAdd, Join(Array( _
                                                                    Join(Array("SRAA_Id", "NEW#" & (GetGridColMaxValue(grd_Attachment, "SRAA_Id", "NEW#") + 1)), SEP1), _
                                                                    Join(Array("Z_Creation", Format(Now, "DD/MM/YYYY")), SEP1), _
                                                                    Join(Array("Z_Creator_Name", ms_CurrentUser_Name), SEP1), _
                                                                    Join(Array("change", "A"), SEP1) _
                                                                ), SEP))
                Call UpdateUISubDetail(smSubAttachement)
            End If
        Case "B"
            If grd_Attachment.SelectedCount > 0 Then
                If grd_Attachment.CurrentLine("change") <> "D" Then
                    ' Want to Update
                    Call InitTaskAttachment
                    ' load detail
                    If Not mo_SRM_Attachment Is Nothing Then
                        Call mo_SRM_Attachment.Run(SRM_Mode.emUpdate, Join(Array( _
                                                                        Build_SrzStringFromGridLine(grd_Attachment) _
                                                                    ), SEP))
                        Call UpdateUISubDetail(smSubAttachement)
                    End If
                Else
                    MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case "C"
            If grd_Attachment.SelectedCount > 0 Then
                If grd_Attachment.CurrentLine("change") <> "D" Then
                    ' Want to delete
                    Call InitTaskAttachment
                    ' load detail
                    If Not mo_SRM_Attachment Is Nothing Then
                        Call mo_SRM_Attachment.Run(SRM_Mode.emDelete, Build_SrzStringFromGridLine(grd_Attachment))
                    End If
                Else
                    MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case "g"    ' save file
            If grd_Attachment.SelectedCount > 0 Then
                If grd_Attachment.CurrentLine("change") <> "D" Then
                    ' Want to save
                    Call SaveBlobFile(grd_Attachment.CurrentLine("SRAA_Id"))
                Else
                    MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        
        Case Else
            Err.Raise ArmErr.InvalidArgument, "tlb_Product_action", "Unknown main toolbar role as_Role=" & as_Role
    End Select

    tlb_Attachment.Enabled = True
    
    Call LockScreen(False)
    
    DoCheck = False

    Exit Sub

ErrHandler:
    
    DoCheck = False
    
    tlb_Attachment.Enabled = True
    Call LockScreen(False)
    
    Call LogMessage("tlb_Attachment_action: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E", False)
    Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
    Exit Sub
End Sub

Private Sub tlb_main_action(ByVal as_Role As String, as_Language As String)
On Error GoTo ErrHandler
    Static DoCheck As Boolean
    
    If DoCheck = True Then Exit Sub
    DoCheck = True
    
    Call LockScreen(True)
    tlb_Main.Enabled = False

    Select Case as_Role
        Case "A"
            Call Run(SRM_Mode.emAdd, Array(""))
        Case "C" 'delete button
            Call Run(SRM_Mode.emDelete, Array(CLng(txt_Key.Text)))
        Case "B" 'goto Update screen
            Call Run(SRM_Mode.emUpdate, Array(CLng(txt_Key.Text)))
        Case "D"
            RaiseEvent OnPrint(Array(CLng(txt_Key.Text)))
        Case "I" 'Refresh update
            Call Item_Cleanup
            If isNumeric(txt_Key.Text) Then
                Call Item_Restore(Array(CLng(txt_Key.Text)))
            Else
                Call Item_Restore(Array(""))
            End If
            
        Case "H" 'validate mode add
            Select Case activeScreenMode
                Case ArmScreenMode.smAdd
                    Call Item_Add
                Case ArmScreenMode.smUpdate
                    Call Item_Update(Array(CLng(txt_Key.Text)))
                Case ArmScreenMode.smDelete
                    Call Item_Delete(Array(CLng(txt_Key.Text)))
                Case Else
                    Debug.Assert (False)
            End Select
        
        Case "Y" 'Goto next item
            Call popScreenMode
            RaiseEvent OnItemNext
            
            If activeScreenMode <> smView Then
                Call pushScreenMode(smView)
            End If

        Case "Z" 'Goto previous item
            Call popScreenMode
            RaiseEvent OnItemPrevious
        
            If activeScreenMode <> smView Then
                Call pushScreenMode(smView)
            End If
        
        Case "T"
            Call Item_Cleanup
            Call Item_Exit
    End Select
    
    tlb_Main.Enabled = True
    
    Call LockScreen(False)
    
    DoCheck = False

    Exit Sub

ErrHandler:
    
    DoCheck = False
    
    tlb_Main.Enabled = True
    Call LockScreen(False)
    
    Select Case Err.Number
    Case 3007
        MsgBox MsgText(3054, ms_Language_Code, "#This data has been updated by another user. Please reload the data and try again."), vbInformation
    
    Case 3008
        MsgBox MsgText(2138, ms_Language_Code, "#The record you try to open has been deleted by an other user. Please refresh the grid."), vbInformation
        Call Item_Exit
    
    Case Else
        Call LogMessage("tlb_Main_action: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E", False)
        Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)
        End
    End Select

    Exit Sub
End Sub

Private Function TestGridContaintRow(ByRef ao_grid As ArmGrid, ByVal as_colName As String, ByVal as_colVal As String, ByVal ab_incSelectedRow As Boolean, Optional ByVal as_colChangeName As String = "change", Optional ByVal as_deletedValue As String = "D") As Boolean
On Error GoTo ErrHandler
    Dim ll_Row As Long
    TestGridContaintRow = False
    For ll_Row = 0 To ao_grid.Rows - 1
        If StrComp(ao_grid.Data(ll_Row, as_colChangeName), as_deletedValue, vbTextCompare) <> 0 Then
            If ab_incSelectedRow Or (Not ab_incSelectedRow And ll_Row <> ao_grid.Row) Then
                If StrComp(ao_grid.Data(ll_Row, as_colName), as_colVal, vbTextCompare) = 0 Then
                    TestGridContaintRow = True
                    Exit Function
                End If
            End If
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".TestGridContaintRow")
End Function

Private Function TestGridNotContaintRow(ByRef ao_grid As ArmGrid, ByVal as_colName As String, ByVal as_colVal As String, ByVal ab_incSelectedRow As Boolean, Optional ByVal as_colChangeName As String = "change", Optional ByVal as_deletedValue As String = "D") As Boolean
On Error GoTo ErrHandler
    Dim ll_Row As Long
    TestGridNotContaintRow = True
    For ll_Row = 0 To ao_grid.Rows - 1
        If StrComp(ao_grid.Data(ll_Row, as_colChangeName), as_deletedValue, vbTextCompare) <> 0 Then
            If ab_incSelectedRow Or (Not ab_incSelectedRow And ll_Row <> ao_grid.Row) Then
                If StrComp(ao_grid.Data(ll_Row, as_colName), as_colVal, vbTextCompare) <> 0 Then
                    ' this means grid containt row which is not of value as_colVal
                    TestGridNotContaintRow = False
                    Exit Function
                End If
            End If
        End If
    Next
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".TestGridNotContaintRow")
End Function

Private Function GetGridNonDeletedRows(ByRef ao_grid As ArmGrid, Optional ByVal as_colName As String = "change", Optional ByVal as_deletedValue As String = "D") As Long
On Error GoTo ErrHandler
    Dim ll_Row As Long
    Dim ll_retVal As Long
    ll_retVal = 0
    For ll_Row = 0 To ao_grid.Rows - 1
        If StrComp(ao_grid.Data(ll_Row, as_colName), as_deletedValue, vbTextCompare) <> 0 Then ll_retVal = ll_retVal + 1
    Next
    GetGridNonDeletedRows = ll_retVal
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".GetGridNonDeletedRows")
End Function
Private Function GetGridColMaxValue(ByRef ao_grid As ArmGrid, ByVal as_colName As String, ByVal as_like As String) As Long
On Error GoTo ErrHandler
    Dim ll_Row As Long
    Dim ls_Data As String
    Dim ll_retVal As Long
    ll_retVal = 0
    For ll_Row = 0 To ao_grid.Rows - 1
        ls_Data = ao_grid.Data(ll_Row, as_colName)
        If Len(ls_Data) > Len(as_like) Then
            If StrComp(Left(ls_Data, Len(as_like)), as_like, vbTextCompare) = 0 Then
                ls_Data = right(ao_grid.Data(ll_Row, as_colName), Len(ao_grid.Data(ll_Row, as_colName)) - Len(as_like))
                If isNumeric(ls_Data) Then
                    If CLng(ls_Data) > ll_retVal Then ll_retVal = CLng(ls_Data)
                End If
            End If
        End If
    Next
    GetGridColMaxValue = ll_retVal
    Exit Function
ErrHandler:
    Call ErrorHandler(Extender.Name & ".GetGridColMaxValue")
End Function

Private Sub tlb_product_action(ByVal as_Role As String, as_Language As String)
On Error GoTo ErrHandler
    Static DoCheck As Boolean
    
    If DoCheck = True Then Exit Sub
    DoCheck = True
    
    Call LockScreen(True)
    tlb_Product.Enabled = False



    Select Case as_Role
        Case "A"
            ' Want to Add
            If Not cbo_Plant.SelectedItem Is Nothing Then
                Call InitTaskProduct
                ' load detail
                
                If Not mo_SRM_TaskProduct Is Nothing Then
                    Call mo_SRM_TaskProduct.Run(SRM_Mode.emAdd, Join(Array( _
                                                                        Join(Array("STP_Id", "NEW#" & (GetGridColMaxValue(grd_product, "STP_Id", "NEW#") + 1)), SEP1), _
                                                                        Join(Array("Z_Creation", Format(Now, "DD/MM/YYYY")), SEP1), _
                                                                        Join(Array("Z_Creator_Name", ms_CurrentUser_Name), SEP1), _
                                                                        Join(Array("change", "A"), SEP1), _
                                                                        Build_SrzStringFromControl(cbo_Plant) _
                                                                    ), SEP))
                    Call UpdateUISubDetail(smSubProduct)
                End If
            Else
                MsgBox MsgText(ErrMsgPlanNotSelected, ms_Language_Code, "#Plant is not selected."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case "B"
            If grd_product.SelectedCount > 0 Then
                If grd_product.CurrentLine("change") <> "D" Then
                    ' Want to Update
                    Call InitTaskProduct
                    ' load detail
                    If Not mo_SRM_TaskProduct Is Nothing Then
                        Call mo_SRM_TaskProduct.Run(SRM_Mode.emUpdate, Join(Array( _
                                                                        Build_SrzStringFromGridLine(grd_product), _
                                                                        Build_SrzStringFromControl(cbo_Plant) _
                                                                    ), SEP))
                        Call UpdateUISubDetail(smSubProduct)
                    End If
                Else
                    MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case "C"
            If grd_product.SelectedCount > 0 Then
                If grd_product.CurrentLine("change") <> "D" Then
                    ' Want to delete
                    Call InitTaskProduct
                    ' load detail
                    If Not mo_SRM_TaskProduct Is Nothing Then
                        Call mo_SRM_TaskProduct.Run(SRM_Mode.emDelete, Build_SrzStringFromGridLine(grd_product))
                        Call UpdateUISubDetail(smSubProduct)
                    End If
                Else
                    MsgBox MsgText(ErrMsgItemIsDeleted, ms_Language_Code, "#Row is deleted."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
                End If
            Else
                MsgBox MsgText(WarMsgSelectRow, ms_Language_Code, "#Please select a row."), vbInformation + vbOKOnly, App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
            End If
        Case Else
            Err.Raise ArmErr.InvalidArgument, "tlb_Product_action", "Unknown main toolbar role as_Role=" & as_Role
    End Select

    tlb_Product.Enabled = True
    
    Call LockScreen(False)
    
    DoCheck = False

    Exit Sub

ErrHandler:
    
    DoCheck = False
    
    tlb_Product.Enabled = True
    Call LockScreen(False)
    
    Call LogMessage("tbl_product_action: " & Err.Number & ": " & Err.Source & ": " & Err.Description, "E", False)
    Call MsgBox("Error during the process, Contact immediatly your IT support.", vbCritical)

    Exit Sub
End Sub

Private Sub UpdateMainToolbar()
On Error GoTo ErrHandler
    Dim lb_isOwner As Boolean, lb_isCompleted As Boolean
    ' business logic B2
    lb_isOwner = False
    lb_isCompleted = False
    
    If isNumeric(txt_User_Owned_Code.Text) Then
        lb_isOwner = (txt_User_Owned_Code.Text = ml_U_Code)
    End If
    If isNumeric(txt_SRTS_Id.Text) Then
        lb_isCompleted = (txt_SRTS_Id.Text = eSRM_TaskStatus.SRTS_Completed)
    End If
    tlb_Main.ButtonVisible("B") = lb_isOwner Or Not lb_isCompleted
    tlb_Main.ButtonVisible("C") = lb_isOwner And Not lb_isCompleted
    
    Exit Sub
ErrHandler:
    Call ErrorHandler("UpdateMainToolbar")
End Sub


Private Sub UpdateActionSubToolbar()
On Error GoTo ErrHandler
    
    Dim lb_updateIsAvailable As Boolean
    
    ' business logic B3 .. only task owner or action.user_assigend can edit the action
    If isNumeric(txt_User_Owned_Code.Text) Then
        lb_updateIsAvailable = (txt_User_Owned_Code.Text = ml_U_Code)
    Else
        lb_updateIsAvailable = False
    End If
    
    If Not lb_updateIsAvailable Then
        If grd_Action.SelectedCount > 0 Then
            If isNumeric(grd_Action.CurrentLine("User_Assigned")) Then
                lb_updateIsAvailable = (grd_Action.CurrentLine("User_Assigned") = ml_U_Code)
            End If
        End If
    End If
    tlb_Action.ButtonVisible("B") = lb_updateIsAvailable

    Exit Sub
ErrHandler:
    Call ErrorHandler("UpdateActionSubToolbar")
End Sub

Private Function GetTempDir() As String
Dim ls_Buff As String, ll_Count As Long

On Error GoTo ErrHandler
    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
  Exit Function
ErrHandler:
  Call ErrorHandler("GetTempDir")
End Function

Private Sub Download_File(ByVal al_SRAA_Id As Long)
Dim ls_ZipDir As String
Dim ls_Request As String
Dim ls_dir As String

On Error GoTo ErrHandler
    
    ls_dir = GetTempDir & "\$SRAA_Id$"
    If Not mo_FSO.FolderExists(ls_dir) Then
      Call mo_FSO.CreateFolder(ls_dir)
    End If
    ls_ZipDir = ls_dir & "\" & al_SRAA_Id
    If Not mo_FSO.FolderExists(ls_ZipDir) Then
      Call mo_FSO.CreateFolder(ls_ZipDir)
    End If
    ls_Request = ReplacePlaceHolder(REQ_SELECT_ATTACHMENT, "$SRAA_Id$", al_SRAA_Id)
    If Not mo_Db.BlobToFileSQL(ls_Request, ls_ZipDir, True, True) Then
      Call Err.Raise(ArmErr.CompFncFailed, "BlobToFileSQL", mo_Db.LastErrorMessage & " ls_Request=" & ls_Request & ",ls_ZipDir=" & ls_ZipDir)
    End If
  Exit Sub
ErrHandler:
  Call ErrorHandler("Download_File:" & al_SRAA_Id)
End Sub

Private Sub Launch_File(ByVal al_SRAA_Id As Long)
Dim ls_TempDir As String
Dim lo_Fld As Object
Dim lo_File As Object
Dim lo_shell As Object

On Error GoTo ErrHandler
  If al_SRAA_Id = 0 Then Exit Sub
  ls_TempDir = GetTempDir & "\$SRAA_Id$\" & al_SRAA_Id
  Set lo_shell = CreateObject("Shell.Application")

  Set lo_Fld = mo_FSO.GetFolder(ls_TempDir)
  For Each lo_File In lo_Fld.Files
    Call lo_shell.ShellExecute(lo_File.Path, "", "", "open", 1)
  Next
  Set lo_shell = Nothing
  Exit Sub
ErrHandler:
  Set lo_shell = Nothing
  Call ErrorHandler("Launch_Report_File:" & al_SRAA_Id)
End Sub

Private Sub Copy_File(ByVal al_SRAA_Id As Long, ByVal as_dir As String)
Dim ls_TempDir As String

On Error GoTo ErrHandler
    
  ls_TempDir = GetTempDir & "\$SRAA_Id$\" & al_SRAA_Id
  Call mo_FSO.CopyFile(ls_TempDir & "\*.*", as_dir, True)
  Exit Sub
ErrHandler:
  Call ErrorHandler("Copy_File al_SRAA_Id=" & al_SRAA_Id & " as_Dir=" & as_dir)
End Sub

Private Sub SaveBlobFile(ByVal al_SRAA_Id As Long)
On Error GoTo ErrHandler
    
    Dim shFolder As Object
    Dim shShell As Object

    Set shShell = CreateObject("Shell.Application")
    Set shFolder = shShell.BrowseForFolder(0, "Choose Folder", 1)
    If Not (shFolder Is Nothing) Then
        Call Download_File(al_SRAA_Id)
        Call Copy_File(al_SRAA_Id, shFolder.self.Path)
    End If
    Exit Sub
ErrHandler:
    Call ErrorHandler("SaveBlobFile")
End Sub

Private Sub SendActionNotification(ByVal as_SrzFields As String, ByRef ao_grid As ArmGrid)
On Error GoTo ErrHandler

Const Subject_Assigned As String = "NC Task $SRT_Id$ Action assigned"

Const Message_Assigned As String = "Action: $SRAS_Desc$" & vbNewLine & _
                          "Vendor: $SV_Name$" & vbNewLine & _
                          "Summary: $SRT_Summary$" & vbNewLine & _
                          "Comment: $SRT_Description$"

Dim li_Idx As Integer
Dim lo_MailClient As MailClient
Dim lo_dataSrc As New Dictionary
Dim ls_Subject As String
Dim ls_Message As String
Dim ll_Index As Long
Dim ll_Row As Long
    
    Set lo_MailClient = New MailClient
    Set lo_MailClient.ArmDb = mo_Db
    lo_MailClient.U_Code = ml_U_Code
    lo_MailClient.Load_A_COM
    
    ' set account which will be used by mo_MailClient
    lo_MailClient.SetActiveMailBox ("SRM")
       
    lo_dataSrc.CompareMode = TextCompare
    
    Call FillDataSrcArray(lo_dataSrc, as_SrzFields)

    For ll_Row = ao_grid.Rows - 1 To 0 Step -1
            
        Select Case ao_grid.Data(ll_Row, "change")
        Case "A"
            If ao_grid.Data(ll_Row, "SRAS_Id") <> eSRM_ActionStatus.SRAS_Completed Then
                ls_Subject = Replace(Subject_Assigned, "$SRT_Id$", txt_Key.Text, , , vbTextCompare)
                ls_Message = ReplacePlaceholderByGridRow(Message_Assigned, ao_grid, ll_Row)
                
                For ll_Index = 0 To lo_dataSrc.Count - 1
                    ls_Message = Replace(ls_Message, "$" & lo_dataSrc.keys(ll_Index) & "$", lo_dataSrc.Items(ll_Index), , , vbTextCompare)
                Next
                
                li_Idx = lo_MailClient.AddEmail(ls_Subject, ls_Message, False, Now, "")
                
                If lo_MailClient.AddEmailAddress(li_Idx, "", emlEmailType.etEmailTo, ao_grid.Data(ll_Row, "User_Assigned")) = emlEmailAddressErr.eaeEmailOk Then
                    Call lo_MailClient.SendEmail(li_Idx)
                End If
            End If
        End Select
    
        ao_grid.Data(ll_Row, "change") = ""
        
    Next
                
ExitHandler:
    ' Unload MailClient
    lo_MailClient.Unload_A_COM
    Set lo_MailClient = Nothing

    Exit Sub
ErrHandler:
    Call ErrorHandler("SendActionNotification")
End Sub

