VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0"; "mscomctl.ocx"
Begin VB.UserControl ArmReporting 
   ClientHeight    =   11520
   ClientLeft      =   0
   ClientTop       =   0
   ClientWidth     =   14565
   ScaleHeight     =   11520
   ScaleWidth      =   14565
   Begin VB.Frame frm_Grid 
      Height          =   1455
      Left            =   6990
      TabIndex        =   112
      Top             =   3405
      Visible         =   0   'False
      Width           =   3135
      Begin VB.Frame frm_GridOperator 
         Height          =   735
         Left            =   120
         TabIndex        =   116
         Top             =   120
         Width           =   2775
         Begin Project1.ArmCombobox cbo_GridLogic 
            Height          =   345
            Left            =   1845
            TabIndex        =   122
            Top             =   240
            Width           =   810
            _ExtentX        =   1429
            _ExtentY        =   609
         End
         Begin Project1.ArmCombobox cbo_GridOperator 
            Height          =   345
            Left            =   90
            TabIndex        =   121
            Top             =   240
            Width           =   1635
            _ExtentX        =   2884
            _ExtentY        =   609
         End
      End
      Begin Project1.ToolbarControl pbGrid 
         Height          =   690
         Left            =   120
         TabIndex        =   114
         Top             =   240
         Width           =   2055
         _ExtentX        =   3625
         _ExtentY        =   1217
      End
      Begin Project1.ArmGrid grd_Filter 
         Height          =   855
         Left            =   120
         TabIndex        =   113
         Top             =   1800
         Width           =   2055
         _ExtentX        =   3625
         _ExtentY        =   1508
      End
      Begin Project1.ArmGrid grd_Criteria 
         Height          =   855
         Left            =   120
         TabIndex        =   115
         Top             =   960
         Width           =   2055
         _ExtentX        =   3625
         _ExtentY        =   1508
      End
   End
   Begin VB.Frame frm_List 
      Height          =   2295
      Left            =   2910
      TabIndex        =   9
      Top             =   8190
      Visible         =   0   'False
      Width           =   4215
      Begin Project1.ArmCombobox cbo_ListLogic 
         Height          =   345
         Left            =   1710
         TabIndex        =   120
         Top             =   1035
         Width           =   855
         _ExtentX        =   1508
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_ListOperator 
         Height          =   345
         Left            =   120
         TabIndex        =   119
         Top             =   1035
         Width           =   1485
         _ExtentX        =   2619
         _ExtentY        =   609
      End
      Begin VB.TextBox txt_List 
         Height          =   375
         Left            =   120
         Locked          =   -1  'True
         TabIndex        =   19
         Top             =   1800
         Width           =   3975
      End
      Begin MSComctlLib.ListView lvw_List 
         Height          =   255
         Left            =   120
         TabIndex        =   10
         Top             =   1440
         Width           =   3975
         _ExtentX        =   7011
         _ExtentY        =   450
         View            =   2
         LabelEdit       =   1
         MultiSelect     =   -1  'True
         LabelWrap       =   0   'False
         HideSelection   =   -1  'True
         Checkboxes      =   -1  'True
         FullRowSelect   =   -1  'True
         GridLines       =   -1  'True
         HotTracking     =   -1  'True
         _Version        =   393217
         ForeColor       =   -2147483640
         BackColor       =   -2147483643
         BorderStyle     =   1
         Appearance      =   1
         NumItems        =   1
         BeginProperty ColumnHeader(1) {BDD1F052-858B-11D1-B16A-00C0F0283628} 
            Text            =   "aaa"
            Object.Width           =   2646
         EndProperty
      End
      Begin Project1.ToolbarControl pbList 
         Height          =   690
         Left            =   120
         TabIndex        =   108
         Top             =   240
         Width           =   3975
         _ExtentX        =   7011
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_FieldsSelection 
      Height          =   1095
      Left            =   9570
      TabIndex        =   22
      Top             =   8775
      Visible         =   0   'False
      Width           =   3375
      Begin Project1.ArmGrid grdFrom 
         Height          =   1695
         Left            =   120
         TabIndex        =   23
         Top             =   240
         Width           =   1455
         _ExtentX        =   11456
         _ExtentY        =   9763
      End
      Begin Project1.ArmGrid grdTo 
         Height          =   1695
         Left            =   1680
         TabIndex        =   24
         Top             =   240
         Width           =   1335
         _ExtentX        =   11456
         _ExtentY        =   9763
      End
   End
   Begin VB.Frame frm_Field 
      Height          =   5895
      Left            =   570
      TabIndex        =   51
      Top             =   1155
      Visible         =   0   'False
      Width           =   14055
      Begin VB.TextBox txt_Out_Column_Hdr_Request 
         Height          =   375
         Left            =   5760
         TabIndex        =   60
         Top             =   960
         Width           =   7560
      End
      Begin Project1.ArmCombobox cbo_Crt_Type 
         Height          =   345
         Left            =   5745
         TabIndex        =   74
         Top             =   3600
         Width           =   3030
         _ExtentX        =   5345
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Out_Alignment 
         Height          =   345
         Left            =   5745
         TabIndex        =   63
         Top             =   1800
         Width           =   2070
         _ExtentX        =   3651
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Out_Order 
         Height          =   345
         Left            =   10335
         TabIndex        =   64
         Top             =   1440
         Width           =   1065
         _ExtentX        =   1879
         _ExtentY        =   609
      End
      Begin VB.CheckBox chk_Out_Can_Select_Logic 
         Caption         =   "#Can select logic"
         Height          =   255
         Left            =   11160
         TabIndex        =   70
         Top             =   2280
         Width           =   2175
      End
      Begin VB.CheckBox chk_Out_Can_Change_Join 
         Caption         =   "#Can change join type"
         Height          =   255
         Left            =   9120
         TabIndex        =   69
         Tag             =   "lbl_Out_Can_Change_Join"
         Top             =   2280
         Width           =   1935
      End
      Begin VB.TextBox txt_out_field_id 
         Height          =   285
         Left            =   5640
         TabIndex        =   102
         TabStop         =   0   'False
         Top             =   7080
         Visible         =   0   'False
         Width           =   2415
      End
      Begin MSComctlLib.ListView lvw_Crt_Report_Operator 
         Height          =   2535
         Left            =   120
         TabIndex        =   71
         Top             =   2880
         Width           =   3855
         _ExtentX        =   6800
         _ExtentY        =   4471
         View            =   2
         LabelEdit       =   1
         LabelWrap       =   -1  'True
         HideSelection   =   -1  'True
         Checkboxes      =   -1  'True
         _Version        =   393217
         ForeColor       =   -2147483640
         BackColor       =   -2147483643
         BorderStyle     =   1
         Appearance      =   1
         NumItems        =   0
      End
      Begin VB.TextBox txt_crt_static_request_Addition 
         Height          =   375
         Left            =   5760
         TabIndex        =   79
         Top             =   4680
         Width           =   7575
      End
      Begin VB.TextBox txt_crt_static_request 
         Height          =   1215
         Left            =   120
         MultiLine       =   -1  'True
         ScrollBars      =   2  'Vertical
         TabIndex        =   81
         Top             =   5640
         Width           =   13215
      End
      Begin Project1.ArmCombobox cbo_Crt_Come_From_Table 
         Height          =   345
         Left            =   10320
         TabIndex        =   77
         Top             =   3960
         Width           =   3015
         _ExtentX        =   5318
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Crt_Field_Name 
         Height          =   345
         Left            =   5760
         TabIndex        =   78
         Top             =   4320
         Width           =   7575
         _ExtentX        =   13361
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Crt_Field_Code 
         Height          =   345
         Left            =   5760
         TabIndex        =   75
         Top             =   3960
         Width           =   3015
         _ExtentX        =   5318
         _ExtentY        =   609
      End
      Begin VB.TextBox txt_Out_Width 
         Height          =   350
         Left            =   10320
         TabIndex        =   65
         Top             =   1800
         Width           =   1575
      End
      Begin Project1.ArmCombobox cbo_Out_Field_Join 
         Height          =   345
         Left            =   5760
         TabIndex        =   72
         Top             =   2760
         Width           =   7575
         _ExtentX        =   13361
         _ExtentY        =   609
      End
      Begin VB.CheckBox chk_Out_Hidden 
         Caption         =   "#Hidden"
         Height          =   255
         Left            =   7800
         TabIndex        =   68
         Tag             =   "lbl_Out_Hidden"
         Top             =   2280
         Width           =   1215
      End
      Begin MSComctlLib.ListView lvw_Out_Measure_Function 
         Height          =   1245
         Left            =   1320
         TabIndex        =   61
         Top             =   1440
         Width           =   2655
         _ExtentX        =   4683
         _ExtentY        =   2196
         View            =   3
         LabelEdit       =   1
         LabelWrap       =   0   'False
         HideSelection   =   0   'False
         HideColumnHeaders=   -1  'True
         Checkboxes      =   -1  'True
         _Version        =   393217
         ForeColor       =   -2147483640
         BackColor       =   -2147483643
         BorderStyle     =   1
         Appearance      =   1
         NumItems        =   1
         BeginProperty ColumnHeader(1) {BDD1F052-858B-11D1-B16A-00C0F0283628} 
            Object.Width           =   2540
         EndProperty
      End
      Begin VB.CheckBox chk_Out_Can_Be_Group_By 
         Caption         =   "#Can be group by"
         Height          =   255
         Left            =   5760
         TabIndex        =   67
         Top             =   2280
         Width           =   1935
      End
      Begin VB.CheckBox chk_Out_Can_Be_Measure 
         Caption         =   "#Can be measure"
         Height          =   255
         Left            =   4080
         TabIndex        =   66
         Top             =   2280
         Width           =   1935
      End
      Begin Project1.ArmCombobox cbo_Out_Field_Tag 
         Height          =   345
         Left            =   10320
         TabIndex        =   59
         Top             =   600
         Width           =   3015
         _ExtentX        =   5318
         _ExtentY        =   609
      End
      Begin VB.TextBox txt_Out_Field_Name 
         Height          =   350
         Left            =   1320
         TabIndex        =   53
         Top             =   240
         Width           =   3015
      End
      Begin Project1.ArmCombobox cbo_Out_Format 
         Height          =   345
         Left            =   5760
         TabIndex        =   62
         Top             =   1440
         Width           =   2055
         _ExtentX        =   3625
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Crt_Field_Prefix 
         Height          =   345
         Left            =   10320
         TabIndex        =   76
         Top             =   3600
         Width           =   1575
         _ExtentX        =   2778
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Out_Field_Prefix 
         Height          =   345
         Left            =   1320
         TabIndex        =   55
         Top             =   960
         Width           =   1455
         _ExtentX        =   2566
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_out_come_from_table 
         Height          =   345
         Left            =   1320
         TabIndex        =   54
         Top             =   600
         Width           =   3015
         _ExtentX        =   5318
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Out_Master_Table 
         Height          =   345
         Left            =   5760
         TabIndex        =   56
         Top             =   240
         Width           =   3015
         _ExtentX        =   5318
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Out_Master_Table_Prefix 
         Height          =   345
         Left            =   5760
         TabIndex        =   57
         Top             =   600
         Width           =   1575
         _ExtentX        =   2778
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Out_Field_Code 
         Height          =   345
         Left            =   10320
         TabIndex        =   58
         Top             =   240
         Width           =   3015
         _ExtentX        =   5318
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Crt_Grid_Tag 
         Height          =   345
         Left            =   5760
         TabIndex        =   80
         Top             =   5040
         Width           =   7575
         _ExtentX        =   13361
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Out_Crosslink_Request 
         Height          =   345
         Left            =   5760
         TabIndex        =   73
         Top             =   3120
         Width           =   7575
         _ExtentX        =   13361
         _ExtentY        =   609
      End
      Begin VB.Label lbl_Column_Hdr_Request 
         Caption         =   "#Column header req"
         Height          =   255
         Left            =   4065
         TabIndex        =   126
         Tag             =   "lbl_Column_Hdr_Request"
         Top             =   1035
         Width           =   1665
      End
      Begin VB.Label lbl_out_crosslink_request 
         Caption         =   "#Crosslink request"
         Height          =   255
         Left            =   4080
         TabIndex        =   118
         Top             =   3120
         Width           =   1575
      End
      Begin VB.Label lbl_crt_grid 
         Caption         =   "#Criteria grid"
         Height          =   255
         Left            =   4080
         TabIndex        =   117
         Tag             =   "lbl_crt_grid"
         Top             =   5040
         Width           =   1575
      End
      Begin VB.Label lbl_Out_Measure 
         Caption         =   "#Measure"
         Height          =   255
         Left            =   120
         TabIndex        =   101
         Top             =   1440
         Width           =   1215
      End
      Begin VB.Label lbl_crt_static_request 
         Caption         =   "#Static request"
         Height          =   255
         Left            =   120
         TabIndex        =   100
         Top             =   5400
         Width           =   1455
      End
      Begin VB.Label lbl_crt_static_request_Addition 
         Caption         =   "#Criteria addition"
         Height          =   255
         Left            =   4080
         TabIndex        =   99
         Top             =   4680
         Width           =   1575
      End
      Begin VB.Label lbl_Crt_Report_Operator 
         Caption         =   "#Crt. operator"
         Height          =   255
         Left            =   120
         TabIndex        =   98
         Top             =   2640
         Width           =   1215
      End
      Begin VB.Label lbl_Crt_Field_Prefix 
         Caption         =   "#Criteria prefix"
         Height          =   255
         Left            =   8880
         TabIndex        =   97
         Top             =   3600
         Width           =   1455
      End
      Begin VB.Label lbl_crt_come_from_table 
         Caption         =   "#Criteria table"
         Height          =   255
         Left            =   8880
         TabIndex        =   96
         Top             =   3975
         Width           =   1455
      End
      Begin VB.Label lbl_Crt_Type 
         Caption         =   "#Criteria type"
         Height          =   255
         Left            =   4080
         TabIndex        =   95
         Top             =   3600
         Width           =   1575
      End
      Begin VB.Label lbl_Crt_Field_Name 
         Caption         =   "#Criteria field name"
         Height          =   255
         Left            =   4080
         TabIndex        =   94
         Top             =   4320
         Width           =   1575
      End
      Begin VB.Label lbl_Crt_Field_Code 
         Caption         =   "#Criteria field code"
         Height          =   255
         Left            =   4080
         TabIndex        =   93
         Top             =   3960
         Width           =   1575
      End
      Begin VB.Label Label3 
         Caption         =   "#Field width"
         Height          =   255
         Left            =   8880
         TabIndex        =   92
         Top             =   1800
         Width           =   1455
      End
      Begin VB.Label Label2 
         Caption         =   "#Field alignment"
         Height          =   255
         Left            =   4080
         TabIndex        =   91
         Top             =   1800
         Width           =   1575
      End
      Begin VB.Label Label1 
         Caption         =   "#Field format"
         Height          =   255
         Left            =   4080
         TabIndex        =   90
         Top             =   1440
         Width           =   1575
      End
      Begin VB.Label lbl_Out_Field_Join 
         Caption         =   "#Field join"
         Height          =   255
         Left            =   4080
         TabIndex        =   89
         Top             =   2760
         Width           =   1575
      End
      Begin VB.Label lbl_Out_Order 
         Caption         =   "#Order"
         Height          =   255
         Left            =   8880
         TabIndex        =   88
         Top             =   1440
         Width           =   1455
      End
      Begin VB.Label lbl_Field_Code 
         Caption         =   "#Field code"
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Left            =   8880
         TabIndex        =   87
         Top             =   240
         Width           =   1455
      End
      Begin VB.Label lbl_Master_Table_Prefix 
         Caption         =   "#Master prefix"
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Left            =   4440
         TabIndex        =   86
         Top             =   600
         Width           =   1335
      End
      Begin VB.Label lbl_Master_Table 
         Caption         =   "#Master table"
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Left            =   4440
         TabIndex        =   85
         Top             =   240
         Width           =   1335
      End
      Begin VB.Label lbl_Business_Name 
         Caption         =   "#Business name"
         Height          =   255
         Left            =   8880
         TabIndex        =   84
         Top             =   600
         Width           =   1455
      End
      Begin VB.Label lbl_Out_Field_Prefix 
         Caption         =   "#Field prefix"
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Left            =   120
         TabIndex        =   83
         Top             =   960
         Width           =   1215
      End
      Begin VB.Label lbl_Out_Com_From_Table 
         Caption         =   "#Table"
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Left            =   120
         TabIndex        =   82
         Top             =   600
         Width           =   1215
      End
      Begin VB.Label lbl_Out_Field_Name 
         Caption         =   "#Field name"
         BeginProperty Font 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         Height          =   255
         Left            =   120
         TabIndex        =   52
         Top             =   240
         Width           =   1215
      End
   End
   Begin VB.Frame frm_FieldsTemp 
      Height          =   975
      Left            =   6960
      TabIndex        =   49
      Top             =   1320
      Visible         =   0   'False
      Width           =   2535
      Begin Project1.ArmGrid grdLst 
         Height          =   615
         Index           =   2
         Left            =   120
         TabIndex        =   50
         Tag             =   "grd_FieldsTemplate"
         Top             =   240
         Width           =   2295
         _ExtentX        =   4048
         _ExtentY        =   1085
      End
   End
   Begin VB.Frame frm_Find 
      Height          =   975
      Left            =   5880
      TabIndex        =   5
      Top             =   4440
      Visible         =   0   'False
      Width           =   4335
      Begin VB.TextBox txt_Find 
         Height          =   375
         Left            =   120
         TabIndex        =   6
         Top             =   360
         Width           =   2775
      End
      Begin Project1.ToolbarControl pbFind 
         Height          =   690
         Left            =   3000
         TabIndex        =   107
         Top             =   240
         Width           =   1215
         _ExtentX        =   2143
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_Combo 
      Height          =   4215
      Left            =   6420
      TabIndex        =   25
      Top             =   3975
      Visible         =   0   'False
      Width           =   4335
      Begin Project1.ArmCombobox cbo_ComboOperator 
         Height          =   345
         Left            =   120
         TabIndex        =   123
         Top             =   1065
         Width           =   1395
         _ExtentX        =   2461
         _ExtentY        =   609
      End
      Begin Project1.ArmCombobox cbo_Combo 
         Height          =   345
         Left            =   120
         TabIndex        =   26
         Top             =   1440
         Width           =   3975
         _ExtentX        =   7011
         _ExtentY        =   609
      End
      Begin Project1.ToolbarControl pbCombo 
         Height          =   690
         Left            =   120
         TabIndex        =   110
         Top             =   240
         Width           =   4095
         _ExtentX        =   7223
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_Sorting 
      Height          =   6135
      Left            =   450
      TabIndex        =   20
      Top             =   4800
      Visible         =   0   'False
      Width           =   3135
      Begin Project1.ToolbarControl pbSorting 
         Height          =   690
         Left            =   120
         TabIndex        =   103
         Top             =   240
         Width           =   2895
         _ExtentX        =   5106
         _ExtentY        =   1217
      End
      Begin VB.ListBox lst_Sorting 
         Height          =   4935
         Left            =   120
         TabIndex        =   21
         Top             =   1080
         Width           =   2895
      End
   End
   Begin VB.Frame frm_Measure 
      Height          =   3015
      Left            =   3600
      TabIndex        =   17
      Top             =   4680
      Visible         =   0   'False
      Width           =   2655
      Begin MSComctlLib.ListView lvw_Measure 
         Height          =   1815
         Left            =   120
         TabIndex        =   18
         Top             =   1080
         Width           =   2415
         _ExtentX        =   4260
         _ExtentY        =   3201
         View            =   3
         LabelEdit       =   1
         LabelWrap       =   -1  'True
         HideSelection   =   -1  'True
         HideColumnHeaders=   -1  'True
         Checkboxes      =   -1  'True
         _Version        =   393217
         ForeColor       =   -2147483640
         BackColor       =   -2147483643
         BorderStyle     =   1
         Appearance      =   1
         NumItems        =   1
         BeginProperty ColumnHeader(1) {BDD1F052-858B-11D1-B16A-00C0F0283628} 
            Object.Width           =   3528
         EndProperty
      End
      Begin Project1.ToolbarControl pbMeasure 
         Height          =   690
         Left            =   120
         TabIndex        =   105
         Top             =   240
         Width           =   2415
         _ExtentX        =   4260
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_Value 
      Height          =   1935
      Left            =   6540
      TabIndex        =   14
      Top             =   7770
      Visible         =   0   'False
      Width           =   4335
      Begin Project1.ArmCombobox cbo_ValueOperator 
         Height          =   345
         Left            =   120
         TabIndex        =   124
         Top             =   1020
         Width           =   1590
         _ExtentX        =   2805
         _ExtentY        =   609
      End
      Begin VB.TextBox txt_Val2 
         Height          =   375
         Left            =   2400
         TabIndex        =   16
         Top             =   1440
         Width           =   1815
      End
      Begin VB.TextBox txt_Val1 
         Height          =   375
         Left            =   120
         TabIndex        =   15
         Top             =   1440
         Width           =   1815
      End
      Begin Project1.ToolbarControl pbValue 
         Height          =   690
         Left            =   120
         TabIndex        =   106
         Top             =   240
         Width           =   4095
         _ExtentX        =   7223
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_Date 
      Height          =   3615
      Left            =   7680
      TabIndex        =   11
      Top             =   5670
      Visible         =   0   'False
      Width           =   4335
      Begin Project1.ArmCombobox cbo_DateOperator 
         Height          =   345
         Left            =   120
         TabIndex        =   125
         Top             =   1035
         Width           =   1770
         _ExtentX        =   3122
         _ExtentY        =   609
      End
      Begin Project1.A_calocx cal2 
         Height          =   375
         Left            =   2400
         TabIndex        =   13
         Top             =   1440
         Width           =   1815
         _ExtentX        =   3201
         _ExtentY        =   661
      End
      Begin Project1.A_calocx cal1 
         Height          =   375
         Left            =   120
         TabIndex        =   12
         Top             =   1440
         Width           =   1815
         _ExtentX        =   3201
         _ExtentY        =   661
      End
      Begin Project1.ToolbarControl pbDate 
         Height          =   690
         Left            =   120
         TabIndex        =   109
         Top             =   240
         Width           =   4095
         _ExtentX        =   7223
         _ExtentY        =   1217
      End
   End
   Begin VB.Frame frm_Share 
      Height          =   3735
      Left            =   120
      TabIndex        =   7
      Top             =   5880
      Visible         =   0   'False
      Width           =   4335
      Begin Project1.ArmCheckView cv_Share 
         Height          =   2655
         Left            =   120
         TabIndex        =   8
         Tag             =   "checkview"
         Top             =   960
         Width           =   4095
         _ExtentX        =   7223
         _ExtentY        =   4683
      End
      Begin Project1.ToolbarControl pbShare 
         Height          =   660
         Left            =   120
         TabIndex        =   104
         Top             =   240
         Width           =   4095
         _ExtentX        =   5106
         _ExtentY        =   1217
      End
   End
   Begin MSComctlLib.TabStrip tbsBar 
      Height          =   375
      Left            =   0
      TabIndex        =   0
      Top             =   0
      Width           =   10095
      _ExtentX        =   17806
      _ExtentY        =   661
      _Version        =   393216
      BeginProperty Tabs {1EFB6598-857C-11D1-B16A-00C0F0283628} 
         NumTabs         =   3
         BeginProperty Tab1 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Execute"
            Key             =   "G0"
            Object.Tag             =   "tbs_Exec"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab2 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Design"
            Key             =   "G1"
            Object.Tag             =   "tbs_Design"
            ImageVarType    =   2
         EndProperty
         BeginProperty Tab3 {1EFB659A-857C-11D1-B16A-00C0F0283628} 
            Caption         =   "#Field template"
            Key             =   "G2"
            Object.Tag             =   "tbs_FieldsTemplate"
            ImageVarType    =   2
         EndProperty
      EndProperty
   End
   Begin VB.Frame frm_Design 
      Height          =   2505
      Left            =   0
      TabIndex        =   33
      Top             =   1200
      Visible         =   0   'False
      Width           =   2715
      Begin VB.Frame frm_DescDesign 
         Height          =   1455
         Left            =   120
         TabIndex        =   35
         Top             =   840
         Width           =   10935
         Begin VB.TextBox txt_MasterDesign 
            Height          =   345
            Left            =   2640
            Locked          =   -1  'True
            TabIndex        =   45
            Top             =   960
            Width           =   2655
         End
         Begin VB.TextBox txt_NameDesign 
            Height          =   345
            Left            =   1440
            TabIndex        =   40
            Top             =   240
            Width           =   3855
         End
         Begin VB.TextBox txt_DescDesign 
            Height          =   735
            Left            =   5400
            MultiLine       =   -1  'True
            ScrollBars      =   2  'Vertical
            TabIndex        =   41
            Top             =   600
            Width           =   4335
         End
         Begin VB.TextBox txt_OwnerDesign 
            Height          =   345
            Left            =   2640
            Locked          =   -1  'True
            TabIndex        =   42
            Top             =   600
            Width           =   2655
         End
         Begin VB.Label lbl_MasterDesign 
            Caption         =   "#Reports driving entity"
            Height          =   255
            Left            =   120
            TabIndex        =   44
            Tag             =   "lbl_MasterTable"
            Top             =   1080
            Width           =   1695
         End
         Begin VB.Label lbl_NameDesign 
            Caption         =   "#Name"
            Height          =   255
            Left            =   120
            TabIndex        =   43
            Tag             =   "lbl_Name"
            Top             =   360
            Width           =   975
         End
         Begin VB.Label lbl_DescDesign 
            Caption         =   "#Description"
            Height          =   255
            Left            =   5400
            TabIndex        =   37
            Tag             =   "lbl_Description"
            Top             =   320
            Width           =   1455
         End
         Begin VB.Label lbl_OwnerDesign 
            Caption         =   "#Owner"
            Height          =   255
            Left            =   120
            TabIndex        =   36
            Tag             =   "lbl_Owner"
            Top             =   720
            Width           =   975
         End
      End
      Begin Project1.ArmTreeView tvItem 
         Height          =   615
         Left            =   75
         TabIndex        =   34
         Top             =   160
         Width           =   3495
         _ExtentX        =   6165
         _ExtentY        =   1085
      End
      Begin Project1.ArmGrid grdLst 
         Height          =   495
         Index           =   1
         Left            =   3600
         TabIndex        =   38
         Tag             =   "grid"
         Top             =   160
         Width           =   4095
         _ExtentX        =   7223
         _ExtentY        =   873
      End
   End
   Begin VB.Frame frm_Exec 
      Height          =   1815
      Left            =   3360
      TabIndex        =   1
      Top             =   1320
      Visible         =   0   'False
      Width           =   2415
      Begin VB.CheckBox chk_Distinct 
         Caption         =   "#Distinct"
         Height          =   255
         Left            =   7320
         TabIndex        =   48
         Tag             =   "lbl_Distinct"
         Top             =   120
         Width           =   1095
      End
      Begin VB.CheckBox chk_GrandTotal 
         Caption         =   "#Grand total"
         Height          =   255
         Left            =   5640
         TabIndex        =   39
         Tag             =   "lbl_GrandTotal"
         Top             =   360
         Value           =   1  'Checked
         Width           =   1695
      End
      Begin VB.Frame frm_DescExec 
         Height          =   1215
         Left            =   120
         TabIndex        =   28
         Top             =   1680
         Width           =   10935
         Begin VB.TextBox txt_MasterExec 
            Height          =   345
            Left            =   1920
            LinkItem        =   "txt_MasterTable"
            Locked          =   -1  'True
            TabIndex        =   47
            Top             =   720
            Width           =   2655
         End
         Begin VB.TextBox txt_DescExec 
            Height          =   735
            Left            =   4680
            Locked          =   -1  'True
            MultiLine       =   -1  'True
            ScrollBars      =   2  'Vertical
            TabIndex        =   30
            Top             =   360
            Width           =   5775
         End
         Begin VB.TextBox txt_OwnerExec 
            Height          =   345
            Left            =   1920
            Locked          =   -1  'True
            TabIndex        =   29
            Tag             =   "lbl_Owner"
            Top             =   360
            Width           =   2655
         End
         Begin VB.Label lbl_MasterExec 
            Caption         =   "#Reports driving entity"
            Height          =   255
            Left            =   120
            TabIndex        =   46
            Tag             =   "lbl_MasterTable"
            Top             =   840
            Width           =   1935
         End
         Begin VB.Label lbl_DescExec 
            Caption         =   "#Description"
            Height          =   255
            Left            =   4680
            TabIndex        =   32
            Tag             =   "lbl_Description"
            Top             =   120
            Width           =   1335
         End
         Begin VB.Label lbl_OwnerExec 
            Caption         =   "#Owner"
            Height          =   255
            Left            =   120
            TabIndex        =   31
            Top             =   480
            Width           =   1095
         End
      End
      Begin VB.CheckBox chk_RepeatLines 
         Caption         =   "#Repeat lines"
         Height          =   255
         Left            =   5640
         TabIndex        =   2
         Tag             =   "lbl_RepeatLines"
         Top             =   120
         Value           =   1  'Checked
         Width           =   1695
      End
      Begin Project1.ArmCombobox cbo_template 
         Height          =   345
         Left            =   1560
         TabIndex        =   3
         Top             =   200
         Width           =   3855
         _ExtentX        =   6800
         _ExtentY        =   609
      End
      Begin Project1.ArmGrid grdLst 
         Height          =   615
         Index           =   0
         Left            =   120
         TabIndex        =   27
         Tag             =   "grid"
         Top             =   650
         Width           =   9615
         _ExtentX        =   16960
         _ExtentY        =   1085
      End
      Begin VB.Label lbl_RptTemplate 
         Caption         =   "#Report template"
         Height          =   255
         Left            =   120
         TabIndex        =   4
         Tag             =   "lbl_Template"
         Top             =   240
         Width           =   1815
      End
   End
   Begin Project1.ToolbarControl pbItem 
      Height          =   690
      Left            =   0
      TabIndex        =   111
      Top             =   360
      Width           =   10095
      _ExtentX        =   17806
      _ExtentY        =   1217
   End
End
Attribute VB_Name = "ArmReporting"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Private Const scrExecute = 0
Private Const scrDesign = 1
Private Const scrFieldsTemplate = 2
Private Const scrReport = 3

Private Const TBR_Add = "A"
Private Const TBR_Update = "B"
Private Const TBR_Delete = "C"
Private Const TBR_Print = "D"
Private Const TBR_Audit = "E"
Private Const TBR_Refresh = "F"
Private Const TBR_Excel = "G"
Private Const TBR_Valid = "H"
Private Const TBR_Undo = "I"
Private Const TBR_OpLT = "J"
Private Const TBR_OpGT = "K"
Private Const TBR_Execute = "L"
Private Const TBR_Find = "M"
Private Const TBR_View = "N"
Private Const TBR_Restore = "O"
Private Const TBR_Save = "P"
Private Const TBR_Language = "Q"
Private Const TBR_SelectAll = "j"
Private Const TBR_Help = "S"
Private Const TBR_Quit = "T"
Private Const TBR_Media = "U"
Private Const TBR_Memo = "V"
Private Const TBR_Previous = "Z"
Private Const TBR_Next = "Y"
Private Const TBR_New = "Z"
Private Const TBR_Share = "a"
Private Const TBR_Copy = "b"
Private Const TBR_Exit = "R"

Private mInitialized As Boolean

Private Const frmSpacing = 75
Private Const SEP = "®©"
Private Const USERSEP = ";"
Private Const RPT_ERR_MSG = -1000 'this has to be set to correct number
Private Const COLOR_HIDDEN = 13158600 'color which mark row in grid with hidden template fields

Private Const MAX_LEVELS = 12

Private Const NODE_RIGHT = 3
Private Const NODE_OWNER = 4

Private Const TV_IMAGE_FOLDER_NORMAL = 1
Private Const TV_IMAGE_FOLDER_OPEN = 2
Private Const TV_IMAGE_NORIGHT = 0
Private Const TV_IMAGE_EXECUTE = 1
Private Const TV_IMAGE_INHERIT = 2
Private Const TV_IMAGE_INHERITEXECUTE = 3

'windows API call from user32 to send message to a window (control)
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
                            (ByVal hwnd As Long, _
                            ByVal wMsg As Long, _
                            wParam As Any, _
                           lParam As Any) As Long   ' <--- !!

'checkview messages for driving checkview behaviour
Private Const LVM_FIRST = &H1000
Private Const LVM_GETCOLUMNWIDTH = LVM_FIRST + 29
Private Const LVM_SETCOLUMNWIDTH = LVM_FIRST + 30
Private Const LVSCW_AUTOSIZE = -1
Private Const LVSCW_AUTOSIZE_USEHEADER = -2

'field type enumeration
Private Enum ArmSysType
  DBTYPE_EMPTY = 0
  DBTYPE_I4 = 3
  DBTYPE_R4 = 4
  DBTYPE_DATE = 7
  DBTYPE_BSTR = 8 '- UNICODE string
  DBTYPE_BOOL = 11
  DBTYPE_STR = 129
  DBTYPE_BMP = 999
End Enum

Public Enum RptMode
  RPT_MODE_VIEW_EXEC = 0
  RPT_MODE_VIEW_DESIGN = 1
  RPT_MODE_VIEW_FIELDS = 2
  RPT_MODE_VIEW_REPORT = 3
  RPT_MODE_INHERITE_TEMPLATE = 4
  RPT_MODE_NEW_TEMPLATE = 5
  RPT_MODE_EDIT_TEMPLATE = 6
  RPT_MODE_EDIT_SELECTION = 7
  RPT_MODE_NEW_FIELD = 8
  RPT_MODE_EDIT_FIELD = 9
  RPT_MODE_COPY_TEMPLATE = 10
End Enum

Private mo_Db As ARMSYSCOMLib.ArmDb
Private ms_Language As String
Private ms_Server As String
Private ms_Db As String
Private ms_User As String
Private ms_Pwd As String
Private ms_App As String
Private ms_UserID As String
Private ms_ConnectString As String
Private mb_InternalConnection As Boolean

Private mo_DesignTemplate As ArmRptTemplate
Private mo_ExecTemplate As ArmRptTemplate
Private mo_UndoTemplate As ArmRptTemplate
Private ml_GridIndex As Long
Private ml_LastFindCol As Long
Private ml_LastFindRow As Long
Private mo_CurFieldDef As ArmFieldDef
Private mo_CurParentFieldDef As ArmFieldDef

Private mt_Mode As RptMode
Private ma_Operators() As rpt_Operator
Private ms_TextGrandTotal As String
Private ms_TextSubTotal As String
Private mb_ITTemplateAdmin As Boolean

Private ml_TempSave_Mdl_Id As Long
Event pbItemAction(as_Action As String, ab_Allow As Boolean)
Public Event quit()

Private Type Rpt_Log
  rpt_tpl_list_ID As Long
  Rpt_Tpl_Name As String
  rpt_userID As String
  rpt_language As String
  rpt_sql As String
  rpt_time As Double
  rpt_success As String
End Type

Private Type rpt_Operator
  rpt_Operator As String
  rpt_Operand_Count As Long
  rpt_Operator_Clause As String
  rpt_Operator_Clause_Display As String
End Type

Public Function Load_A_COM() As Boolean

On Error GoTo ErrorHandler

  Set mo_DesignTemplate = New ArmRptTemplate
  Call mo_DesignTemplate.Load_A_COM
  
  Set mo_ExecTemplate = New ArmRptTemplate
  Call mo_ExecTemplate.Load_A_COM
  
  Set mo_UndoTemplate = New ArmRptTemplate
  Call mo_UndoTemplate.Load_A_COM
  
  mt_Mode = RPT_MODE_VIEW_EXEC
  Call pbItem.Load_A_COM
  Call pbFind.Load_A_COM
  Call pbShare.Load_A_COM
  Call pbMeasure.Load_A_COM
  Call pbDate.Load_A_COM
  Call pbValue.Load_A_COM
  Call pbList.Load_A_COM
  Call pbGrid.Load_A_COM
  Call pbSorting.Load_A_COM
  Call pbCombo.Load_A_COM
  
  Call cv_Share.Load_A_COM
  Call tvItem.Load_A_COM
  Call grdlst(scrFieldsTemplate).Load_A_COM
  Call grdlst(scrDesign).Load_A_COM
  Call grdlst(scrExecute).Load_A_COM
  Call grdFrom.Load_A_COM
  Call grdTo.Load_A_COM
  Call grd_Filter.Load_A_COM
  Call grd_Criteria.Load_A_COM
  grd_Criteria.MaxRows = 100
  ml_GridIndex = scrReport + 1
  Call cbo_template.Load_A_COM
  Call cbo_Combo.Load_A_COM
  Call cal1.reinit_cal
  Call cal2.reinit_cal
  
  Call cbo_out_come_from_table.Load_A_COM
  Call cbo_Out_Field_Prefix.Load_A_COM
  Call cbo_Out_Master_Table.Load_A_COM
  Call cbo_Out_Master_Table_Prefix.Load_A_COM
  Call cbo_Out_Field_Code.Load_A_COM
  Call cbo_Out_Field_Tag.Load_A_COM
  Call cbo_Crt_Grid_Tag.Load_A_COM
  
  Call cbo_Out_Format.Load_A_COM
  Call cbo_Out_Field_Join.Load_A_COM
  Call cbo_Out_Crosslink_Request.Load_A_COM
  Call cbo_Crt_Field_Code.Load_A_COM
  Call cbo_Crt_Field_Name.Load_A_COM
  Call cbo_Crt_Come_From_Table.Load_A_COM
  Call cbo_Crt_Field_Prefix.Load_A_COM
  
  Call cbo_GridLogic.Load_A_COM
  Call cbo_GridOperator.Load_A_COM
  Call cbo_ListLogic.Load_A_COM
  Call cbo_ListOperator.Load_A_COM
  Call cbo_Out_Alignment.Load_A_COM
  Call cbo_Crt_Type.Load_A_COM
  Call cbo_Out_Order.Load_A_COM
  Call cbo_ComboOperator.Load_A_COM
  Call cbo_ValueOperator.Load_A_COM
  Call cbo_DateOperator.Load_A_COM
  
    
  cbo_out_come_from_table.Locked = False
  cbo_Out_Field_Prefix.Locked = False
  cbo_Out_Master_Table.Locked = False
  cbo_Out_Master_Table_Prefix.Locked = False
  cbo_Out_Field_Tag.FirstBlankItem = True
  cbo_Crt_Grid_Tag.Locked = False
  cbo_Crt_Grid_Tag.FirstBlankItem = True
  cbo_Out_Field_Code.Locked = False
  cbo_Out_Format.Locked = False
  cbo_Out_Field_Join.Locked = False
  cbo_Out_Crosslink_Request.Locked = False
  cbo_Crt_Field_Code.Locked = False
  cbo_Crt_Field_Name.Locked = False
  cbo_Crt_Come_From_Table.Locked = False
  cbo_Crt_Field_Prefix.Locked = False
  
  ml_LastFindCol = 1
  ml_LastFindRow = 0
  mInitialized = True
  
  Load_A_COM = True
  Exit Function
ErrorHandler:
  Load_A_COM = False
End Function

Public Function Unload_A_COM() As Boolean
Dim ll_Index As Long

On Error GoTo ErrorHandler
  
  Call cbo_out_come_from_table.Unload_A_COM
  Call cbo_Out_Field_Prefix.Unload_A_COM
  Call cbo_Out_Master_Table.Unload_A_COM
  Call cbo_Out_Master_Table_Prefix.Unload_A_COM
  Call cbo_Out_Field_Code.Unload_A_COM
  Call cbo_Out_Field_Tag.Unload_A_COM
  Call cbo_Crt_Grid_Tag.Unload_A_COM
  Call cbo_Out_Format.Unload_A_COM
  Call cbo_Out_Field_Join.Unload_A_COM
  Call cbo_Out_Crosslink_Request.Unload_A_COM
  Call cbo_Crt_Field_Code.Unload_A_COM
  Call cbo_Crt_Field_Name.Unload_A_COM
  Call cbo_Crt_Come_From_Table.Unload_A_COM
  Call cbo_Crt_Field_Prefix.Unload_A_COM
  
  Call cbo_GridLogic.Unload_A_COM
  Call cbo_GridOperator.Unload_A_COM
  Call cbo_ListLogic.Unload_A_COM
  Call cbo_ListOperator.Unload_A_COM
  Call cbo_Out_Alignment.Unload_A_COM
  Call cbo_Crt_Type.Unload_A_COM
  Call cbo_Out_Order.Unload_A_COM
  Call cbo_ComboOperator.Unload_A_COM
  Call cbo_ValueOperator.Unload_A_COM
  Call cbo_DateOperator.Unload_A_COM
  
  Call grdlst(scrFieldsTemplate).Unload_A_COM
  Call grdlst(scrDesign).Unload_A_COM
  Call grdlst(scrExecute).Unload_A_COM
  Call grdFrom.Unload_A_COM
  Call grdTo.Unload_A_COM
  Call grd_Filter.Unload_A_COM
  Call grd_Criteria.Unload_A_COM
  
  Call cbo_template.Unload_A_COM
  Call cbo_Combo.Unload_A_COM
  Call pbItem.Unload_A_COM
  Call pbFind.Unload_A_COM
  Call pbShare.Unload_A_COM
  Call pbMeasure.Unload_A_COM
  Call pbList.Unload_A_COM
  Call pbGrid.Unload_A_COM
  Call pbDate.Unload_A_COM
  Call pbValue.Unload_A_COM
  Call pbSorting.Unload_A_COM
  Call pbCombo.Unload_A_COM
  
  Call cv_Share.Unload_A_COM
  Call tvItem.Unload_A_COM
  
  'delete all created reports
  For ll_Index = tbsBar.Tabs.Count To 1 Step -1
    Call DeleteTabReport(ll_Index)
  Next
  
  If mb_InternalConnection Then
    Call CloseConnection
  End If
  
  Set mo_Db = Nothing
  If Not (mo_DesignTemplate Is Nothing) Then
    Call mo_DesignTemplate.Unload_A_COM
    Set mo_DesignTemplate = Nothing
  End If
  If Not (mo_ExecTemplate Is Nothing) Then
    Call mo_ExecTemplate.Unload_A_COM
    Set mo_ExecTemplate = Nothing
  End If
  If Not (mo_UndoTemplate Is Nothing) Then
    Call mo_UndoTemplate.Unload_A_COM
    Set mo_UndoTemplate = Nothing
  End If
  Unload_A_COM = True
  Exit Function
ErrorHandler:
  Unload_A_COM = False
End Function

Public Property Set ArmDb(ao_Db As ARMSYSCOMLib.ArmDb)

  Set mo_Db = ao_Db
  Set pbItem.ArmDb = ao_Db
  Set pbFind.ArmDb = ao_Db
  Set pbShare.ArmDb = ao_Db
  Set pbMeasure.ArmDb = ao_Db
  Set pbList.ArmDb = ao_Db
  Set pbGrid.ArmDb = ao_Db
  Set pbDate.ArmDb = ao_Db
  Set pbValue.ArmDb = ao_Db
  Set pbSorting.ArmDb = ao_Db
  Set pbCombo.ArmDb = ao_Db
  
  Set cv_Share.ArmDb = ao_Db
  Set tvItem.ArmDb = ao_Db
  Set grdlst(scrFieldsTemplate).ArmDb = ao_Db
  Set grdlst(scrDesign).ArmDb = ao_Db
  Set grdlst(scrExecute).ArmDb = ao_Db
  Set grdFrom.ArmDb = ao_Db
  Set grdTo.ArmDb = ao_Db
  Set grd_Filter.ArmDb = ao_Db
  Set grd_Criteria.ArmDb = ao_Db
  Set cbo_template.ArmDb = ao_Db
  Set cbo_Combo.ArmDb = ao_Db
  Set mo_DesignTemplate.ArmDb = ao_Db
  Set mo_ExecTemplate.ArmDb = ao_Db
  Set mo_UndoTemplate.ArmDb = ao_Db
  
  Set cbo_out_come_from_table.ArmDb = ao_Db
  Set cbo_Out_Field_Prefix.ArmDb = ao_Db
  Set cbo_Out_Master_Table.ArmDb = ao_Db
  Set cbo_Out_Master_Table_Prefix.ArmDb = ao_Db
  Set cbo_Out_Field_Code.ArmDb = ao_Db
  Set cbo_Out_Field_Tag.ArmDb = ao_Db
  Set cbo_Crt_Grid_Tag.ArmDb = ao_Db
  Set cbo_Out_Format.ArmDb = ao_Db
  Set cbo_Out_Field_Join.ArmDb = ao_Db
  Set cbo_Out_Crosslink_Request.ArmDb = ao_Db
  Set cbo_Crt_Field_Code.ArmDb = ao_Db
  Set cbo_Crt_Field_Name.ArmDb = ao_Db
  Set cbo_Crt_Come_From_Table.ArmDb = ao_Db
  Set cbo_Crt_Field_Prefix.ArmDb = ao_Db

End Property

Public Property Get ArmDb() As ARMSYSCOMLib.ArmDb
  Set ArmDb = mo_Db
End Property

Property Let ConnectString(as_Value As String)
Dim la_Params() As String
  
  ms_ConnectString = as_Value
  If (as_Value <> "") Then
    la_Params = Split(as_Value, SEP, 5)
    ms_Server = la_Params(0)
    ms_Db = la_Params(1)
    ms_User = la_Params(2)
    ms_Pwd = la_Params(3)
    If UBound(la_Params) >= 4 Then
      ms_App = la_Params(4)
    Else
      ms_App = "ArmReporting"
    End If
    tvItem.ConnectString = as_Value
    pbItem.ConnectString = as_Value
    pbFind.ConnectString = as_Value
    pbShare.ConnectString = as_Value
    pbMeasure.ConnectString = as_Value
    pbList.ConnectString = as_Value
    pbGrid.ConnectString = as_Value
    pbDate.ConnectString = as_Value
    pbValue.ConnectString = as_Value
    pbSorting.ConnectString = as_Value
    pbCombo.ConnectString = as_Value
    
    cv_Share.ConnectString = as_Value
    grdlst(scrFieldsTemplate).ConnectString = as_Value
    grdlst(scrDesign).ConnectString = as_Value
    grdlst(scrExecute).ConnectString = as_Value
    grdFrom.ConnectString = as_Value
    grdTo.ConnectString = as_Value
    grd_Filter.ConnectString = as_Value
    grd_Criteria.ConnectString = as_Value
    cbo_template.ConnectString = as_Value
    cbo_Combo.ConnectString = as_Value
    
    cbo_out_come_from_table.ConnectString = as_Value
    cbo_Out_Field_Prefix.ConnectString = as_Value
    cbo_Out_Master_Table.ConnectString = as_Value
    cbo_Out_Master_Table_Prefix.ConnectString = as_Value
    cbo_Out_Field_Code.ConnectString = as_Value
    cbo_Out_Field_Tag.ConnectString = as_Value
    cbo_Crt_Grid_Tag.ConnectString = as_Value
    cbo_Out_Format.ConnectString = as_Value
    cbo_Out_Field_Join.ConnectString = as_Value
    cbo_Out_Crosslink_Request.ConnectString = as_Value
    cbo_Crt_Field_Code.ConnectString = as_Value
    cbo_Crt_Field_Name.ConnectString = as_Value
    cbo_Crt_Come_From_Table.ConnectString = as_Value
    cbo_Crt_Field_Prefix.ConnectString = as_Value
  Else
    ms_Server = ""
    ms_Db = ""
    ms_User = ""
    ms_Pwd = ""
  End If
End Property

Public Property Get ConnectString() As String
  ConnectString = ms_ConnectString
End Property

Property Get IsConnected() As Boolean

  IsConnected = False
  If Not (mo_Db Is Nothing) Then
    IsConnected = mo_Db.IsConnected
  End If
End Property

Public Property Let Language(as_Language As String)

  ms_Language = as_Language
  tvItem.Language = as_Language
  pbItem.Language = as_Language
  pbFind.Language = as_Language
  pbShare.Language = as_Language
  pbMeasure.Language = as_Language
  pbList.Language = as_Language
  pbGrid.Language = as_Language
  pbDate.Language = as_Language
  pbValue.Language = as_Language
  pbSorting.Language = as_Language
  pbCombo.Language = as_Language
  
  cal1.Language = ms_Language
  cal2.Language = ms_Language
  mo_DesignTemplate.Language = as_Language
  mo_ExecTemplate.Language = as_Language
  mo_UndoTemplate.Language = as_Language
End Property

Public Property Get Language() As String

  Language = ms_Language
End Property

Public Property Let UserID(as_UserID As String)

  ms_UserID = as_UserID
  mo_DesignTemplate.UserID = as_UserID
  mo_ExecTemplate.UserID = as_UserID
  mo_UndoTemplate.UserID = as_UserID
End Property

Public Property Get UserID() As String
  UserID = ms_UserID
End Property

Public Property Let Mode(at_Mode As RptMode)
  mt_Mode = at_Mode
  Call InitControls
  Call UpdateToolbarDisplayFace
End Property

Public Property Get Mode() As RptMode
  Mode = mt_Mode
End Property

Public Property Get ITTemplateAdmin() As Boolean
  ITTemplateAdmin = mb_ITTemplateAdmin
End Property

Public Function Init() As Boolean

On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  mb_ITTemplateAdmin = GetAdminRight
  Call InitTreeView
  Call InitDefInfoGrid(grdlst(scrDesign))
  Call InitDefInfoGrid(grdlst(scrExecute))
  Call InitFieldsGrid(grdlst(scrFieldsTemplate))
  Call InitTemplateCombo
  Call InitTab
  Call LoadToolbars
  Call InitFrames
  Call LoadOperators
  Call InitControls
  'language of the reporting main control has to be set before programmer call Init !!!!
  Call ChangeCharset(UserControl.Controls, GetCharSet(GetCodePage(ms_Language)))
  Call LoadLabels(mo_Db, UserControl.Controls, "Reporting_Tool", ms_Language)
  Init = True
  Call SetMousePointer(True)
  Exit Function
ErrorHandler:
  Init = False
  Call SetMousePointer(True)
End Function

Private Function GetAdminRight() As Boolean
Dim ll_Cursor As Long

On Error GoTo ErrorHandler
  GetAdminRight = False
  ll_Cursor = OpenCursor("SELECT rpt_right FROM rpt_right WHERE login_name=" & SQLStr(ms_UserID))
  If mo_Db.RowCount(ll_Cursor) > 0 Then
    If mo_Db.GetFields(ll_Cursor, 0) = 1 Then
      GetAdminRight = True
    End If
  End If
  Call CloseCursor(ll_Cursor)
  Exit Function
ErrorHandler:
  GetAdminRight = False
End Function

Private Function InitTab() As Boolean
Dim ll_Index As Long
Dim ll_ScreenIndex As Long

  If Not mb_ITTemplateAdmin Then
    For ll_Index = tbsBar.Tabs.Count To 1 Step -1
      ll_ScreenIndex = GetScreenIndexFromTabIndex(ll_Index)
      If (ll_ScreenIndex = scrFieldsTemplate) Then
        Call tbsBar.Tabs.Remove(ll_Index)
      End If
    Next
  End If
  InitTab = True
End Function

Private Function InitTreeView() As Boolean

  InitTreeView = False
  tvItem.AllowCheckboxes = False
  tvItem.Levels = MAX_LEVELS
  tvItem.StartDemandLevel = 1              'set level on which we load childs on demand
  tvItem.UseImages = True                  'show icons in treeview
  tvItem.NodeRequests = Array( _
    "exec rpt_tpl_list_tv 0,'" & UserID & "',NULL," & IIf(ITTemplateAdmin, 1, 0), _
    "exec rpt_tpl_list_tv 1,'" & UserID & "',$0$ ," & IIf(ITTemplateAdmin, 1, 0), _
    "exec rpt_tpl_list_tv 2,'" & UserID & "',$0$ ," & IIf(ITTemplateAdmin, 1, 0))
    
  tvItem.Images = Array(TV_IMAGE_FOLDER_NORMAL, TV_IMAGE_FOLDER_NORMAL)
  tvItem.SelectedImages = Array(TV_IMAGE_FOLDER_OPEN, TV_IMAGE_FOLDER_OPEN)
  If IsConnected Then
    InitTreeView = tvItem.LoadTree(LoadTypeChildsDemand)
  End If
End Function

Private Function InitTemplateCombo() As Boolean

  cbo_template.FirstBlankItem = True
  cbo_template.Request = "exec rpt_tpl_list_cbo '" & ms_UserID & "','E'"
End Function

Private Function InitDefInfoGrid(ao_Grid As ArmGrid) As Boolean

  ao_Grid.AutoColumns = False
  ao_Grid.UnBound = True
  ao_Grid.MultiSelect = False
  ao_Grid.FreeSelect = True
  ao_Grid.AllowSort = False
  Call ao_Grid.LoadConstants(ptStatic, SEP & "CENTER", ctTopGrid)
  InitDefInfoGrid = ao_Grid.SetColumns(Array( _
                                  "Out_Field_ID®©0®©1®©Out_Field_ID®©ID", _
                                  "Field_selected®©500®©0®©Field_selected®©#Visible®©BITMAP", _
                                  "Field_Order®©2000®©0®©Out_Business_Name®©#Field", _
                                  "Info_Displayed_To_User®©5000®©0®©Info_Displayed_To_User®©#Report criterias", _
                                  "Group_By®©500®©0®©Group_By®©#Group®©BITMAP", _
                                  "Total_Visible®©500®©0®©Total_Visible®©#Total®©BITMAP", _
                                  "Measure®©850®©0®©Measure®©#Measure®©®©®©CENTER", _
                                  "Field_sorted®©500®©0®©Field_sorted®©#Sorting®©BITMAP", _
                                  "Report_Order®©500®©0®©Report_Order®©#Report order", _
                                  "group_by_weight®©" & IIf(mb_ITTemplateAdmin, 500, 0) & "®©0®©group_by_weight®©#Weight", _
                                  "Join_Type®©500®©0®©Join_Type®©#Compulsory®©BITMAP", _
                                  "Locked®©500®©0®©Locked®©#Locked®©BITMAP"))
End Function

Private Function InitFieldsGrid(ao_Grid As ArmGrid) As Boolean

  ao_Grid.AutoColumns = False
  ao_Grid.MultiSelect = False
  ao_Grid.Requests = "exec rpt_fields_lst '" & ms_Language & "'"
  Call ao_Grid.LoadConstants(ptStatic, SEP & "CENTER", ctTopGrid)
  InitFieldsGrid = ao_Grid.SetColumns(Array( _
                                  "Out_Field_ID®©0®©1®©Out_Field_ID®©ID", _
                                  "out_field_name®©2000®©0®©out_field_name®©#Field name®©", _
                                  "out_come_from_table®©2000®©0®©out_come_from_table®©#Table name", _
                                  "out_field_prefix®©1000®©0®©out_field_prefix®©#Field prefix®©", _
                                  "out_master_table®©2000®©0®©out_master_table®©#Master table®©", _
                                  "out_master_table_prefix®©1000®©0®©out_master_table_prefix®©#Master table prefix®©", _
                                  "out_business_name®©2500®©0®©out_business_name®©#Business name"))
End Function

Private Function InitReportGrid(ao_Grid As ArmGrid, as_Title As String) As Boolean

  Call ao_Grid.Load_A_COM
  Set ao_Grid.ArmDb = mo_Db
  ao_Grid.AutoColumns = False
  ao_Grid.MultiSelect = False
  ao_Grid.FreeSelect = True
  ao_Grid.AllowSort = False
  Call ao_Grid.LoadConstants(ptStatic, SEP & "CENTER", ctTopGrid)
  ao_Grid.Title = as_Title
End Function

Private Function LoadToolbars()
On Error GoTo ErrHandler
    
    Const CL_REQUEST_TB As String = "SELECT Toolbar_Info FROM Toolbars_Users WHERE User_Code=$user_id$ AND App_Id=$App_Id$"
    Dim lc_Toolbar As Long
    Dim ls_ToolbarRequest As String
    Dim ls_ToolbarInfo As String

    ls_ToolbarRequest = Replace(CL_REQUEST_TB, "$user_id$", 0)
    ls_ToolbarRequest = Replace(ls_ToolbarRequest, "$App_Id$", 1)
    lc_Toolbar = mo_Db.OpenSQL(ls_ToolbarRequest)
    If lc_Toolbar = 0 Then
        LoadToolbars = False
        Exit Function
    End If

    ls_ToolbarInfo = mo_Db.GetFields(lc_Toolbar, "Toolbar_info")
    ' init toolbar
    Call pbItem.SetToolbarInfoStringParameters(ls_ToolbarInfo, "072")
  Call UpdateToolbarDisplayFace
    
    Call pbMeasure.SetToolbarInfoStringParameters(ls_ToolbarInfo, "073")
    Call pbMeasure.DisplayFace(0)
    
    Call pbValue.SetToolbarInfoStringParameters(ls_ToolbarInfo, "074")
    Call pbValue.DisplayFace(0)
    
    Call pbDate.SetToolbarInfoStringParameters(ls_ToolbarInfo, "075")
    Call pbDate.DisplayFace(0)
    
    Call pbCombo.SetToolbarInfoStringParameters(ls_ToolbarInfo, "076")
    Call pbCombo.DisplayFace(0)
    
    Call pbSorting.SetToolbarInfoStringParameters(ls_ToolbarInfo, "077")
    Call pbSorting.DisplayFace(0)

    Call pbList.SetToolbarInfoStringParameters(ls_ToolbarInfo, "078")
    Call pbList.DisplayFace(0)
    
    Call pbFind.SetToolbarInfoStringParameters(ls_ToolbarInfo, "079")
    Call pbFind.DisplayFace(0)
    
    Call pbShare.SetToolbarInfoStringParameters(ls_ToolbarInfo, "080")
    Call pbShare.DisplayFace(0)

    Call pbGrid.SetToolbarInfoStringParameters(ls_ToolbarInfo, "081")
    Call pbGrid.DisplayFace(0)
    
    Call mo_Db.Close(lc_Toolbar)
    LoadToolbars = True
    Exit Function
ErrHandler:
    LoadToolbars = False
    Call mo_Db.Close(lc_Toolbar)
End Function

Private Sub UpdateToolbarDisplayFace()

Select Case Mode
  Case RPT_MODE_VIEW_DESIGN
    If mb_ITTemplateAdmin Then
      Call pbItem.DisplayFace(0)
    Else
      Call pbItem.DisplayFace(1)
    End If
  Case RPT_MODE_VIEW_EXEC
    Call pbItem.DisplayFace(2)
  Case RPT_MODE_VIEW_FIELDS
    Call pbItem.DisplayFace(3)
  Case RPT_MODE_VIEW_REPORT
    Call pbItem.DisplayFace(4)
  Case RPT_MODE_EDIT_FIELD, RPT_MODE_NEW_FIELD
    Call pbItem.DisplayFace(5)
  Case RPT_MODE_EDIT_SELECTION
    Call pbItem.DisplayFace(6)
  Case RPT_MODE_EDIT_TEMPLATE, _
       RPT_MODE_NEW_TEMPLATE, _
       RPT_MODE_INHERITE_TEMPLATE, _
       RPT_MODE_COPY_TEMPLATE
    Call pbItem.DisplayFace(7)
  End Select
End Sub

Private Function ClearFieldFrame() As Boolean

  Call ControlsClear(Controls, frm_Field)
End Function

Public Sub AutoSizeListView(ByVal ao_Listview As MSComctlLib.ListView)
Dim ll_Index As Long
Dim ll_Width As Long

On Error GoTo ErrHandler

  For ll_Index = 0 To ao_Listview.ColumnHeaders.Count - 1
    If ao_Listview.ColumnHeaders(ll_Index + 1).Width > 0 Then
      ll_Width = SendMessage(ao_Listview.hwnd, LVM_GETCOLUMNWIDTH, ByVal ll_Index, ByVal 0)
      Call SendMessage(ao_Listview.hwnd, LVM_SETCOLUMNWIDTH, ByVal ll_Index, ByVal LVSCW_AUTOSIZE_USEHEADER)
      If ll_Width > SendMessage(ao_Listview.hwnd, LVM_GETCOLUMNWIDTH, ByVal ll_Index, ByVal 0) Then
        Call SendMessage(ao_Listview.hwnd, LVM_SETCOLUMNWIDTH, ByVal ll_Index, ByVal ll_Width)
      End If
    End If
  Next
  Exit Sub
ErrHandler:

End Sub

Private Function InitFieldFrame() As Boolean
Dim ll_Index As Long
Dim lo_ListItem As ListItem

  If lvw_Crt_Report_Operator.ListItems.Count = 0 Then
    For ll_Index = 0 To UBound(ma_Operators)
      Set lo_ListItem = lvw_Crt_Report_Operator.ListItems.Add(, , ma_Operators(ll_Index).rpt_Operator)
      lo_ListItem.Tag = ma_Operators(ll_Index).rpt_Operator
    Next
    Set lo_ListItem = lvw_Out_Measure_Function.ListItems.Add(, , "SUM")
    lo_ListItem.Tag = "SUM"
    Set lo_ListItem = lvw_Out_Measure_Function.ListItems.Add(, , "COUNT")
    lo_ListItem.Tag = "COUNT"
    Set lo_ListItem = lvw_Out_Measure_Function.ListItems.Add(, , "AVG")
    lo_ListItem.Tag = "AVG"
    Set lo_ListItem = lvw_Out_Measure_Function.ListItems.Add(, , "SUMPERCGAIN")
    lo_ListItem.Tag = "SUMPERCGAIN"
    Call AutoSizeListView(lvw_Out_Measure_Function)
    
    cbo_out_come_from_table.Request = "SELECT DISTINCT out_come_from_table,out_come_from_table FROM rpt_fields ORDER BY out_come_from_table"
    cbo_Out_Field_Prefix.Request = "SELECT DISTINCT out_field_prefix,out_field_prefix FROM rpt_fields ORDER BY out_field_prefix"
    cbo_Out_Master_Table.Request = "SELECT DISTINCT Out_Master_Table,Out_Master_Table FROM rpt_fields ORDER BY out_master_table"
    cbo_Out_Master_Table_Prefix.Request = "SELECT DISTINCT Out_Master_Table_Prefix,Out_Master_Table_Prefix FROM rpt_fields ORDER BY out_master_table_prefix"
    cbo_Out_Field_Code.Request = "SELECT DISTINCT Out_Field_Code,Out_Field_Code FROM rpt_fields ORDER BY out_field_code"
    cbo_Out_Field_Tag.Request = "SELECT field_tag,business_name FROM rpt_csts WHERE language_code='" & ms_Language & "' ORDER BY business_name"
    cbo_Crt_Grid_Tag.Request = "SELECT field_tag,business_name FROM rpt_csts WHERE language_code='" & ms_Language & "' ORDER BY business_name"
    Call cbo_Out_Field_Tag.Load
    Call cbo_Crt_Grid_Tag.Load
    cbo_Out_Format.Request = "SELECT DISTINCT out_format,out_format FROM rpt_fields ORDER BY out_format"
    cbo_Out_Field_Join.Request = "SELECT DISTINCT out_field_join,out_field_join FROM rpt_fields ORDER BY out_field_join"
    cbo_Out_Crosslink_Request.Request = "SELECT DISTINCT out_crosslink_request,out_crosslink_request FROM rpt_fields ORDER BY out_crosslink_request"
    cbo_Crt_Field_Code.Request = "SELECT DISTINCT crt_field_code,crt_field_code FROM rpt_fields ORDER BY crt_field_code"
    cbo_Crt_Come_From_Table.Request = "SELECT DISTINCT crt_come_from_table,crt_come_from_table FROM rpt_fields ORDER BY crt_come_from_table"
    cbo_Crt_Field_Name.Request = "SELECT DISTINCT crt_field_name,crt_field_name FROM rpt_fields ORDER BY crt_field_name"
    cbo_Crt_Field_Prefix.Request = "SELECT DISTINCT crt_field_prefix,crt_field_prefix FROM rpt_fields ORDER BY crt_field_prefix"
    
    Call cbo_Crt_Type.AddItem(Array("", ""))
    Call cbo_Crt_Type.AddItem(Array("LIST", "LIST"))
    Call cbo_Crt_Type.AddItem(Array("GRID", "GRID"))
    Call cbo_Crt_Type.AddItem(Array("NUMERIC", "NUMERIC"))
    Call cbo_Crt_Type.AddItem(Array("CHAR", "CHAR"))
    Call cbo_Crt_Type.AddItem(Array("DATE", "DATE"))
    Call cbo_Crt_Type.AddItem(Array("COMBO", "COMBO"))
    Call cbo_Crt_Type.AddItem(Array("NUM CONST", "NUM CONST"))
    Call cbo_Crt_Type.AddItem(Array("CHAR CONST", "CHAR CONST"))
    Call cbo_Crt_Type.AddItem(Array("DATE CONST", "DATE CONST"))
    
    Call cbo_Out_Alignment.AddItem(Array("", ""))
    Call cbo_Out_Alignment.AddItem(Array("LEFT", "LEFT"))
    Call cbo_Out_Alignment.AddItem(Array("CENTER", "CENTER"))
    Call cbo_Out_Alignment.AddItem(Array("RIGHT", "RIGHT"))
        
    Call cbo_Out_Order.AddItem(Array("", ""))
    Call cbo_Out_Order.AddItem(Array("AZ", "AZ"))
    Call cbo_Out_Order.AddItem(Array("ZA", "ZA"))
  End If
End Function

Private Function LoadFieldFrame() As Boolean
Dim lv_Key As Variant
Dim ll_Cursor As Long
Dim lv_Array As Variant

On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  LoadFieldFrame = False
  Call InitFieldFrame
  Call ClearFieldFrame
  lv_Key = grdlst(scrFieldsTemplate).SelectedKey(0)
  If IsArray(lv_Key) Then
    ll_Cursor = OpenCursor("rpt_fields_sel " & lv_Key(0) & ",'" & ms_Language & "'")
    If ll_Cursor > 0 Then
      If mo_Db.RowCount(ll_Cursor) = 1 Then
        txt_out_field_id.Text = mo_Db.GetFields(ll_Cursor, "out_field_id")
        txt_Out_Field_Name.Text = mo_Db.GetFields(ll_Cursor, "out_field_name")
        cbo_out_come_from_table.Text = mo_Db.GetFields(ll_Cursor, "out_come_from_table")
        cbo_Out_Field_Prefix.Text = mo_Db.GetFields(ll_Cursor, "out_field_prefix")
        cbo_Out_Master_Table.Text = mo_Db.GetFields(ll_Cursor, "out_master_table")
        cbo_Out_Master_Table_Prefix.Text = mo_Db.GetFields(ll_Cursor, "out_master_table_prefix")
        cbo_Out_Field_Code.Text = mo_Db.GetFields(ll_Cursor, "out_field_code")
        Call cbo_Out_Field_Tag.SearchItem(mo_Db.GetFields(ll_Cursor, "out_field_tag"))
        Call cbo_Crt_Grid_Tag.SearchItem(mo_Db.GetFields(ll_Cursor, "crt_grid_tag"))
        cbo_Out_Format.Text = mo_Db.GetFields(ll_Cursor, "out_format")
        cbo_Out_Field_Join.Text = mo_Db.GetFields(ll_Cursor, "out_field_join")
        cbo_Out_Crosslink_Request.Text = mo_Db.GetFields(ll_Cursor, "out_crosslink_request")
        Call cbo_Out_Order.SearchItem(mo_Db.GetFields(ll_Cursor, "Out_Order"))
        Call cbo_Out_Alignment.SearchItem(mo_Db.GetFields(ll_Cursor, "Out_Alignment"))
        chk_Out_Can_Be_Measure.Value = IIf(mo_Db.GetFields(ll_Cursor, "out_can_be_measure") = "X", vbChecked, vbUnchecked)
        chk_Out_Can_Be_Group_By.Value = IIf(mo_Db.GetFields(ll_Cursor, "out_can_be_group_by") = "X", vbChecked, vbUnchecked)
        chk_Out_Hidden.Value = IIf(mo_Db.GetFields(ll_Cursor, "out_hidden") = "X", vbChecked, vbUnchecked)
        chk_Out_Can_Change_Join.Value = IIf(mo_Db.GetFields(ll_Cursor, "out_can_change_join") = "X", vbChecked, vbUnchecked)
        chk_Out_Can_Select_Logic.Value = IIf(mo_Db.GetFields(ll_Cursor, "out_can_select_logic") = "X", vbChecked, vbUnchecked)
        txt_Out_Width.Text = mo_Db.GetFields(ll_Cursor, "Out_Width")
        txt_Out_Column_Hdr_Request.Text = mo_Db.GetFields(ll_Cursor, "Out_Column_Hdr_Request")
        
        Call cbo_Crt_Type.SearchItem(mo_Db.GetFields(ll_Cursor, "crt_type"))
        cbo_Crt_Field_Code.Text = mo_Db.GetFields(ll_Cursor, "crt_field_code")
        cbo_Crt_Field_Name.Text = mo_Db.GetFields(ll_Cursor, "crt_field_name")
        cbo_Crt_Come_From_Table.Text = mo_Db.GetFields(ll_Cursor, "crt_come_from_table")
        cbo_Crt_Field_Prefix.Text = mo_Db.GetFields(ll_Cursor, "crt_field_prefix")
        
        txt_crt_static_request_Addition.Text = mo_Db.GetFields(ll_Cursor, "crt_static_request_addition")
        txt_crt_static_request.Text = mo_Db.GetFields(ll_Cursor, "crt_static_request")
        lv_Array = Split(mo_Db.GetFields(ll_Cursor, "out_measure_function"), USERSEP)
        Call CheckListViewArray(lvw_Out_Measure_Function, lv_Array)
        lv_Array = Split(mo_Db.GetFields(ll_Cursor, "crt_report_operator"), USERSEP)
        Call CheckListViewArray(lvw_Crt_Report_Operator, lv_Array)
        Call CloseCursor(ll_Cursor)
        LoadFieldFrame = True
      End If
    End If
  End If
  Call SetMousePointer(True)
  Exit Function
ErrorHandler:
  Call SetMousePointer(True)
End Function

Private Function SaveFieldFrame() As Boolean
Dim lv_Measure As Variant
Dim lv_Operator As Variant
Dim lv_ID As Variant
Dim ls_SQL As String
Dim lb_Result As Boolean

  If txt_out_field_id.Text = "" Then
    ls_SQL = "exec rpt_fields_ins "
  Else
    ls_SQL = "exec rpt_fields_upd "
  End If
  ls_SQL = ls_SQL & SQLStr(txt_out_field_id.Text) & ","
  ls_SQL = ls_SQL & SQLStr(txt_Out_Field_Name.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_out_come_from_table.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Field_Prefix.Text) & ","
  If cbo_Out_Field_Tag.SelectedItem Is Nothing Then
    ls_SQL = ls_SQL & SQLStr("") & ","
  Else
    ls_SQL = ls_SQL & SQLStr(cbo_Out_Field_Tag.SelectedItem.Key) & ","
  End If
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Master_Table.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Master_Table_Prefix.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Field_Code.Text) & ","
  ls_SQL = ls_SQL & SQLStr(IIf(chk_Out_Can_Be_Measure.Value = vbChecked, "X", "")) & ","
  ls_SQL = ls_SQL & SQLStr(IIf(chk_Out_Can_Be_Group_By.Value = vbChecked, "X", "")) & ","
  
  lv_Measure = GetCheckedCodes(lvw_Out_Measure_Function)
  If IsEmpty(lv_Measure) Then
    ls_SQL = ls_SQL & SQLStr("") & ","
  Else
    ls_SQL = ls_SQL & SQLStr(Join(lv_Measure, USERSEP)) & ","
  End If
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Order.Text) & ","
  ls_SQL = ls_SQL & SQLStr(IIf(chk_Out_Hidden.Value = vbChecked, "X", "")) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Field_Join.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Format.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Alignment.Text) & ","
  ls_SQL = ls_SQL & SQLStr(txt_Out_Width.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Crt_Field_Code.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Crt_Field_Name.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Crt_Type.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Crt_Come_From_Table.Text) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Crt_Field_Prefix.Text) & ","
  
  lv_Operator = GetCheckedCodes(lvw_Crt_Report_Operator)
  If IsEmpty(lv_Operator) Then
    ls_SQL = ls_SQL & SQLStr("") & ","
  Else
    ls_SQL = ls_SQL & SQLStr(Join(lv_Operator, USERSEP)) & ","
  End If

  ls_SQL = ls_SQL & SQLStr(txt_crt_static_request.Text) & ","
  ls_SQL = ls_SQL & SQLStr(txt_crt_static_request_Addition.Text) & ","
  If cbo_Crt_Grid_Tag.SelectedItem Is Nothing Then
    ls_SQL = ls_SQL & SQLStr("") & ","
  Else
    ls_SQL = ls_SQL & SQLStr(cbo_Crt_Grid_Tag.SelectedItem.Key) & ","
  End If
  ls_SQL = ls_SQL & SQLStr(IIf(chk_Out_Can_Change_Join.Value = vbChecked, "X", "")) & ","
  ls_SQL = ls_SQL & SQLStr(IIf(chk_Out_Can_Select_Logic.Value = vbChecked, "X", "")) & ","
  ls_SQL = ls_SQL & SQLStr(cbo_Out_Crosslink_Request.Text) & ","
  ls_SQL = ls_SQL & SQLStr(txt_Out_Column_Hdr_Request.Text)
  
  
  lb_Result = ExecuteSQL(ls_SQL, lv_ID)
  If lb_Result Then
    If txt_out_field_id.Text = "" Then
      Call grdlst(scrFieldsTemplate).InsertLine(0, _
      Array(lv_ID, txt_Out_Field_Name.Text, cbo_out_come_from_table.Text, _
      cbo_Out_Field_Prefix.Text, cbo_Out_Master_Table.Text, cbo_Out_Master_Table_Prefix.Text, cbo_Out_Field_Tag.Text))
    Else
      If grdlst(scrFieldsTemplate).SearchKey(True, txt_out_field_id.Text) Then
        grdlst(scrFieldsTemplate).CurrentLine(1) = txt_Out_Field_Name.Text
        grdlst(scrFieldsTemplate).CurrentLine(2) = cbo_out_come_from_table.Text
        grdlst(scrFieldsTemplate).CurrentLine(3) = cbo_Out_Field_Prefix.Text
        grdlst(scrFieldsTemplate).CurrentLine(4) = cbo_Out_Master_Table.Text
        grdlst(scrFieldsTemplate).CurrentLine(5) = cbo_Out_Master_Table_Prefix.Text
        grdlst(scrFieldsTemplate).CurrentLine(6) = cbo_Out_Field_Tag.Text
      End If
    End If
  End If
  SaveFieldFrame = lb_Result
End Function

Private Function InitFrames() As Boolean
Dim lv_Cols As Variant

  'frame for editing measure
  Call CenterFrameToTab(frm_Measure)
  'frame for editing fields
  Call ResizeFrameToTab(frm_FieldsSelection)
  grdFrom.Top = 0
  grdTo.Top = grdFrom.Top
  grdFrom.Left = 0
  grdTo.Left = frm_FieldsSelection.Width / 2
  grdFrom.Width = frm_FieldsSelection.Width / 2
  grdTo.Width = grdFrom.Width
  grdFrom.Height = frm_FieldsSelection.Height - grdFrom.Top
  grdTo.Height = grdFrom.Height
  lv_Cols = Array("out_field_id®©0®©1®©out_field_id®©ID", _
                  "out_business_name®©2000®©0®©out_business_name®©#Name", _
                  "out_field_name®©1200®©0®©out_field_name®©#Field", _
                  "out_come_from_table®©1200®©0®©out_come_from_table®©#Table", _
                  "out_field_prefix®©500®©0®©out_field_prefix®©#Prefix", _
                  "out_master_table®©1200®©0®©out_master_table®©#Master", _
                  "out_master_table_prefix®©400®©0®©out_master_table_prefix®©#Master prefix", _
                  "out_hidden®©0®©0®©out_hidden®©#Hidden")
  Call grdFrom.SetColumns(lv_Cols)
  grdFrom.Requests = "exec rpt_fields_lst " & SQLStr(ms_Language)
  
  Call grdTo.SetColumns(lv_Cols)
  'frame for field
  Call ResizeFrameToTab(frm_Field)
  'frame for editing value
  Call CenterFrameToTab(frm_Value)
  'frame for editing date
  Call CenterFrameToTab(frm_Date)
  'frame for editing combo
  Call CenterFrameToTab(frm_Combo)
  'frame for editing sorting
  Call CenterFrameToTab(frm_Sorting)
  'frame for editing list
  Call ResizeFrameToTab(frm_List, True)
  txt_List.Width = frm_List.Width - txt_List.Left - frmSpacing
  txt_List.Top = frm_List.Height - txt_List.Height - frmSpacing
  
  lvw_List.Width = frm_List.Width - lvw_List.Left - frmSpacing
  lvw_List.Height = frm_List.Height - lvw_List.Top - txt_List.Height - 2 * frmSpacing
  'frame for finding text in report
  frm_Find.Top = tbsBar.Top + tbsBar.Height
  frm_Find.Left = 0
  'frame for setting share rights
  Call CenterFrameToTab(frm_Share)

  cv_Share.RoleCount = 3
  cv_Share.Driven_By = "Report"
  cv_Share.Common_List_Load = True
  cv_Share.Type_Of_Key = tkDependant
  cv_Share.Calling_Key_Fields = "rpt_tpl_id"
  cv_Share.Link_Key_Fields = "login_name®©share"
  If Not cv_Share.SetRoleList(Array( _
  Array("MAIN", "VIEW", "", "", "Main view", "login_name®©share®©firstname®©lastname", "lastname®©firstname®©share", "1300®©1300®©400", "login_name®©share", "exec rpt_share_sel $rpt_tpl_id$,NULL,NULL", "exec rpt_share_ins $rpt_tpl_id$,'$login_name$','$share$'", "exec rpt_share_del $rpt_tpl_id$,'$login_name$','$share$'", True, 2, False, True, 0, 1), _
  Array("INHERIT", "EDIT", "share", "I", "#Can_inherit", "login_name®©firstname®©lastname", "lastname®©firstname", "1500®©1500", "login_name", "exec security_identity_sel", "exec rpt_share_ins $rpt_tpl_id$,'$login_name$','$share$'", "exec rpt_share_del $rpt_tpl_id$,'$login_name$','$share$'", False, 2, False, True, 1, 0), _
  Array("EXECUTE", "EDIT", "share", "E", "#Can_execute", "login_name®©firstname®©lastname", "lastname®©firstname", "1500®©1500", "login_name", "exec security_identity_sel", "exec rpt_share_ins $rpt_tpl_id$,'$login_name$','$share$'", "exec rpt_share_del $rpt_tpl_id$,'$login_name$','$share$'", False, 2, False, True, 1, 0) _
  )) Then
    Call ASC_SendMessage(ms_Language, RPT_ERR_MSG, "#Setting CheckView parameters failed.")
  End If
  cv_Share.Synchronize_View = True
  cv_Share.ComboVisible = True

  'frame for grid filter criteria
  Call ResizeFrameToTab(frm_Grid, True)
  pbGrid.Top = 3 * frmSpacing
  pbGrid.Left = frmSpacing
  
  grd_Criteria.Left = frmSpacing
  grd_Criteria.Top = pbGrid.Top + pbGrid.Height
  grd_Criteria.Width = frm_Grid.Width - 2 * frmSpacing
  grd_Criteria.Height = frm_Grid.Height / 4
  
  frm_GridOperator.Left = frmSpacing
  frm_GridOperator.Top = grd_Criteria.Top + grd_Criteria.Height
  frm_GridOperator.Width = frm_Grid.Width - 2 * frmSpacing
  
  grd_Filter.FiltersEnabled = True
  grd_Filter.Left = frmSpacing
  grd_Filter.Top = frm_GridOperator.Top + frm_GridOperator.Height + frmSpacing
  grd_Filter.Width = frm_Grid.Width - 2 * frmSpacing
  grd_Filter.Height = frm_Grid.Height - frm_GridOperator.Top - frm_GridOperator.Height - 2 * frmSpacing
End Function

Private Sub InitControls()
Dim ll_Index As Long
Dim ll_ScrIndex As Long
Dim lo_Grid As Control

  tbsBar.Top = 0
  tbsBar.Left = 0
  tbsBar.Width = Width
  tbsBar.Enabled = (Mode = RPT_MODE_VIEW_DESIGN Or _
                    Mode = RPT_MODE_VIEW_EXEC Or _
                    Mode = RPT_MODE_VIEW_FIELDS Or _
                    Mode = RPT_MODE_VIEW_REPORT)
  
  pbItem.Top = tbsBar.Top + tbsBar.Height
  pbItem.Width = Width
  
  Set lo_Grid = grdlst(ActiveScreenIndex)
  
  If Mode = RPT_MODE_VIEW_FIELDS Then
    Call ResizeFrameToTab(frm_FieldsTemp)
    lo_Grid.Left = frmSpacing
    lo_Grid.Top = 2 * frmSpacing
    lo_Grid.Width = Width
    lo_Grid.Height = frm_FieldsTemp.Height - 3 * frmSpacing
    If lo_Grid.Rows = 0 Then Call lo_Grid.Execute
  ElseIf Mode = RPT_MODE_VIEW_DESIGN Or _
         Mode = RPT_MODE_EDIT_TEMPLATE Or _
         Mode = RPT_MODE_INHERITE_TEMPLATE Or _
         Mode = RPT_MODE_NEW_TEMPLATE Or _
         Mode = RPT_MODE_COPY_TEMPLATE Then
    Call ResizeFrameToTab(frm_Design)
    
    tvItem.Left = frmSpacing
    tvItem.Top = 2 * frmSpacing
    tvItem.Height = frm_Design.Height - 3 * frmSpacing
    tvItem.Visible = Mode = RPT_MODE_VIEW_DESIGN
    
    lo_Grid.Top = 2 * frmSpacing
    lo_Grid.Left = IIf(Mode = RPT_MODE_VIEW_DESIGN, 2 * frmSpacing + tvItem.Width, frmSpacing)
    lo_Grid.Width = frm_Design.Width - lo_Grid.Left - frmSpacing
    lo_Grid.Height = frm_Design.Height - lo_Grid.Top - frm_DescDesign.Height - frmSpacing
    
    frm_DescDesign.Top = lo_Grid.Top + lo_Grid.Height
    frm_DescDesign.Left = lo_Grid.Left
    frm_DescDesign.Width = lo_Grid.Width
    txt_DescDesign.Width = frm_DescDesign.Width - txt_DescDesign.Left - frmSpacing
    txt_DescDesign.Locked = Mode = RPT_MODE_VIEW_DESIGN
    txt_NameDesign.Locked = Mode = RPT_MODE_VIEW_DESIGN
  ElseIf Mode = RPT_MODE_VIEW_EXEC Then
    Call ResizeFrameToTab(frm_Exec)
    lo_Grid.Left = frmSpacing
    lo_Grid.Width = frm_Exec.Width - 2 * frmSpacing
    lo_Grid.Height = frm_Exec.Height - lo_Grid.Top - frm_DescExec.Height - frmSpacing
    
    frm_DescExec.Top = lo_Grid.Top + lo_Grid.Height
    frm_DescExec.Left = lo_Grid.Left
    frm_DescExec.Width = lo_Grid.Width
    txt_DescExec.Width = frm_DescExec.Width - txt_DescExec.Left - frmSpacing
  ElseIf Mode = RPT_MODE_VIEW_REPORT Then
    lo_Grid.Left = 0
    lo_Grid.Top = pbItem.Top + pbItem.Height
    lo_Grid.Width = Width
    lo_Grid.Height = Height - lo_Grid.Top
  End If
  
  frm_Exec.Visible = Mode = RPT_MODE_VIEW_EXEC
  frm_Design.Visible = Mode = RPT_MODE_VIEW_DESIGN Or _
                       Mode = RPT_MODE_EDIT_TEMPLATE Or _
                       Mode = RPT_MODE_INHERITE_TEMPLATE Or _
                       Mode = RPT_MODE_NEW_TEMPLATE Or _
                       Mode = RPT_MODE_COPY_TEMPLATE
  frm_FieldsTemp.Visible = Mode = RPT_MODE_VIEW_FIELDS
  frm_Field.Visible = Mode = RPT_MODE_EDIT_FIELD Or Mode = RPT_MODE_NEW_FIELD
  frm_FieldsSelection.Visible = Mode = RPT_MODE_EDIT_SELECTION
  
  For ll_Index = 1 To tbsBar.Tabs.Count
    ll_ScrIndex = GetScreenIndexFromTabIndex(ll_Index)
    If ll_ScrIndex >= scrReport Then
      grdlst(ll_ScrIndex).Visible = ll_ScrIndex = ActiveScreenIndex
    End If
  Next
End Sub

Private Sub ResizeFrameToTab(ao_Frame As Frame, Optional ab_FullResize As Boolean = False)

  ao_Frame.Top = IIf(ab_FullResize, 0, pbItem.Top + pbItem.Height)
  ao_Frame.Left = 0
  ao_Frame.Height = IIf(ab_FullResize, Height, Height - pbItem.Top - pbItem.Height)
  ao_Frame.Width = Width
End Sub

Private Sub CenterFrameToTab(ao_Frame As Frame)
  ao_Frame.Top = (Height - ao_Frame.Height) / 2
  ao_Frame.Left = (Width - ao_Frame.Width) / 2
End Sub

Private Sub grd_Filter_DblClick()
  Call pbGrid_Action(TBR_Add, "")
End Sub

Private Sub grdLst_AfterExcelExport(Index As Integer, ByVal ao_ExcelApp As Object, ByVal ao_ExcelWorkbook As Object, ByVal ao_ExcelSheet As Object)
Dim lv_Criteria As Variant
Dim ll_Index As Long

On Error GoTo ErrorHandler
 If Not (ao_ExcelWorkbook Is Nothing) Then
    lv_Criteria = grdlst(Index).TagVariant
    ao_ExcelWorkbook.Sheets(2).Name = "Report Criteria"
    ao_ExcelWorkbook.Sheets(2).Columns("A:A").columnWidth = 20
    ao_ExcelWorkbook.Sheets(2).Columns("B:B").columnWidth = 40
    ao_ExcelWorkbook.Sheets(2).Columns("C:C").columnWidth = 40
    
    ao_ExcelWorkbook.Sheets(2).cells(1, 1).Value = "Report Title"
    ao_ExcelWorkbook.Sheets(2).cells(1, 1).Font.Bold = True
    ao_ExcelWorkbook.Sheets(2).cells(1, 2).Value = grdlst(Index).Title
    
    ao_ExcelWorkbook.Sheets(2).cells(2, 1).Value = "Report Created"
    ao_ExcelWorkbook.Sheets(2).cells(2, 1).Font.Bold = True
    ao_ExcelWorkbook.Sheets(2).cells(2, 2).Value = Format(Now(), "dd/mm/yyyy hh:mm:ss") + " by " + ms_UserID
    
    
    ao_ExcelWorkbook.Sheets(2).cells(3, 1).Value = "Criteria"
    ao_ExcelWorkbook.Sheets(2).cells(3, 1).Font.Bold = True
    
    If IsArray(lv_Criteria) Then
      For ll_Index = 0 To UBound(lv_Criteria, 2)
        ao_ExcelWorkbook.Sheets(2).cells(ll_Index + 3, 2).Value = "'" & lv_Criteria(0, ll_Index)
        ao_ExcelWorkbook.Sheets(2).cells(ll_Index + 3, 3).Value = "'" & lv_Criteria(1, ll_Index)
      Next
    End If
  End If
  Exit Sub
ErrorHandler:
End Sub

Private Sub grdTo_ItemSelected()
  Call pbItem_action(TBR_OpLT, "")
End Sub

Private Sub grdFrom_ItemSelected()
  Call pbItem_action(TBR_OpGT, "")
End Sub

Private Sub grdLst_ItemSelected(Index As Integer)
Dim lo_Template As ArmRptTemplate
Dim lo_FieldDef As ArmFieldDef
Dim lo_ParentFieldDef As ArmFieldDef
Dim ll_Col As Long
Dim ll_Row As Long
Dim ls_Str As String
Dim lb_Locked As Boolean
Dim lb_FieldChanged As Boolean
Dim lb_TemplateChanged As Boolean

  lb_FieldChanged = False
  lb_TemplateChanged = False
  If Mode = RPT_MODE_EDIT_TEMPLATE Or _
     Mode = RPT_MODE_INHERITE_TEMPLATE Or _
     Mode = RPT_MODE_NEW_TEMPLATE Or _
     Mode = RPT_MODE_COPY_TEMPLATE Then
    Set lo_Template = mo_DesignTemplate
  ElseIf Mode = RPT_MODE_VIEW_EXEC Then
    Set lo_Template = mo_ExecTemplate
  ElseIf Mode = RPT_MODE_VIEW_FIELDS Then
    Call pbItem_action(TBR_Update, "")
    Exit Sub
  Else
    Exit Sub
  End If
    
  ll_Row = grdlst(Index).Row
  ll_Col = grdlst(Index).Col
  
  Set lo_FieldDef = lo_Template.GetFieldDef(grdlst(Index).SelectedKey(0)(0))
  Set lo_ParentFieldDef = lo_Template.Parent.GetFieldDef(grdlst(Index).SelectedKey(0)(0))
  
  If Not (lo_FieldDef Is Nothing) Then
    Select Case UCase(grdlst(Index).Columns(ll_Col).Name)
    Case "FIELD_SELECTED"
      
      If (lo_FieldDef.Locked = "") Or (lo_FieldDef.Locked = "P") Then
        lo_FieldDef.Field_selected = IIf(lo_FieldDef.Field_selected = "", "X", "")
        lb_TemplateChanged = True
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      End If
    Case "FIELD_ORDER", "REPORT_ORDER"
      
      Call EditOrder(lo_Template, grdlst(Index).Columns(ll_Col).Name)
    Case "INFO_DISPLAYED_TO_USER"
      
      If (lo_FieldDef.Locked = "") Or (lo_FieldDef.Locked = "P") Then
        Call EditCriteria(lo_FieldDef, lo_ParentFieldDef)
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      End If
    Case "TOTAL_VISIBLE"
      
      If lo_FieldDef.Locked = "" Then
        If lo_FieldDef.Group_By <> "" Then
          If (lo_FieldDef.Measure = "") Or (StrComp(lo_FieldDef.Measure, "COUNT", vbTextCompare) = 0) Then
            lo_FieldDef.Total_Visible = IIf(lo_FieldDef.Total_Visible = "", "X", "")
            lb_TemplateChanged = True
          End If
        End If
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      End If
    Case "GROUP_BY"
      
      If lo_FieldDef.Locked = "" Then
        If lo_FieldDef.Out_Can_Be_Group_By <> "" Then
          If (lo_FieldDef.Measure = "") Or (StrComp(lo_FieldDef.Measure, "COUNT", vbTextCompare) = 0) Then
            lo_FieldDef.Group_By = IIf(lo_FieldDef.Group_By = "", "X", "")
            lo_FieldDef.Total_Visible = lo_FieldDef.Group_By
            If (lo_FieldDef.Group_By <> "") And (lo_FieldDef.Field_sorted = "") Then
              lo_FieldDef.Field_sorted = "AZ"
            End If
            lb_TemplateChanged = True
          End If
        End If
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      End If
    Case "FIELD_SORTED"
      
      If lo_FieldDef.Locked = "" Then
        Select Case UCase(lo_FieldDef.Field_sorted)
        Case "AZ"
          lo_FieldDef.Field_sorted = "ZA"
        Case "ZA"
          lo_FieldDef.Field_sorted = IIf(lo_FieldDef.Group_By = "", "", "AZ")
        Case Else
          lo_FieldDef.Field_sorted = "AZ"
        End Select
        lb_TemplateChanged = True
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      End If
    Case "MEASURE"
      
      If (lo_FieldDef.Locked = "") Or (lo_FieldDef.Locked = "P") Then
        If lo_FieldDef.Out_Can_Be_Measure <> "" Then
          'If lo_FieldDef.Group_By = "" Then
            Call EditMeasure(lo_FieldDef, lo_ParentFieldDef)
          'End If
        End If
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      End If
    Case "LOCKED"
      
      lb_Locked = True
      If ActiveScreenIndex = scrDesign Then
        'if the template has already children, don't allow lock unlock
        If lo_Template.HasChildren Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 8, "#Template contains children")
        Else
          'if this is IT Template, allow lock unlock for the owner
          If (lo_Template.Rpt_Tpl_ID_Parent = 0) Then
            lb_Locked = False
          ElseIf Not (lo_ParentFieldDef Is Nothing) Then
            'parent exists if the parent field is not locked, then allow lock unlock
            If (lo_ParentFieldDef.Locked = "") Then
              lb_Locked = False
            End If
          End If
        End If
      End If
      If lb_Locked Then
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      Else
        lo_FieldDef.Locked = IIf(lo_FieldDef.Locked = "", "P", IIf(lo_FieldDef.Locked = "P", "X", ""))
        lb_FieldChanged = True
      End If
    Case "GROUP_BY_WEIGHT"
      If mb_ITTemplateAdmin Then
        If ActiveScreenIndex = scrDesign Then
          ls_Str = InputBox(grdlst(Index).Columns(grdlst(Index).Col).Title, mo_DesignTemplate.Rpt_Tpl_Name, lo_FieldDef.Group_By_Weight)
          If isNumeric(ls_Str) Then
            lo_FieldDef.Group_By_Weight = Val(ls_Str)
            lb_FieldChanged = True
          End If
        End If
      End If
    Case "JOIN_TYPE"
      If lo_FieldDef.Locked = "" Then
        If lo_FieldDef.Out_Can_Change_join <> "" Then
          Call lo_Template.SetJoin_Type(lo_FieldDef, IIf(lo_FieldDef.Join_Type = "L", "I", "L"))
          lb_TemplateChanged = True
        End If
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
      End If
    End Select
    If lb_TemplateChanged Then
      Call lo_Template.ReorderFields
      Call RefreshGrid(lo_Template, grdlst(Index))
    ElseIf lb_FieldChanged Then
      Call UpdateGridRow(grdlst(Index), lo_FieldDef)
      If ActiveScreenIndex = scrDesign Then
        lo_FieldDef.SQL_Flag = "U"
      End If
    End If
  End If
End Sub

Private Sub lvw_List_ItemCheck(ByVal Item As MSComctlLib.ListItem)
  
  Call UpdateCheckedItems(lvw_List, txt_List)
End Sub

Private Sub cbo_ListOperator_ComboItemSelected()
  
  If cbo_ListOperator.Text = "" Then
    Call ListViewChange(lvw_List, False)
    Call UpdateCheckedItems(lvw_List, txt_List)
  End If
  Call SelectCombo(cbo_ListLogic, GetDefaultLogic(cbo_ListOperator.Text))
End Sub

Private Sub cbo_GridOperator_ComboItemSelected()

  If cbo_GridOperator.Text = "" Then
    Call grd_Criteria.ClearGrid
  End If
  Call SelectCombo(cbo_GridLogic, GetDefaultLogic(cbo_GridOperator.Text))
End Sub

Private Sub ListViewChange(lo_ListView As ListView, ab_Checked As Boolean)
Dim lo_item As ListItem

  For Each lo_item In lo_ListView.ListItems
    lo_item.Checked = ab_Checked
  Next
End Sub

Private Sub ClearTemplateControls(al_Screen As Long)

  If al_Screen = scrDesign Then
    txt_OwnerDesign.Text = ""
    txt_DescDesign.Text = ""
    txt_NameDesign.Text = ""
    txt_MasterDesign.Text = ""
  ElseIf al_Screen = scrExecute Then
    txt_OwnerExec.Text = ""
    txt_DescExec.Text = ""
    txt_MasterExec.Text = ""
  End If
  Call grdlst(al_Screen).ClearGrid
  grdlst(al_Screen).Title = ""
End Sub

Private Sub DisplayTemplateControls(ao_Template As ArmRptTemplate, al_Screen As Long)

  If al_Screen = scrDesign Then
    txt_OwnerDesign.Text = ao_Template.Owner
    txt_DescDesign.Text = ao_Template.Rpt_Tpl_Comment
    txt_NameDesign.Text = ao_Template.Rpt_Tpl_Name
    txt_MasterDesign.Text = ao_Template.Table_Business_Name
  ElseIf al_Screen = scrExecute Then
    txt_OwnerExec.Text = ao_Template.Owner
    txt_DescExec.Text = ao_Template.Rpt_Tpl_Comment
    txt_MasterExec.Text = ao_Template.Table_Business_Name
  End If
  Call RefreshGrid(ao_Template, grdlst(al_Screen))
End Sub

Private Sub tvItem_NodeClick(ByVal Node As MSComctlLib.Node)
  
On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  If Mode = RPT_MODE_VIEW_DESIGN Then
    Call ClearTemplateControls(scrDesign)
    If Not (Node Is Nothing) Then
      If Node.Tag.ml_Level > 1 Then
        If mo_DesignTemplate.Load(tvItem.NodeInfo(Node).IDValue) Then
          Call DisplayTemplateControls(mo_DesignTemplate, scrDesign)
        End If
      End If
    End If
  End If
  Call SetMousePointer(True)
  Exit Sub
ErrorHandler:
  Call SetMousePointer(True)
End Sub

Private Sub tvItem_TreeNodesLoad(ByRef LoadType As TreeLoadType, ByVal NodeInfo As NodeInfo, ByVal Level As Long, Request As Variant, ByVal NewNodeInfo As NodeInfo)
  If Level = 2 Then
    LoadType = LoadTypeBranch
    'HERE: I have to save old ID of module and set it temporaly to 0, because IT template has parent ID (root) 0.
    'After branch is loaded, I set it in TreeNodesLoaded back to previous value
    ml_TempSave_Mdl_Id = NodeInfo.IDValue
    NodeInfo.IDValue = 0
    NewNodeInfo.LoadType = LoadTypeBranch
  End If
End Sub

Private Sub tvItem_TreeNodesLoaded(ByVal LoadType As TreeLoadType, ByVal NodeInfo As NodeInfo, ByVal Level As Long, Request As Variant)

  If Level = 2 Then
    'put back saved module ID. (Because root of the template branch is zero, we had to temporary replace it)
    NodeInfo.IDValue = ml_TempSave_Mdl_Id
    'hide or unhide templates
    If Not mb_ITTemplateAdmin Then
      Call HideNodesWithoutRights(tvItem, NodeInfo.mo_Node)
    End If
  End If
End Sub

Private Sub tvItem_TreeNodeAdded(ByVal ao_Node As MSComctlLib.Node)

  If ao_Node.Tag.ml_Level > 1 Then
    Call UpdateTVNode(ao_Node)
  End If
End Sub

Private Sub cbo_template_ComboItemSelected()
  
On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  Call ClearTemplateControls(scrExecute)
  If Not (cbo_template.SelectedItem Is Nothing) Then
    If mo_ExecTemplate.Load(cbo_template.SelectedItem.Key) Then
      Call mo_ExecTemplate.LoadParent
      Call DisplayTemplateControls(mo_ExecTemplate, scrExecute)
    End If
  End If
  Call SetMousePointer(True)
  Exit Sub
ErrorHandler:
  Call SetMousePointer(True)
End Sub

Private Function UpdateTemplateToControls(ao_Template As ArmRptTemplate) As Boolean
Dim lo_Node As Node
  
  UpdateTemplateToControls = False
  Set lo_Node = Nothing
  
  If Mode = RPT_MODE_COPY_TEMPLATE Then
    If Not (tvItem.SelectedItem Is Nothing) Then
      Set lo_Node = tvItem.AddNode(tvItem.SelectedItem.Parent, ao_Template.Rpt_Tpl_ID, ao_Template.Rpt_Tpl_Name)
    End If
  ElseIf Mode = RPT_MODE_INHERITE_TEMPLATE Then
    Set lo_Node = tvItem.AddNode(tvItem.SelectedItem, ao_Template.Rpt_Tpl_ID, ao_Template.Rpt_Tpl_Name)
  ElseIf Mode = RPT_MODE_NEW_TEMPLATE Then
    Set lo_Node = tvItem.AddNode(tvItem.SelectedItem, ao_Template.Rpt_Tpl_ID, ao_Template.Rpt_Tpl_Name)
  ElseIf Mode = RPT_MODE_EDIT_TEMPLATE Then
    Set lo_Node = tvItem.SelectedItem
  End If
  
  If Not (lo_Node Is Nothing) Then
    If ao_Template.Rpt_Execute <> "" Then
      If ao_Template.Rpt_Inherit <> "" Then
        Call lo_Node.Tag.SetData(NODE_RIGHT, TV_IMAGE_INHERITEXECUTE)
      Else
        Call lo_Node.Tag.SetData(NODE_RIGHT, TV_IMAGE_EXECUTE)
      End If
    ElseIf ao_Template.Rpt_Inherit <> "" Then
      Call lo_Node.Tag.SetData(NODE_RIGHT, TV_IMAGE_INHERIT)
    Else
      Call lo_Node.Tag.SetData(NODE_RIGHT, TV_IMAGE_NORIGHT)
    End If
    Call lo_Node.Tag.SetData(NODE_OWNER, ao_Template.Owner)
    Call UpdateTVNode(lo_Node)
    grdlst(scrDesign).Title = ao_Template.Rpt_Tpl_Name
    If Not cbo_template.SearchItem(ao_Template.Rpt_Tpl_ID, , , False) Then
      Call cbo_template.AddItem(Array(ao_Template.Rpt_Tpl_ID, ao_Template.Rpt_Tpl_Name))
    End If
    Set tvItem.SelectedItem = lo_Node
    UpdateTemplateToControls = True
  End If
End Function

Private Function InheriteTemplate(ao_Template As ArmRptTemplate) As Boolean
Dim ls_Name As String

On Error GoTo ErrorHandler
  InheriteTemplate = False
  If ao_Template.Rpt_Tpl_ID <> 0 Then
    If ao_Template.CanInherite Then
      If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 2, "#Really inherite ?", "", vbYesNo) = vbYes Then
        ls_Name = InputBox("#Template name", ao_Template.Rpt_Tpl_Name, ao_Template.Rpt_Tpl_Name)
        If ls_Name <> "" Then
          Call ao_Template.CopyTo(ao_Template.Parent)
          If ao_Template.Inherite(ls_Name) Then
            Call DisplayTemplateControls(ao_Template, scrDesign)
            Call ao_Template.CopyTo(mo_UndoTemplate)
            InheriteTemplate = True
          End If
        End If
      End If
    Else
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 4, "#You don't have rights to inherite this template")
    End If
  End If
  Exit Function
ErrorHandler:
  InheriteTemplate = False
End Function

Private Function NewTemplate(ao_Template As ArmRptTemplate) As Boolean
Dim ls_Name As String
Dim ll_Mdl_Id As Long

On Error GoTo ErrorHandler
  NewTemplate = False
  
  ll_Mdl_Id = 0
  If Not (tvItem.SelectedItem Is Nothing) Then
    If tvItem.SelectedItem.Tag.ml_Level = 1 Then
      ll_Mdl_Id = tvItem.SelectedItem.Tag.IDValue
    End If
  End If
  If ll_Mdl_Id <> 0 Then
    If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 22, "#Really create template ?", "", vbYesNo) = vbYes Then
      ls_Name = InputBox("#Template name", , "")
      If ls_Name <> "" Then
        If ao_Template.Create(ls_Name, ll_Mdl_Id) Then
          Call DisplayTemplateControls(ao_Template, scrDesign)
          Call mo_UndoTemplate.Clear
          Call ao_Template.Parent.Clear
          NewTemplate = True
        End If
      End If
    End If
  End If
  Exit Function
ErrorHandler:
  NewTemplate = False
End Function

Private Function CopyTemplate(ao_Template As ArmRptTemplate) As Boolean
Dim ls_Name As String

On Error GoTo ErrorHandler
  CopyTemplate = False
  If ao_Template.Rpt_Tpl_ID <> 0 Then
    If ao_Template.ReadOnly Then
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 7, "#You are not owner of this template")
    Else
      If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 21, "#Really copy ?", "", vbYesNo) = vbYes Then
        ls_Name = InputBox("#Template name", ao_Template.Rpt_Tpl_Name, ao_Template.Rpt_Tpl_Name)
        If ls_Name <> "" Then
          Call SetMousePointer(False)
          If ao_Template.Clone(ls_Name) Then
            Call DisplayTemplateControls(ao_Template, scrDesign)
            Call ao_Template.CopyTo(mo_UndoTemplate)
            If ao_Template.LoadParent Then
              CopyTemplate = True
            End If
          End If
          Call SetMousePointer(True)
        End If
      End If
    End If
  End If
  Exit Function
ErrorHandler:
  CopyTemplate = False
End Function

Private Function EditTemplate(ao_Template As ArmRptTemplate) As Boolean
Dim ls_Name As String

On Error GoTo ErrorHandler
  EditTemplate = False
  If ao_Template.Rpt_Tpl_ID <> 0 Then
    If ao_Template.Rpt_Tpl_ID = mo_ExecTemplate.Rpt_Tpl_ID Then
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 6, "#You have this template open in execute mode, close it first")
    Else
      If ao_Template.ReadOnly Then
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 7, "#You are not owner of this template")
      Else
        Call SetMousePointer(False)
        If ao_Template.LoadParent Then
          Call ao_Template.CopyTo(mo_UndoTemplate)
          EditTemplate = True
        End If
        Call SetMousePointer(True)
      End If
    End If
  End If
  Exit Function
ErrorHandler:
  EditTemplate = False
End Function

Private Sub pbItem_action(ByVal as_Role As String, as_Language As String)
Dim lo_Node As Node
Dim ll_ErrorCode As Long
Dim lb_Allow As Boolean

  lb_Allow = True
  RaiseEvent pbItemAction(as_Role, lb_Allow)
  If lb_Allow Then
    Select Case as_Role
    Case TBR_Add
      If Mode = RPT_MODE_VIEW_DESIGN Then
        If Not (tvItem.SelectedItem Is Nothing) Then
          If tvItem.SelectedItem.Tag.ml_Level < MAX_LEVELS - 1 Then
            If InheriteTemplate(mo_DesignTemplate) Then
              Mode = RPT_MODE_INHERITE_TEMPLATE
            End If
          End If
        End If
      ElseIf Mode = RPT_MODE_VIEW_FIELDS Then
        Call InitFieldFrame
        Call ClearFieldFrame
        Mode = RPT_MODE_NEW_FIELD
      End If
    Case TBR_New
      If Mode = RPT_MODE_VIEW_DESIGN Then
        If NewTemplate(mo_DesignTemplate) Then
          Mode = RPT_MODE_NEW_TEMPLATE
        End If
      End If
    Case TBR_Copy
      If Mode = RPT_MODE_VIEW_DESIGN Then
        If CopyTemplate(mo_DesignTemplate) Then
          Mode = RPT_MODE_COPY_TEMPLATE
        End If
      End If
    Case TBR_Update
      If Mode = RPT_MODE_VIEW_DESIGN Then
        If EditTemplate(mo_DesignTemplate) Then
          Mode = RPT_MODE_EDIT_TEMPLATE
        End If
      ElseIf ActiveScreenIndex = scrFieldsTemplate Then
        If LoadFieldFrame Then
          Mode = RPT_MODE_EDIT_FIELD
        End If
      End If
    Case TBR_Audit
      If (mo_DesignTemplate.Rpt_Tpl_ID <> 0) And _
         (mo_DesignTemplate.Rpt_Tpl_ID_Parent = 0) Then
        If LoadFieldsSelectionFrame Then
          Mode = RPT_MODE_EDIT_SELECTION
        End If
      End If
    Case TBR_Valid
      If Mode = RPT_MODE_INHERITE_TEMPLATE Or _
         Mode = RPT_MODE_EDIT_TEMPLATE Or _
         Mode = RPT_MODE_NEW_TEMPLATE Or _
         Mode = RPT_MODE_COPY_TEMPLATE Then
        Select Case mo_DesignTemplate.Validate
        Case "COMMENT"
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 20, "#Please, enter at least 20 characters in comment field")
          Exit Sub
        End Select
        If mo_DesignTemplate.Changed Then
          If Not mo_DesignTemplate.IsOKGroup_By_Weight Then
            If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 19, "#Group weight balance is breaked. Continue ?", , vbYesNo) = vbNo Then Exit Sub
          End If
          Call SetMousePointer(False)
          If mo_DesignTemplate.Save(ll_ErrorCode) Then
            If Mode = RPT_MODE_INHERITE_TEMPLATE Then
              Call mo_DesignTemplate.CopyShareFrom(mo_DesignTemplate.Rpt_Tpl_ID_Parent)
            ElseIf Mode = RPT_MODE_COPY_TEMPLATE Then
              Call mo_DesignTemplate.CopyShareFrom(tvItem.NodeInfo(tvItem.SelectedItem).IDValue)
            End If
            Call UpdateTemplateToControls(mo_DesignTemplate)
            
            If Mode = RPT_MODE_INHERITE_TEMPLATE Or _
               Mode = RPT_MODE_NEW_TEMPLATE Or _
               Mode = RPT_MODE_COPY_TEMPLATE Then
              Call mo_DesignTemplate.AddShare("E")
              Call mo_DesignTemplate.AddShare("I")
            End If
            Mode = RPT_MODE_VIEW_DESIGN
          Else
            If ll_ErrorCode = 2627 Then
              Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 18, "#Template name is not unique")
            Else
              Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 3, "#Save template failed")
            End If
          End If
          Call SetMousePointer(True)
        Else
          Mode = RPT_MODE_VIEW_DESIGN
        End If
      ElseIf Mode = RPT_MODE_EDIT_SELECTION Then
        Call ApplyChangedRows
        
      ElseIf Mode = RPT_MODE_EDIT_FIELD Or Mode = RPT_MODE_NEW_FIELD Then
        Call SetMousePointer(False)
        If SaveFieldFrame Then
          Mode = RPT_MODE_VIEW_FIELDS
        Else
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 3, "#Save template failed")
        End If
        Call SetMousePointer(True)
      End If
    Case TBR_Undo
      If Mode = RPT_MODE_EDIT_TEMPLATE Or _
         Mode = RPT_MODE_INHERITE_TEMPLATE Or _
         Mode = RPT_MODE_NEW_TEMPLATE Or _
         Mode = RPT_MODE_COPY_TEMPLATE Then
        Call mo_UndoTemplate.CopyTo(mo_DesignTemplate)
        Call DisplayTemplateControls(mo_DesignTemplate, scrDesign)
      ElseIf Mode = RPT_MODE_EDIT_SELECTION Then
        Call LoadFieldsSelectionFrame
      ElseIf Mode = RPT_MODE_EDIT_FIELD Then
        Call LoadFieldFrame
      ElseIf Mode = RPT_MODE_NEW_FIELD Then
        Call ClearFieldFrame
      End If
    Case TBR_Quit
      If Mode = RPT_MODE_EDIT_TEMPLATE Or _
         Mode = RPT_MODE_INHERITE_TEMPLATE Or _
         Mode = RPT_MODE_NEW_TEMPLATE Or _
         Mode = RPT_MODE_COPY_TEMPLATE Then
        Mode = RPT_MODE_VIEW_DESIGN
        Call tvItem_NodeClick(tvItem.SelectedItem)
      ElseIf Mode = RPT_MODE_EDIT_SELECTION Then
        Mode = RPT_MODE_VIEW_DESIGN
      ElseIf Mode = RPT_MODE_EDIT_FIELD Or Mode = RPT_MODE_NEW_FIELD Then
        Mode = RPT_MODE_VIEW_FIELDS
      End If
    Case TBR_Delete
      If Mode = RPT_MODE_VIEW_DESIGN Then
        If mo_DesignTemplate.Rpt_Tpl_ID <> 0 Then
          If mo_DesignTemplate.ReadOnly Then
            Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 7, "#You are not owner of this template")
          Else
            If mo_DesignTemplate.HasChildren Then
              Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 8, "#Template contains children")
            Else
              If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 9, "#Really delete ?", "", vbYesNo) = vbYes Then
                Call SetMousePointer(False)
                If mo_DesignTemplate.Delete Then
                  If mo_DesignTemplate.Rpt_Tpl_ID = mo_ExecTemplate.Rpt_Tpl_ID Then
                    Call mo_ExecTemplate.Clear
                    Call DisplayTemplateControls(mo_ExecTemplate, scrExecute)
                  End If
                  Call tvItem.RemoveNode(tvItem.SelectedItem)
                  Call cbo_template.DeleteItemKey(mo_DesignTemplate.Rpt_Tpl_ID)
                  Call mo_DesignTemplate.Clear
                  Call tvItem_NodeClick(tvItem.SelectedItem)
                Else
                  Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 10, "#Delete template failed")
                End If
                Call SetMousePointer(True)
              End If
            End If
          End If
        End If
      ElseIf Mode = RPT_MODE_VIEW_REPORT Then
        If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 9, "#Really delete ?", "", vbYesNo) = vbYes Then
          Call DeleteTabReport(tbsBar.SelectedItem.Index)
        End If
      End If
    Case TBR_Refresh
      If Mode = RPT_MODE_VIEW_DESIGN Then
        Call tvItem.Refresh
      ElseIf Mode = RPT_MODE_VIEW_EXEC Then
        Call cbo_template.Load
        Call cbo_template_ComboItemSelected
      ElseIf Mode = RPT_MODE_VIEW_FIELDS Then
        Call grdlst(scrFieldsTemplate).Refresh
        Call cbo_out_come_from_table.Clear
        Call cbo_Out_Field_Code.Clear
        Call cbo_Out_Field_Join.Clear
        Call cbo_Out_Crosslink_Request.Clear
        Call cbo_Out_Field_Prefix.Clear
        Call cbo_Out_Field_Tag.Clear
        Call cbo_Out_Master_Table.Clear
        Call cbo_Out_Master_Table_Prefix.Clear
        
        Call cbo_Crt_Come_From_Table.Clear
        Call cbo_Crt_Field_Code.Clear
        Call cbo_Crt_Field_Name.Clear
        Call cbo_Crt_Field_Prefix.Clear
        Call cbo_Crt_Grid_Tag.Clear
      End If
    Case TBR_Execute
      If mo_ExecTemplate.Rpt_Tpl_ID <> 0 Then
        If mo_ExecTemplate.GetReportColumnCount > 0 Then
          If Not mo_ExecTemplate.IsOKGroup_By_Weight Then
            If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 19, "#Group weight balance is breaked. Continue ?", , vbYesNo) = vbNo Then Exit Sub
          End If
          Call ExecuteNewReport(pbItem.Language)
        Else
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 11, "#Select at least one field")
        End If
      End If
    Case TBR_Excel
      If Mode = RPT_MODE_VIEW_EXEC Then
        If mo_ExecTemplate.Rpt_Tpl_ID <> 0 Then
          If ExecuteNewReport(pbItem.Language) Then
            Call grdlst(ActiveScreenIndex).ExportToExcel
          End If
        End If
      ElseIf Mode = RPT_MODE_VIEW_REPORT Then
        Call grdlst(ActiveScreenIndex).ExportToExcel
      End If
    Case TBR_Find
      Call EnableReportControl(False, frm_Find)
      Call frm_Find.Zorder(0)
      ml_LastFindCol = grdlst(ActiveScreenIndex).Row
      ml_LastFindRow = grdlst(ActiveScreenIndex).Col
    Case TBR_Share
      If mo_DesignTemplate.Rpt_Tpl_ID <> 0 Then
        If mo_DesignTemplate.ReadOnly Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 7, "#You are not owner of this template")
        Else
          cv_Share.Calling_Key_Values = mo_DesignTemplate.Rpt_Tpl_ID
          If cv_Share.LoadList Then
            Call cv_Share.SetVisibleList("main")
            Call EnableReportControl(False, frm_Share)
          End If
        End If
      End If
    Case TBR_OpGT
      Call MoveSelectedRows(False)
    Case TBR_OpLT
      Call MoveSelectedRows(True)
    Case TBR_Exit
      RaiseEvent quit
    End Select
  End If
End Sub

Private Sub pbGrid_Action(ByVal as_Role As String, as_Language As String)
Dim ll_Row As Long
Dim ll_Col As Long
Dim lv_Code As Variant
Dim lv_Desc As Variant

  Select Case as_Role
  Case TBR_Execute
    Call grd_Filter.Execute
  Case TBR_Quit
    Call EnableReportControl(True, frm_Grid)
  Case TBR_Add
    For ll_Row = 0 To grd_Filter.SelectedCount - 1
      If Not grd_Criteria.SearchKey(True, grd_Filter.SelectedKey(ll_Row)) Then
        If grd_Criteria.AddLine Then
          For ll_Col = 0 To grd_Filter.Cols - 1
            grd_Criteria.Data(grd_Criteria.Rows - 1, ll_Col) = grd_Filter.SelectedLine(ll_Row, ll_Col)
          Next
        End If
      End If
    Next
  Case TBR_Delete
    For ll_Row = grd_Criteria.SelectedCount - 1 To 0 Step -1
      Call grd_Criteria.DeleteLine(grd_Criteria.SelectedKey(ll_Row))
    Next
  Case TBR_Valid
    If Not (mo_CurFieldDef Is Nothing) Then
      If grd_Criteria.Rows > 0 Then
        If (cbo_GridOperator.Text = "") Or ((cbo_GridLogic.Text = "") And cbo_GridLogic.Visible) Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 24, "#Select an operator and logic.")
          Exit Sub
        End If
        ReDim lv_Code(grd_Criteria.Rows - 1)
        ReDim lv_Desc(grd_Criteria.Rows - 1)
        If grd_Criteria.FirstLine Then
          Do
            lv_Code(grd_Criteria.Row) = grd_Criteria.CurrentLine(0)
            lv_Desc(grd_Criteria.Row) = grd_Criteria.CurrentLine(1)
          Loop While grd_Criteria.NextLine
        End If
        mo_CurFieldDef.Code_Selected = Join(lv_Code, USERSEP)
        mo_CurFieldDef.Code_Operator = cbo_GridOperator.Text
        mo_CurFieldDef.Logic = cbo_GridLogic.Text
        mo_CurFieldDef.Info_Displayed_To_User = cbo_GridOperator.Text & " " & cbo_GridLogic.Text & "(" & Join(lv_Desc, USERSEP) & ")"
        mo_CurFieldDef.Sql_Clause = GetSQL_Clause(lv_Code, mo_CurFieldDef, cbo_GridOperator.Text, cbo_GridLogic.Text)
      Else
        If mo_CurFieldDef.Locked <> "" Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 25, "#Select at least one criteria.")
          Exit Sub
        End If
        mo_CurFieldDef.Code_Selected = ""
        mo_CurFieldDef.Code_Operator = ""
        mo_CurFieldDef.Info_Displayed_To_User = ""
        mo_CurFieldDef.Sql_Clause = ""
      End If
      mo_CurFieldDef.SQL_Flag = "U"
      Call UpdateGridRow(GetVisibleGrid, mo_CurFieldDef)
    End If
    Set mo_CurFieldDef = Nothing
    Set mo_CurParentFieldDef = Nothing
    Call EnableReportControl(True, frm_Grid)
  End Select
End Sub

Private Function MoveSelectedRows(ab_Delete As Boolean) As Boolean
Dim ll_Row As Long
Dim ll_Col As Long
Dim lv_Data As Variant

  ReDim lv_Data(grdFrom.Cols - 1)
  If ab_Delete Then
    If grdTo.SelectedCount > 0 Then
      For ll_Row = grdTo.SelectedCount - 1 To 0 Step -1
        For ll_Col = 0 To grdTo.Cols - 1
          lv_Data(ll_Col) = grdTo.SelectedLine(ll_Row, ll_Col)
        Next
        If grdFrom.AddLine(lv_Data) Then Call grdTo.DeleteLine(grdTo.SelectedKey(ll_Row))
        If grdFrom.CurrentLine("out_hidden") <> "" Then grdFrom.LineColor(grdFrom.Row) = COLOR_HIDDEN
      Next
      Call grdTo.DeselectRow
    End If
  Else
    If grdFrom.SelectedCount > 0 Then
      For ll_Row = grdFrom.SelectedCount - 1 To 0 Step -1
        For ll_Col = 0 To grdFrom.Cols - 1
          lv_Data(ll_Col) = grdFrom.SelectedLine(ll_Row, ll_Col)
        Next
        If grdTo.AddLine(lv_Data) Then Call grdFrom.DeleteLine(grdFrom.SelectedKey(ll_Row))
        If grdTo.CurrentLine("out_hidden") <> "" Then grdTo.LineColor(grdTo.Row) = COLOR_HIDDEN
      Next
      Call grdFrom.DeselectRow
    End If
  End If
End Function

Private Function ApplyChangedRowsRecursively(ao_Template As ArmRptTemplate, ao_Node As Node) As Boolean
Dim lo_Node As Node
Dim lb_Result As Boolean
Dim ll_ErrorCode As Long
  
On Error GoTo ErrorHandler
  lb_Result = False
  If Not (ao_Node Is Nothing) Then
    lb_Result = True
    Set lo_Node = ao_Node.Child
    Do While Not (lo_Node Is Nothing)
      lb_Result = ApplyChangedRowsRecursively(ao_Template, lo_Node)
      If Not lb_Result Then Exit Do
      Set lo_Node = lo_Node.Next
    Loop
    If lb_Result Then
      ao_Template.Rpt_Tpl_ID = tvItem.NodeInfo(ao_Node).IDValue
      lb_Result = ao_Template.Save(ll_ErrorCode, False, False)
    End If
  End If
  ApplyChangedRowsRecursively = lb_Result
  Exit Function
ErrorHandler:
  ApplyChangedRowsRecursively = False
End Function

Private Function ApplyChangedRows() As Boolean
Dim lb_Result As Boolean

On Error GoTo ErrorHandler
  lb_Result = False
  Call SetMousePointer(False)
  If UpdateSelectedRows(mo_DesignTemplate) Then
    If mo_Db.ExecuteSQL("BEGIN TRANSACTION") Then
      If ApplyChangedRowsRecursively(mo_DesignTemplate, tvItem.SelectedItem) Then
        lb_Result = mo_Db.ExecuteSQL("COMMIT TRANSACTION")
      End If
      If Not lb_Result Then
        Call mo_Db.ExecuteSQL("ROLLBACK TRANSACTION")
      End If
    End If
  End If
  Call mo_DesignTemplate.Refresh
  Call RefreshGrid(mo_DesignTemplate, grdlst(scrDesign))
  Mode = RPT_MODE_VIEW_DESIGN
  Call SetMousePointer(True)
  If Not lb_Result Then
    Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 3, "#Save template failed")
  End If
  ApplyChangedRows = lb_Result
  Exit Function
ErrorHandler:
  Call SetMousePointer(True)
  Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 3, "#Save template failed")
  ApplyChangedRows = False
End Function

Private Function UpdateSelectedRows(ao_Template As ArmRptTemplate) As Boolean
Dim lo_FieldDef As ArmFieldDef
Dim ll_Index As Long

On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  grdTo.Redraw = False
  For Each lo_FieldDef In ao_Template.Fields
    If Not grdTo.SearchKey(True, Array(lo_FieldDef.Out_Field_ID)) Then
      lo_FieldDef.SQL_Flag = "D"
    End If
  Next
  If grdTo.FirstLine Then
    Do
      Set lo_FieldDef = ao_Template.GetFieldDef(grdTo.CurrentKey(0))
      If lo_FieldDef Is Nothing Then
        'this is new field, so add it to collection
        Set lo_FieldDef = ao_Template.AddFieldDef(ao_Template.Rpt_Tpl_ID, grdTo.CurrentKey(0))
        lo_FieldDef.SQL_Flag = "I"
        lo_FieldDef.Field_order = grdTo.Row
        lo_FieldDef.Original = False
      Else
        'make sure field is not marked as deleted or marked as insert if not original
        lo_FieldDef.SQL_Flag = IIf(lo_FieldDef.Original, "", "I")
      End If
    Loop Until Not grdTo.NextLine
  End If
  grdTo.Redraw = True
  Call SetMousePointer(True)
  UpdateSelectedRows = True
  Exit Function
ErrorHandler:
  grdTo.Redraw = True
  Call SetMousePointer(True)
  UpdateSelectedRows = False
End Function

Private Function LoadFieldsSelectionFrame() As Boolean
Dim ll_Index As Long

On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  grdFrom.Redraw = False
  grdTo.Redraw = False
  Call grdFrom.Refresh
  If grdFrom.FirstLine Then
    Do
      If grdFrom.CurrentLine("Out_Hidden") <> "" Then
        grdFrom.LineColor(grdFrom.Row) = COLOR_HIDDEN
      End If
    Loop Until Not grdFrom.NextLine
  End If
  
  Call RefreshGrid(mo_DesignTemplate, grdTo, True)
  If grdTo.FirstLine Then
    Do
      Call grdFrom.DeleteLine(grdTo.CurrentKey)
    Loop Until Not grdTo.NextLine
  End If
  grdFrom.Redraw = True
  grdTo.Redraw = True
  Call SetMousePointer(True)
  LoadFieldsSelectionFrame = True
  Exit Function
ErrorHandler:
  grdFrom.Redraw = True
  grdTo.Redraw = True
  Call SetMousePointer(True)
  LoadFieldsSelectionFrame = False
End Function

Private Sub pbDate_action(ByVal as_Role As String, as_Language As String)
Dim lt_Operator As rpt_Operator
Dim ls_SQL_Clause As String

  Select Case as_Role
  Case TBR_Quit
    Call EnableReportControl(True, frm_Date)
  Case TBR_Valid
    If Not (mo_CurFieldDef Is Nothing) Then
      lt_Operator = GetOperator(cbo_DateOperator.Text)
      If lt_Operator.rpt_Operand_Count = 0 Then
        mo_CurFieldDef.Code_Operator = ""
        mo_CurFieldDef.Info_Displayed_To_User = ""
        mo_CurFieldDef.Sql_Clause = ""
      Else
        If (cal1.Visible And (cal1.date_us = "")) Or _
           (cal2.Visible And (cal2.date_us = "")) Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 12, "#Enter value")
          Exit Sub
        End If
        mo_CurFieldDef.Code_Selected = cal1.date_us
        If lt_Operator.rpt_Operand_Count > 1 Then
          mo_CurFieldDef.Code_Selected = mo_CurFieldDef.Code_Selected & SEP & cal2.date_us
        End If
        mo_CurFieldDef.Code_Operator = cbo_DateOperator.Text
        mo_CurFieldDef.Sql_Clause = ReplaceSQLClause(lt_Operator.rpt_Operator_Clause, mo_CurFieldDef.Out_Full_Field_Name, cal1.date_sql, cal2.date_sql, "CHAR")
        mo_CurFieldDef.Info_Displayed_To_User = ReplaceSQLClause(lt_Operator.rpt_Operator_Clause_Display, mo_CurFieldDef.Out_Business_Name, cal1.date_courte, cal2.date_courte, "CHAR")
      End If
      mo_CurFieldDef.SQL_Flag = "U"
      Call UpdateGridRow(GetVisibleGrid, mo_CurFieldDef)
      Call EnableReportControl(True, frm_Date)
    End If
 End Select
End Sub

Private Sub pbCombo_action(ByVal as_Role As String, as_Language As String)
Dim lt_Operator As rpt_Operator
Dim ls_Text As String
Dim ls_Key As String

  Select Case as_Role
  Case TBR_Quit
    Call EnableReportControl(True, frm_Combo)
  Case TBR_Valid
    If Not (mo_CurFieldDef Is Nothing) Then
      lt_Operator = GetOperator(cbo_ComboOperator.Text)
      If lt_Operator.rpt_Operand_Count = 0 Then
        mo_CurFieldDef.Code_Operator = ""
        mo_CurFieldDef.Info_Displayed_To_User = ""
        mo_CurFieldDef.Sql_Clause = ""
      Else
        ls_Key = ""
        ls_Text = ""
        If Not (cbo_Combo.SelectedItem Is Nothing) Then
          ls_Key = cbo_Combo.SelectedItem.Key
          ls_Text = cbo_Combo.SelectedItem.DisplayText
        End If
        
        mo_CurFieldDef.Code_Selected = ls_Key
        mo_CurFieldDef.Code_Operator = cbo_ComboOperator.Text
        
        mo_CurFieldDef.Sql_Clause = ReplaceSQLClause(lt_Operator.rpt_Operator_Clause, mo_CurFieldDef.Out_Full_Field_Name, ls_Key, "", "CHAR")
        mo_CurFieldDef.Info_Displayed_To_User = ReplaceSQLClause(lt_Operator.rpt_Operator_Clause_Display, mo_CurFieldDef.Out_Business_Name, ls_Text, "", "CHAR")
      End If
      mo_CurFieldDef.SQL_Flag = "U"
      Call UpdateGridRow(GetVisibleGrid, mo_CurFieldDef)
      Call EnableReportControl(True, frm_Combo)
    End If
  End Select
End Sub

Private Sub pbValue_action(ByVal as_Role As String, as_Language As String)
Dim lt_Operator As rpt_Operator

  Select Case as_Role
  Case TBR_Quit
    Call EnableReportControl(True, frm_Value)
  Case TBR_Valid
    If Not (mo_CurFieldDef Is Nothing) Then
      lt_Operator = GetOperator(cbo_ValueOperator.Text)
      If lt_Operator.rpt_Operand_Count = 0 Then
        mo_CurFieldDef.Code_Operator = ""
        mo_CurFieldDef.Info_Displayed_To_User = ""
        mo_CurFieldDef.Sql_Clause = ""
      Else
        If StrComp(frm_Value.Tag, "NUMERIC", vbTextCompare) = 0 Then
          If Not isNumeric(txt_Val1.Text) Then
            Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 13, "#Enter numeric value")
            Exit Sub
          End If
          If lt_Operator.rpt_Operand_Count > 1 Then
            If Not isNumeric(txt_Val2.Text) Then
              Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 13, "#Enter numeric value")
              Exit Sub
            End If
          End If
        End If
        mo_CurFieldDef.Code_Selected = txt_Val1.Text
        If lt_Operator.rpt_Operand_Count > 1 Then
          mo_CurFieldDef.Code_Selected = mo_CurFieldDef.Code_Selected & SEP & txt_Val2.Text
        End If
        mo_CurFieldDef.Code_Operator = cbo_ValueOperator.Text
        mo_CurFieldDef.Sql_Clause = ReplaceSQLClause(lt_Operator.rpt_Operator_Clause, mo_CurFieldDef.Out_Full_Field_Name, txt_Val1.Text, txt_Val2.Text, frm_Value.Tag)
        mo_CurFieldDef.Info_Displayed_To_User = ReplaceSQLClause(lt_Operator.rpt_Operator_Clause_Display, mo_CurFieldDef.Out_Business_Name, txt_Val1.Text, txt_Val2.Text, frm_Value.Tag)
      End If
      mo_CurFieldDef.SQL_Flag = "U"
      Call UpdateGridRow(GetVisibleGrid, mo_CurFieldDef)
      Call EnableReportControl(True, frm_Value)
    End If
  End Select
End Sub

Private Sub pbFind_action(ByVal as_Role As String, as_Language As String)

  Select Case as_Role
  Case TBR_Quit
    Call EnableReportControl(True, frm_Find)
  Case TBR_Find
    Call FindReportData(txt_Find.Text)
  End Select
End Sub

Private Sub pbList_action(ByVal as_Role As String, as_Language As String)
Dim lv_Code As Variant

  Select Case as_Role
  Case TBR_Quit
    Call EnableReportControl(True, frm_List)
  Case TBR_SelectAll
    Call ListViewChange(lvw_List, True)
    Call UpdateCheckedItems(lvw_List, txt_List)
  Case TBR_Valid
    If Not (mo_CurFieldDef Is Nothing) Then
      lv_Code = GetCheckedCodes(lvw_List)
      If IsArray(lv_Code) Then
        If (cbo_ListOperator.Text = "") Or (cbo_ListLogic.Visible And cbo_ListLogic.Text = "") Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 24, "#Select an operator and logic.")
          Exit Sub
        End If
        mo_CurFieldDef.Code_Selected = Join(lv_Code, USERSEP)
        mo_CurFieldDef.Code_Operator = cbo_ListOperator.Text
        mo_CurFieldDef.Logic = cbo_ListLogic.Text
        mo_CurFieldDef.Info_Displayed_To_User = cbo_ListOperator.Text & " " & cbo_ListLogic.Text & "(" & txt_List.Text & ")"
        mo_CurFieldDef.Sql_Clause = GetSQL_Clause(lv_Code, mo_CurFieldDef, cbo_ListOperator.Text, cbo_ListLogic.Text)
      Else
        If mo_CurFieldDef.Locked <> "" Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 25, "#Select at least one criteria.")
          Exit Sub
        End If
        mo_CurFieldDef.Code_Selected = ""
        mo_CurFieldDef.Code_Operator = ""
        mo_CurFieldDef.Info_Displayed_To_User = ""
        mo_CurFieldDef.Sql_Clause = ""
      End If
      mo_CurFieldDef.SQL_Flag = "U"
      Call UpdateGridRow(GetVisibleGrid, mo_CurFieldDef)
    End If
    Set mo_CurFieldDef = Nothing
    Set mo_CurParentFieldDef = Nothing
    Call EnableReportControl(True, frm_List)
  End Select
End Sub

Private Function CanReorderFields(ao_Field1 As ArmFieldDef, ao_Field2 As ArmFieldDef, as_SortType As String) As Boolean

  CanReorderFields = False
  If StrComp(as_SortType, "FIELD_ORDER", vbTextCompare) = 0 Then
    If ao_Field1.Group_By <> ao_Field2.Group_By Then
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 14, "#You can not reorder a detailed field within the group by field")
      Exit Function
    End If
    If ao_Field1.Field_selected <> ao_Field2.Field_selected Then
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 28, "#You can not reorder selected and unselected fields")
      Exit Function
    End If
  ElseIf StrComp(as_SortType, "REPORT_ORDER", vbTextCompare) = 0 Then
    If (ao_Field1.Group_By <> "") Or (ao_Field2.Group_By <> "") Then
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 17, "#You can not reorder group by field")
      Exit Function
    End If
  End If
  If (ao_Field1.Locked <> "") Or (ao_Field2.Locked <> "") Then
    Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 1, "#Field is locked")
    Exit Function
  End If
  CanReorderFields = True
End Function

Private Sub pbSorting_action(ByVal as_Role As String, as_Language As String)
Dim ll_Index As Long
Dim ll_Data As Long
Dim ls_Text As String
Dim lo_Template As ArmRptTemplate
Dim lo_FieldDef As ArmFieldDef
Dim lo_FieldDef1 As ArmFieldDef
Dim lo_FieldDef2 As ArmFieldDef

  ll_Index = lst_Sorting.ListIndex
  If ActiveScreenIndex = scrDesign Then
    Set lo_Template = mo_DesignTemplate
  ElseIf ActiveScreenIndex = scrExecute Then
    Set lo_Template = mo_ExecTemplate
  End If
  
  Select Case as_Role
  Case TBR_Quit
    Call EnableReportControl(True, frm_Sorting)
  Case TBR_Valid
    If Not (lo_Template Is Nothing) Then
      For ll_Index = 0 To lst_Sorting.ListCount - 1
        Set lo_FieldDef = lo_Template.GetFieldDef(lst_Sorting.ItemData(ll_Index))
        If Not (lo_FieldDef Is Nothing) Then
          If StrComp(frm_Sorting.Tag, "FIELD_ORDER", vbTextCompare) = 0 Then
            lo_FieldDef.Field_order = ll_Index + 1
          ElseIf StrComp(frm_Sorting.Tag, "REPORT_ORDER", vbTextCompare) = 0 Then
            lo_FieldDef.Report_Order = ll_Index + 1
          End If
        End If
      Next
      Call lo_Template.ReorderFields
    End If
    Call RefreshGrid(lo_Template, GetVisibleGrid)
    Call EnableReportControl(True, frm_Sorting)
  Case TBR_Next
    If (ll_Index >= 0) And (ll_Index < lst_Sorting.ListCount - 1) Then
      Set lo_FieldDef1 = lo_Template.GetFieldDef(lst_Sorting.ItemData(ll_Index))
      Set lo_FieldDef2 = lo_Template.GetFieldDef(lst_Sorting.ItemData(ll_Index + 1))
      If CanReorderFields(lo_FieldDef1, lo_FieldDef2, frm_Sorting.Tag) Then
        ll_Data = lst_Sorting.ItemData(ll_Index)
        ls_Text = lst_Sorting.Text
        Call lst_Sorting.RemoveItem(ll_Index)
        Call lst_Sorting.AddItem(ls_Text, ll_Index + 1)
        lst_Sorting.ItemData(lst_Sorting.NewIndex) = ll_Data
        lst_Sorting.ListIndex = lst_Sorting.NewIndex
      End If
    End If
  Case TBR_Previous
    If ll_Index > 0 Then
      Set lo_FieldDef1 = lo_Template.GetFieldDef(lst_Sorting.ItemData(ll_Index))
      Set lo_FieldDef2 = lo_Template.GetFieldDef(lst_Sorting.ItemData(ll_Index - 1))
      If CanReorderFields(lo_FieldDef1, lo_FieldDef2, frm_Sorting.Tag) Then
        ll_Data = lst_Sorting.ItemData(ll_Index)
        ls_Text = lst_Sorting.Text
        Call lst_Sorting.RemoveItem(ll_Index)
        Call lst_Sorting.AddItem(ls_Text, ll_Index - 1)
        lst_Sorting.ItemData(lst_Sorting.NewIndex) = ll_Data
        lst_Sorting.ListIndex = lst_Sorting.NewIndex
      End If
    End If
  End Select
End Sub

Private Sub pbMeasure_action(ByVal as_Role As String, as_Language As String)
Dim ls_Measure As String
Dim lv_Code As Variant

  Select Case UCase(as_Role)
  Case TBR_Quit
    Call EnableReportControl(True, frm_Measure)
  Case TBR_Valid
    If Not (mo_CurFieldDef Is Nothing) Then
      lv_Code = GetCheckedCodes(lvw_Measure)
      If IsArray(lv_Code) Then
        ls_Measure = Join(lv_Code, USERSEP)
      Else
        ls_Measure = ""
      End If
      If mo_CurFieldDef.Group_By <> "" Then
        If (ls_Measure <> "") And (StrComp(ls_Measure, "COUNT", vbTextCompare) <> 0) Then
          'don't allow to do other measure function than count on group column
          Exit Sub
        End If
      End If
      mo_CurFieldDef.Measure = ls_Measure
      mo_CurFieldDef.SQL_Flag = "U"
      Call UpdateGridRow(GetVisibleGrid, mo_CurFieldDef)
    End If
    Set mo_CurFieldDef = Nothing
    Set mo_CurParentFieldDef = Nothing
    Call EnableReportControl(True, frm_Measure)
  End Select
End Sub

Private Sub pbShare_action(ByVal as_Role As String, as_Language As String)

  Select Case UCase(as_Role)
  Case TBR_Quit
    Call EnableReportControl(True, frm_Share)
  Case TBR_Valid
    If cv_Share.SaveList Then
      Call cv_Share.SetVisibleList("MAIN")
    Else
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 15, "#Error update share")
    End If
    Call UpdateTVNodeData(tvItem.SelectedItem)
  End Select
End Sub

Private Sub cbo_DateOperator_ComboItemSelected()
Dim lt_Operator As rpt_Operator

  lt_Operator = GetOperator(cbo_DateOperator.Text)
  cal1.Visible = lt_Operator.rpt_Operand_Count > 0
  cal2.Visible = lt_Operator.rpt_Operand_Count > 1
End Sub

Private Sub cbo_ValueOperator_ComboItemSelected()
Dim lt_Operator As rpt_Operator

  lt_Operator = GetOperator(cbo_ValueOperator.Text)
  txt_Val1.Visible = lt_Operator.rpt_Operand_Count > 0
  txt_Val2.Visible = lt_Operator.rpt_Operand_Count > 1
End Sub

Private Sub tbsBar_Click()
Dim ll_Screen As Long

  ll_Screen = ActiveScreenIndex
  If ll_Screen = scrExecute Then
    Mode = RPT_MODE_VIEW_EXEC
  ElseIf ll_Screen = scrDesign Then
    Mode = RPT_MODE_VIEW_DESIGN
  ElseIf ll_Screen = scrFieldsTemplate Then
    Mode = RPT_MODE_VIEW_FIELDS
  Else
    Mode = RPT_MODE_VIEW_REPORT
  End If
End Sub

Private Sub txt_DescDesign_Change()
  If Mode = RPT_MODE_EDIT_TEMPLATE Or Mode = RPT_MODE_NEW_TEMPLATE Or _
     Mode = RPT_MODE_INHERITE_TEMPLATE Or Mode = RPT_MODE_COPY_TEMPLATE Then
    mo_DesignTemplate.Rpt_Tpl_Comment = txt_DescDesign.Text
    mo_DesignTemplate.SQL_Flag = "U"
  End If
End Sub

Private Sub txt_NameDesign_Change()
  If Mode = RPT_MODE_EDIT_TEMPLATE Or Mode = RPT_MODE_NEW_TEMPLATE Or _
     Mode = RPT_MODE_INHERITE_TEMPLATE Or Mode = RPT_MODE_COPY_TEMPLATE Then
    mo_DesignTemplate.Rpt_Tpl_Name = txt_NameDesign.Text
    mo_DesignTemplate.SQL_Flag = "U"
  End If
End Sub

Private Function EditCriteriaList(ao_FieldDef As ArmFieldDef, ao_ParentFieldDef As ArmFieldDef) As Boolean
Dim ls_SQL As String
Dim ll_Cursor As Long
Dim lv_Checked As Variant
Dim lv_Locked As Variant
Dim ls_Code_Selected As String

  EditCriteriaList = False
  
  
  Call UpdateComboList(cbo_ListOperator, ao_FieldDef.Crt_Report_Operator, USERSEP)
  Call SelectCombo(cbo_ListOperator, ao_FieldDef.Code_Operator)
  
  If ao_FieldDef.Out_Can_Select_Logic <> "" Then
    cbo_ListLogic.Visible = True
    Call SelectCombo(cbo_ListLogic, ao_FieldDef.Logic, True)
  Else
    cbo_ListLogic.Visible = False
    Set cbo_ListLogic.SelectedItem = Nothing
  End If
  
  ls_SQL = ReplaceSQLPLaceholders(ao_FieldDef.GetCrtSQL)
  If ls_SQL <> "" Then
    lv_Checked = Empty
    If ao_FieldDef.Code_Selected <> "" Then
      lv_Checked = Split(ao_FieldDef.Code_Selected, USERSEP)
    End If
    ll_Cursor = OpenCursor(ls_SQL)
    If ll_Cursor <> 0 Then
      lv_Locked = Empty
      ls_Code_Selected = ""
      If ao_FieldDef.Locked = "P" Then
        If ActiveScreenIndex = scrDesign Then
          If Not (ao_ParentFieldDef Is Nothing) Then
            ls_Code_Selected = ao_ParentFieldDef.Code_Selected
          End If
        Else
          ls_Code_Selected = ao_FieldDef.Init_Code_Selected
        End If
        If ls_Code_Selected <> "" Then
          lv_Locked = Split(ls_Code_Selected, USERSEP)
        End If
      End If
      Call FillListViewCursor(lvw_List, ll_Cursor, lv_Checked, lv_Locked)
      Call CloseCursor(ll_Cursor)
      Set mo_CurFieldDef = ao_FieldDef
      Set mo_CurParentFieldDef = ao_ParentFieldDef
      Call UpdateCheckedItems(lvw_List, txt_List)
      frm_List.Caption = ao_FieldDef.Out_Business_Name
      Call EnableReportControl(False, frm_List)
      EditCriteriaList = True
    Else
      Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 16, "#Error execute SQL query")
    End If
  End If
End Function

Private Function EditCriteriaValue(ao_FieldDef As ArmFieldDef, ao_ParentFieldDef As ArmFieldDef, as_Type As String) As Boolean
Dim lv_Value As Variant

  Set mo_CurFieldDef = ao_FieldDef
  Set mo_CurParentFieldDef = ao_ParentFieldDef
  Call UpdateComboList(cbo_ValueOperator, ao_FieldDef.Crt_Report_Operator, USERSEP)
  Call SelectCombo(cbo_ValueOperator, ao_FieldDef.Code_Operator)
  Call cbo_ValueOperator_ComboItemSelected
  frm_Value.Tag = as_Type
  frm_Value.Caption = ao_FieldDef.Out_Business_Name
  
  txt_Val1.Text = ""
  txt_Val2.Text = ""
  If ao_FieldDef.Code_Selected <> "" Then
    lv_Value = Split(ao_FieldDef.Code_Selected, SEP)
    txt_Val1.Text = lv_Value(0)
    If UBound(lv_Value) > 0 Then txt_Val2.Text = lv_Value(1)
  End If
  Call EnableReportControl(False, frm_Value)
  EditCriteriaValue = True
End Function

Private Function EditCriteriaCombo(ao_FieldDef As ArmFieldDef, ao_ParentFieldDef As ArmFieldDef) As Boolean
Dim ls_SQL As String

  EditCriteriaCombo = False
  Set mo_CurFieldDef = ao_FieldDef
  Set mo_CurParentFieldDef = ao_ParentFieldDef
  Call UpdateComboList(cbo_ComboOperator, ao_FieldDef.Crt_Report_Operator, USERSEP)
  Call SelectCombo(cbo_ComboOperator, ao_FieldDef.Code_Operator)
  
  ls_SQL = ReplaceSQLPLaceholders(ao_FieldDef.GetCrtSQL)
  If ls_SQL <> "" Then
  
    Call cbo_Combo.Clear
    cbo_Combo.Request = ls_SQL
    Call cbo_Combo.Load
    If ao_FieldDef.Code_Selected <> "" Then
      Call cbo_Combo.SearchItem(ao_FieldDef.Code_Selected)
    End If
    frm_Combo.Caption = ao_FieldDef.Out_Business_Name
    Call EnableReportControl(False, frm_Combo)
    EditCriteriaCombo = True
  End If
End Function

Private Function EditCriteriaDate(ao_FieldDef As ArmFieldDef, ao_ParentFieldDef As ArmFieldDef) As Boolean
Dim lv_Date As Variant

  EditCriteriaDate = False
  Set mo_CurFieldDef = ao_FieldDef
  Set mo_CurParentFieldDef = ao_ParentFieldDef
  Call UpdateComboList(cbo_DateOperator, ao_FieldDef.Crt_Report_Operator, USERSEP)
  Call SelectCombo(cbo_DateOperator, ao_FieldDef.Code_Operator)
  Call cbo_DateOperator_ComboItemSelected
  frm_Date.Caption = ao_FieldDef.Out_Business_Name
  Call cal1.reinit_cal
  Call cal2.reinit_cal
  If ao_FieldDef.Code_Selected <> "" Then
    lv_Date = Split(ao_FieldDef.Code_Selected, SEP)
    cal1.date_us = lv_Date(0)
    If UBound(lv_Date) > 0 Then cal2.date_us = lv_Date(1)
  End If
  
  Call EnableReportControl(False, frm_Date)
  EditCriteriaDate = True
End Function

Private Function EditCriteriaGrid(ao_FieldDef As ArmFieldDef, ao_ParentFieldDef As ArmFieldDef) As Boolean
Dim ls_SQL As String, ls_Code_Selected As String
Dim ll_Cursor As Long
Dim ll_Index As Long
Dim lv_Selected As Variant
Dim lv_Locked As Variant
Dim lv_Fields As Variant
Dim lv_Columns As Variant

  EditCriteriaGrid = False
  Call UpdateComboList(cbo_GridOperator, ao_FieldDef.Crt_Report_Operator, USERSEP)
  Call SelectCombo(cbo_GridOperator, ao_FieldDef.Code_Operator)
  
  If ao_FieldDef.Out_Can_Select_Logic <> "" Then
    cbo_GridLogic.Visible = True
    Call SelectCombo(cbo_GridLogic, ao_FieldDef.Logic, True)
  Else
    cbo_GridLogic.Visible = False
    Set cbo_GridLogic.SelectedItem = Nothing
  End If
  
  ls_SQL = ReplaceSQLPLaceholders(ao_FieldDef.GetCrtSQL)
  If ls_SQL <> "" Then
    lv_Selected = Empty
    Call grd_Criteria.ResetGrid
    Call grd_Filter.ResetGrid
    If (ao_FieldDef.Crt_Field_Code <> "") And (ao_FieldDef.Crt_Field_Name <> "") Then
      'initializing columns for grids
      lv_Fields = Split(ao_FieldDef.Crt_Field_Name, SEP)
      ReDim lv_Columns(UBound(lv_Fields) + 1)
      
      lv_Columns(0) = ao_FieldDef.Crt_Field_Code & SEP & "0" & SEP & "1" & SEP & ao_FieldDef.Crt_Field_Code & SEP & "ID"
      For ll_Index = 0 To UBound(lv_Fields)
        lv_Columns(ll_Index + 1) = lv_Fields(ll_Index) & SEP & "1500" & SEP & "0" & SEP & lv_Fields(ll_Index) & SEP & lv_Fields(ll_Index)
      Next
      'initializing top grid - criteria selection
      If Not grd_Criteria.SetColumns(lv_Columns) Then Exit Function
      Call grd_Criteria.LoadConstants(ptSQL, "rpt_csts_sel " & SQLStr(ao_FieldDef.Crt_Grid_Tag) & "," & SQLStr(ms_Language), ctColumns)
      If ao_FieldDef.Code_Selected <> "" Then
        lv_Selected = Split(ao_FieldDef.Code_Selected, USERSEP)
        If Not grd_Criteria.Load(ao_FieldDef.UpdateWhereCrtSQL(ls_SQL, lv_Selected), True) Then
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 16, "#Error execute SQL query")
          Exit Function
        End If
      End If
      'initialize bottom grid - filter selection
      If Not grd_Filter.SetColumns(lv_Columns) Then Exit Function
      'copy titles - don't load again from sql db
      For ll_Index = 0 To grd_Criteria.Cols - 1
        grd_Filter.Columns(ll_Index).Title = grd_Criteria.Columns(ll_Index).Title
      Next
      
      lv_Locked = Empty
      ls_Code_Selected = ""
      If ao_FieldDef.Locked = "P" Then
        If ActiveScreenIndex = scrDesign Then
          If Not (ao_ParentFieldDef Is Nothing) Then
            ls_Code_Selected = ao_ParentFieldDef.Code_Selected
          End If
        Else
          ls_Code_Selected = ao_FieldDef.Init_Code_Selected
        End If
        
        If ls_Code_Selected <> "" Then
          lv_Locked = Split(ls_Code_Selected, USERSEP)
          ls_SQL = ao_ParentFieldDef.UpdateWhereCrtSQL(ls_SQL, lv_Locked)
        End If
      End If
      
      grd_Filter.Requests = ReplaceSQLPLaceholders(ls_SQL)
      Call grd_Criteria.LoadConstants(ptStatic, ao_FieldDef.Out_Business_Name & SEP & "CENTER", ctTopGrid)
      Call grd_Filter.LoadConstants(ptStatic, ao_FieldDef.Out_Business_Name & SEP & "CENTER", ctTopGrid)
      'initilize and show frame
      Set mo_CurFieldDef = ao_FieldDef
      Set mo_CurParentFieldDef = ao_ParentFieldDef
      frm_Grid.Caption = ao_FieldDef.Out_Business_Name
      Call EnableReportControl(False, frm_Grid)
      EditCriteriaGrid = True
    End If
  End If
End Function

Private Function EditCriteria(ao_FieldDef As ArmFieldDef, ao_ParentFieldDef As ArmFieldDef) As Boolean

  EditCriteria = False
  If Not (ao_FieldDef Is Nothing) Then
    Select Case UCase(ao_FieldDef.Crt_Type)
    Case "LIST"
      EditCriteria = EditCriteriaList(ao_FieldDef, ao_ParentFieldDef)
    Case "COMBO"
      EditCriteria = EditCriteriaCombo(ao_FieldDef, ao_ParentFieldDef)
    Case "CHAR", "CHAR CONST" 'mw 1.8.2008
      EditCriteria = EditCriteriaValue(ao_FieldDef, ao_ParentFieldDef, "CHAR")
    Case "NUMERIC", "NUM CONST" 'mw 1.8.2008
      EditCriteria = EditCriteriaValue(ao_FieldDef, ao_ParentFieldDef, "NUMERIC")
    Case "DATE", "DATE CONST " 'mw 1.8.2008
      EditCriteria = EditCriteriaDate(ao_FieldDef, ao_ParentFieldDef)
    Case "GRID"
      EditCriteria = EditCriteriaGrid(ao_FieldDef, ao_ParentFieldDef)
    End Select
  End If
End Function

Private Function EditMeasure(ao_FieldDef As ArmFieldDef, ao_ParentFieldDef As ArmFieldDef) As Boolean
Dim lv_Code As Variant
Dim lv_Text As Variant
Dim lv_Checked As Variant

  lv_Code = Split(ao_FieldDef.Out_Measure_Function, USERSEP)
  lv_Text = lv_Code
  lv_Checked = Split(ao_FieldDef.Measure, USERSEP)
  Call FillListViewArray(lvw_Measure, lv_Code, lv_Text, lv_Checked, Empty)
  Call AutoSizeListView(lvw_Measure)
  Set mo_CurFieldDef = ao_FieldDef
  Set mo_CurParentFieldDef = ao_ParentFieldDef
  frm_Measure.Caption = ao_FieldDef.Out_Business_Name
  Call EnableReportControl(False, frm_Measure)
End Function

Private Function EditOrder(ao_Template As ArmRptTemplate, as_Column As String) As Boolean
Dim lo_FieldDef As ArmFieldDef
Dim ll_Index As Long

  EditOrder = False
  If Not (ao_Template Is Nothing) Then
    Call lst_Sorting.Clear
    Call ao_Template.SortByField(as_Column)
    
    For Each lo_FieldDef In ao_Template.Fields
      If lo_FieldDef.Out_Hidden = "" Then
        If UCase(as_Column) = "FIELD_ORDER" Then
          'If lo_FieldDef.Field_selected <> "" Then
            lst_Sorting.AddItem (lo_FieldDef.Out_Business_Name)
            lst_Sorting.ItemData(lst_Sorting.NewIndex) = lo_FieldDef.Out_Field_ID
          'End If
        ElseIf UCase(as_Column) = "REPORT_ORDER" Then
          If (lo_FieldDef.Report_Order > 0) Then
            lst_Sorting.AddItem (lo_FieldDef.Out_Business_Name)
            lst_Sorting.ItemData(lst_Sorting.NewIndex) = lo_FieldDef.Out_Field_ID
          End If
        End If
      End If
    Next
    Set mo_CurFieldDef = Nothing
    Set mo_CurParentFieldDef = Nothing
    frm_Sorting.Caption = GetVisibleGrid.Columns(as_Column).Title
    frm_Sorting.Tag = as_Column
    Call EnableReportControl(False, frm_Sorting)
    EditOrder = True
  End If
End Function

Private Function UpdateComboList(ao_Combo As ArmCombobox, as_Operators As String, as_Separator As String) As Boolean
Dim lv_List As Variant
Dim ll_Index As Long

  UpdateComboList = False
  Call ao_Combo.Clear
  Call ao_Combo.AddItem(Array("", ""), True)
  If as_Operators <> "" Then
    lv_List = Split(as_Operators, as_Separator)
    For ll_Index = 0 To UBound(lv_List)
      Call ao_Combo.AddItem(Array(lv_List(ll_Index), lv_List(ll_Index)))
    Next
    UpdateComboList = True
  End If
End Function

Private Function SelectCombo(ao_Combo As ArmCombobox, as_Text As String, Optional ab_ClearIfNotFound As Boolean = False) As Boolean
Dim ll_Index As Long
  
  SelectCombo = False
  If ab_ClearIfNotFound Then Set ao_Combo.SelectedItem = Nothing
  If as_Text <> "" Then
    If ao_Combo.SearchItem(as_Text, , , False) Then
      SelectCombo = ao_Combo.SearchItem(as_Text)
    End If
  End If
End Function

Private Sub UpdateCheckedItems(ao_Listview As ListView, ao_Text As TextBox)
Dim lv_CheckedNames As Variant
  
  lv_CheckedNames = GetCheckedNames(ao_Listview)
  If IsArray(lv_CheckedNames) Then
    ao_Text.Text = Join(lv_CheckedNames, ";")
  Else
    ao_Text.Text = ""
  End If
End Sub

Private Function ReplaceSQLClause(as_Clause As String, as_Field As String, lv_Val1 As Variant, lv_Val2 As Variant, as_Type As String)
Dim ls_SQL_Clause As String
  
  ls_SQL_Clause = Replace(as_Clause, "$FIELD$", as_Field, , , vbTextCompare)
  Select Case UCase(as_Type)
  Case "CHAR"
    ls_SQL_Clause = Replace(ls_SQL_Clause, "$VAL1$", SQLStr(lv_Val1), , , vbTextCompare)
    ls_SQL_Clause = Replace(ls_SQL_Clause, "$VAL2$", SQLStr(lv_Val2), , , vbTextCompare)
  Case "NUMERIC"
    If isNumeric(lv_Val1) Then
      ls_SQL_Clause = Replace(ls_SQL_Clause, "$VAL1$", SQLDouble(lv_Val1), , , vbTextCompare)
    End If
    If isNumeric(lv_Val2) Then
      ls_SQL_Clause = Replace(ls_SQL_Clause, "$VAL2$", SQLDouble(lv_Val2), , , vbTextCompare)
    End If
  Case "DATE"
    ls_SQL_Clause = Replace(ls_SQL_Clause, "$VAL1$", SqlDate(lv_Val1), , , vbTextCompare)
    ls_SQL_Clause = Replace(ls_SQL_Clause, "$VAL2$", SqlDate(lv_Val2), , , vbTextCompare)
  Case Else
    ls_SQL_Clause = ""
  End Select
  ReplaceSQLClause = ls_SQL_Clause
End Function

Function CheckListViewArray(ao_Listview As ListView, av_Checked As Variant)
Dim lo_ListItem As ListItem
Dim ll_Index As Long

  If IsArray(av_Checked) Then
    For ll_Index = 0 To UBound(av_Checked)
      For Each lo_ListItem In ao_Listview.ListItems
        If StrComp(lo_ListItem.Tag, av_Checked(ll_Index), vbTextCompare) = 0 Then
          lo_ListItem.Checked = True
          Exit For
        End If
      Next
    Next
  End If
End Function

Private Function FillListViewArray(ao_Listview As ListView, av_Code As Variant, av_Text As Variant, av_Checked As Variant, av_UnLocked As Variant) As Boolean
Dim ll_Index As Long
Dim ll_ItemIndex As Long
Dim lo_ListItem As ListItem
Dim lb_Checked As Boolean
Dim lb_Locked As Boolean

On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  ao_Listview.ListItems.Clear
  For ll_Index = 0 To UBound(av_Code)
    lb_Checked = False
    If IsArray(av_Checked) Then
      For ll_ItemIndex = 0 To UBound(av_Checked)
        If StrComp(av_Code(ll_Index), av_Checked(ll_ItemIndex), vbTextCompare) = 0 Then
          lb_Checked = True
          Exit For
        End If
      Next
    End If
    lb_Locked = False
    If IsArray(av_UnLocked) Then
      lb_Locked = True
      For ll_ItemIndex = 0 To UBound(av_UnLocked)
        If StrComp(av_Code(ll_Index), av_UnLocked(ll_ItemIndex), vbTextCompare) = 0 Then
          lb_Locked = False
          Exit For
        End If
      Next
    End If
    If Not lb_Locked Then
      Set lo_ListItem = ao_Listview.ListItems.Add(, , av_Text(ll_Index))
      lo_ListItem.Checked = lb_Checked
      lo_ListItem.Tag = av_Code(ll_Index)
    End If
  Next
  
  Call SetMousePointer(True)
  FillListViewArray = True
  Exit Function
ErrorHandler:
  Call SetMousePointer(True)
  FillListViewArray = False
End Function

Private Function FillListViewCursor(ao_Listview As ListView, al_cursor As Long, av_Checked As Variant, av_UnLocked As Variant) As Boolean
Dim ll_Index As Long
Dim ll_ItemIndex As Long
Dim lo_ListItem As ListItem
Dim lb_Checked As Boolean
Dim lb_Locked As Boolean
Dim lv_Key As Variant

On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  ao_Listview.ListItems.Clear
  For ll_Index = 0 To mo_Db.RowCount(al_cursor) - 1
    lb_Checked = False
    lv_Key = mo_Db.GetFieldsAt(al_cursor, ll_Index, 0)
    If IsArray(av_Checked) Then
      For ll_ItemIndex = 0 To UBound(av_Checked)
        If StrComp(lv_Key, av_Checked(ll_ItemIndex), vbTextCompare) = 0 Then
          lb_Checked = True
          Exit For
        End If
      Next
    End If
    lb_Locked = False
    If IsArray(av_UnLocked) Then
      lb_Locked = True
      For ll_ItemIndex = 0 To UBound(av_UnLocked)
        If StrComp(lv_Key, av_UnLocked(ll_ItemIndex), vbTextCompare) = 0 Then
          lb_Locked = False
          Exit For
        End If
      Next
    End If
    If Not lb_Locked Then
      Set lo_ListItem = ao_Listview.ListItems.Add(, , Trim(mo_Db.GetFieldsAt(al_cursor, ll_Index, 1)))
      lo_ListItem.Checked = lb_Checked
      lo_ListItem.Tag = lv_Key
    End If
  Next
  
  Call SetMousePointer(True)
  FillListViewCursor = True
  Exit Function
ErrorHandler:
  Call SetMousePointer(True)
  FillListViewCursor = False
End Function

Private Function RefreshGrid(ao_Template As ArmRptTemplate, ao_Grid As ArmGrid, Optional ab_DisplayHidden As Boolean = False) As Boolean
Dim lo_FieldDef As ArmFieldDef
Dim ll_SaveCol As Long
Dim ll_SaveRow As Long
Dim ll_Rows As Long, ll_Index As Long

On Error GoTo ErrorHandler

  RefreshGrid = False
  Call SetMousePointer(False)
  ao_Grid.Redraw = False
  ll_SaveCol = ao_Grid.Col
  ll_SaveRow = ao_Grid.Row
  ao_Grid.Title = ao_Template.Rpt_Tpl_Name
  'first count number of fields in template (its faster than adding the rows one by one)
  ll_Rows = 0
  For Each lo_FieldDef In ao_Template.Fields
    If lo_FieldDef.SQL_Flag <> "D" Then
      If (lo_FieldDef.Out_Hidden = "") Or ab_DisplayHidden Then
        ll_Rows = ll_Rows + 1
      End If
    End If
  Next
  'set number of rows in template
  If ao_Grid.Rows <> ll_Rows Then ao_Grid.Rows = ll_Rows
  'fill the template grid
  ll_Index = 0
  For Each lo_FieldDef In ao_Template.Fields
    If lo_FieldDef.SQL_Flag <> "D" Then
      If (lo_FieldDef.Out_Hidden = "") Or ab_DisplayHidden Then
        ao_Grid.Data(ll_Index, "out_field_id") = lo_FieldDef.Out_Field_ID
        Call UpdateGridRow(ao_Grid, lo_FieldDef)
        If lo_FieldDef.Out_Hidden <> "" Then
          ao_Grid.LineColor(ll_Index) = COLOR_HIDDEN
        End If
        ll_Index = ll_Index + 1
      End If
    End If
  Next
  ao_Grid.Col = ll_SaveCol
  ao_Grid.Row = ll_SaveRow
  ao_Grid.Redraw = True
  Call SetMousePointer(True)
  RefreshGrid = True
  Exit Function
ErrorHandler:
  RefreshGrid = False
  ao_Grid.Redraw = True
  Call SetMousePointer(True)
End Function

Private Function UpdateGridRow(ao_Grid As ArmGrid, ao_FieldDef As ArmFieldDef) As Boolean
  
On Error GoTo ErrorHandler
  UpdateGridRow = False
  ao_Grid.Redraw = False
  If ao_Grid.SearchKey(True, ao_FieldDef.Out_Field_ID) Then
    ao_Grid.SelectedLine(0, "Field_selected") = IIf(ao_FieldDef.Field_selected = "", "UNCHECK", "CHECK")
    ao_Grid.SelectedLine(0, "Field_Order") = ao_FieldDef.Out_Business_Name
    ao_Grid.SelectedLine(0, "Info_Displayed_To_User") = ao_FieldDef.Info_Displayed_To_User
    ao_Grid.SelectedLine(0, "Group_By") = IIf(ao_FieldDef.Out_Can_Be_Group_By = "", "", IIf(ao_FieldDef.Group_By = "", "UNCHECK", "CHECK"))
    ao_Grid.SelectedLine(0, "Total_Visible") = IIf(ao_FieldDef.Out_Can_Be_Group_By = "", "", IIf(ao_FieldDef.Total_Visible = "", "UNCHECK", "CHECK"))
    ao_Grid.SelectedLine(0, "Field_sorted") = UCase(ao_FieldDef.Field_sorted)
    ao_Grid.SelectedLine(0, "Measure") = IIf(ao_FieldDef.Out_Can_Be_Measure = "", ao_FieldDef.Measure, IIf(ao_FieldDef.Measure = "", "-", ao_FieldDef.Measure))
    ao_Grid.SelectedLine(0, "Report_Order") = IIf(ao_FieldDef.Report_Order = 0, "", ao_FieldDef.Report_Order)
    ao_Grid.SelectedLine(0, "Locked") = IIf(ao_FieldDef.Locked = "X", "LOCK", IIf(ao_FieldDef.Locked = "P", "KEY", ""))
    ao_Grid.SelectedLine(0, "Group_By_Weight") = ao_FieldDef.Group_By_Weight
    ao_Grid.SelectedLine(0, "out_field_name") = ao_FieldDef.Out_Field_Name
    ao_Grid.SelectedLine(0, "out_come_from_table") = ao_FieldDef.Out_Come_From_Table
    ao_Grid.SelectedLine(0, "Out_Field_Prefix") = ao_FieldDef.Out_Field_Prefix
    ao_Grid.SelectedLine(0, "Out_Master_Table") = ao_FieldDef.Out_Master_Table
    ao_Grid.SelectedLine(0, "Out_Master_Table_Prefix") = ao_FieldDef.Out_Master_Table_Prefix
    ao_Grid.SelectedLine(0, "out_business_name") = ao_FieldDef.Out_Business_Name
    ao_Grid.SelectedLine(0, "out_hidden") = ao_FieldDef.Out_Hidden
    ao_Grid.SelectedLine(0, "join_type") = IIf(ao_FieldDef.Out_Can_Change_join = "", "", IIf(ao_FieldDef.Join_Type = "L", "UNCHECK", IIf(ao_FieldDef.Join_Type = "I", "CHECK", "GRAYED")))
    UpdateGridRow = True
  End If
  ao_Grid.Redraw = True
  Exit Function
ErrorHandler:
  ao_Grid.Redraw = True
  UpdateGridRow = False
End Function

Private Function FillGridRequest(av_Request As Variant, ao_Grid As ArmGrid, ao_Template As ArmRptTemplate) As Boolean

On Error GoTo ErrorHandler
  Call ao_Grid.SetColumns(ao_Template.GetGridSetColumnArray)
  ao_Grid.RemoveRepeatValue = ao_Template.RepeatLines
  ao_Grid.ShowGrandTotal = ao_Template.GrandTotal
  ao_Grid.TotalRowColor = RGB(245, 220, 220)
  ao_Grid.ExportOnlyVisibleColumns = True
  FillGridRequest = ao_Grid.Load(av_Request, True)
  Exit Function
ErrorHandler:
  FillGridRequest = False
End Function

Private Function GetCheckedCodes(ao_Listview As ListView) As Variant
Dim ll_Count As Long
Dim ll_Index As Long
Dim lo_ListItem As ListItem
Dim lv_Codes As Variant

  lv_Codes = Empty
  ll_Count = 0
  For Each lo_ListItem In ao_Listview.ListItems
    If lo_ListItem.Checked Then ll_Count = ll_Count + 1
  Next
  If ll_Count > 0 Then
    ReDim lv_Codes(ll_Count - 1)
    ll_Index = 0
    For Each lo_ListItem In ao_Listview.ListItems
      If lo_ListItem.Checked Then
        lv_Codes(ll_Index) = lo_ListItem.Tag
        ll_Index = ll_Index + 1
      End If
    Next
  End If
  GetCheckedCodes = lv_Codes
End Function

Private Function GetCheckedNames(ao_Listview As ListView) As Variant
Dim ll_Count As Long
Dim ll_Index As Long
Dim lo_ListItem As ListItem
Dim lv_Names As Variant

  lv_Names = Empty
  ll_Count = 0
  For Each lo_ListItem In ao_Listview.ListItems
    If lo_ListItem.Checked Then ll_Count = ll_Count + 1
  Next
  If ll_Count > 0 Then
    ReDim lv_Names(ll_Count - 1)
    ll_Index = 0
    For Each lo_ListItem In ao_Listview.ListItems
      If lo_ListItem.Checked Then
        lv_Names(ll_Index) = lo_ListItem.Text
        ll_Index = ll_Index + 1
      End If
    Next
  End If
  GetCheckedNames = lv_Names
End Function

Private Function GetDefaultLogic(as_Operator As String) As String

  Select Case as_Operator
  Case "="
    GetDefaultLogic = "OR"
  Case "<>"
    GetDefaultLogic = "AND"
  Case Else
    GetDefaultLogic = ""
  End Select
End Function

Private Function GetSQL_Clause(av_Codes As Variant, ao_field As ArmFieldDef, as_Operator As String, as_Logic As String)
Dim ls_Logic As String
Dim ls_SQL_Clause As String
Dim ll_Index As Long
Dim ls_Crosslink_Request As String

  ls_SQL_Clause = ""
  If IsArray(av_Codes) Then
    ls_Logic = Trim(UCase(as_Logic))
    If as_Logic = "" Then
      ls_Logic = GetDefaultLogic(as_Operator)
    End If
    
    If ls_Logic <> "" Then
      If UBound(av_Codes) > 0 Then
        For ll_Index = 0 To UBound(av_Codes)
          If ls_SQL_Clause <> "" Then ls_SQL_Clause = ls_SQL_Clause & ","
          ls_SQL_Clause = ls_SQL_Clause & SQLStr(av_Codes(ll_Index))
        Next
        ls_SQL_Clause = "(" & ls_SQL_Clause & ")"
        
        If (as_Operator = "=") And (ls_Logic = "OR") Then
          ls_SQL_Clause = ao_field.Out_Full_Field_Code & " IN " & ls_SQL_Clause
        ElseIf (as_Operator = "<>") And (ls_Logic = "AND") Then
          ls_SQL_Clause = ao_field.Out_Full_Field_Code & " NOT IN " & ls_SQL_Clause
        ElseIf (as_Operator = "=") And (ls_Logic = "AND") Then
          If ao_field.Out_Crosslink_Request = "" Then
            Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 26, "#Field template is missing crosslink request")
            ls_SQL_Clause = ""
          Else
            ls_SQL_Clause = Replace(ao_field.Out_Crosslink_Request, "$SET$", ls_SQL_Clause, , , vbTextCompare)
            ls_SQL_Clause = Replace(ls_SQL_Clause, "$LOGIC$", "IN", , , vbTextCompare)
            ls_SQL_Clause = Replace(ls_SQL_Clause, "$HAVING$", "HAVING COUNT(*)=" & CStr(UBound(av_Codes) + 1), , , vbTextCompare)
          End If
        ElseIf (as_Operator = "<>") And (ls_Logic = "OR") Then
          If ao_field.Out_Crosslink_Request = "" Then
            Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 26, "#Field template is missing crosslink request")
            ls_SQL_Clause = ""
          Else
            ls_SQL_Clause = Replace(ao_field.Out_Crosslink_Request, "$SET$", ls_SQL_Clause, , , vbTextCompare)
            ls_SQL_Clause = Replace(ls_SQL_Clause, "$LOGIC$", "NOT IN", , , vbTextCompare)
            ls_SQL_Clause = Replace(ls_SQL_Clause, "$HAVING$", "HAVING COUNT(*)>0", , , vbTextCompare)
          End If
        Else
          Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 27, "#Invalid operator and logic combination.")
          ls_SQL_Clause = ""
        End If
      Else
        ls_SQL_Clause = ao_field.Out_Full_Field_Code & as_Operator & SQLStr(av_Codes(0))
      End If
    End If
  End If
  GetSQL_Clause = ls_SQL_Clause
End Function

Private Function NodeIsVisible(ao_NodeInfo As NodeInfo)

  NodeIsVisible = False
  If (StrComp(ao_NodeInfo.GetData(NODE_OWNER), ms_UserID, vbTextCompare) = 0) Or _
     (ao_NodeInfo.GetData(NODE_RIGHT) > 0) Then
    NodeIsVisible = True
  End If
End Function

Private Function HideNodesWithoutRights(ao_Tree As ArmTreeView, ByVal ao_parentNode As Node) As Boolean
Dim lo_Node As Node
Dim lo_SaveNode As Node
Dim lb_HideNode As Boolean


  If ao_Tree.Count > 0 Then
    If ao_parentNode Is Nothing Then
      Set lo_Node = ao_Tree.Nodes(1)
      lb_HideNode = Not NodeIsVisible(ao_Tree.NodeInfo(lo_Node))
    Else
      lb_HideNode = Not NodeIsVisible(ao_Tree.NodeInfo(ao_parentNode))
      Set lo_Node = ao_parentNode.Child
    End If
    
    
    While Not (lo_Node Is Nothing)
      Set lo_SaveNode = lo_Node.Next
      If HideNodesWithoutRights(ao_Tree, lo_Node) Then
        Call ao_Tree.RemoveNode(lo_Node)
        Set lo_Node = lo_SaveNode
      Else
        lb_HideNode = False
        Set lo_Node = lo_Node.Next
      End If
    Wend
  End If
  HideNodesWithoutRights = lb_HideNode
End Function

Private Sub UpdateTVNode(ao_Node As Node)
Dim lo_NodeInfo As NodeInfo

  Set lo_NodeInfo = tvItem.NodeInfo(ao_Node)
  If Not (lo_NodeInfo Is Nothing) Then
    ao_Node.Image = lo_NodeInfo.GetData(NODE_RIGHT) + 11
    ao_Node.Bold = StrComp(ms_UserID, lo_NodeInfo.GetData(NODE_OWNER), vbTextCompare) = 0
  End If
End Sub

Private Sub UpdateTVNodeData(ao_Node As Node)
Dim lo_item As ArmItemInfo
Dim lb_Inherit As Boolean
Dim lb_Execute As Boolean
  
  If Not (ao_Node Is Nothing) Then
    lb_Execute = False
    lb_Inherit = False
    Set lo_item = cv_Share.RoleList("INHERIT").GetItem(Array(mo_DesignTemplate.Owner))
    If Not (lo_item Is Nothing) Then
      lb_Inherit = lo_item.CurrentChecked
    End If
    Set lo_item = cv_Share.RoleList("EXECUTE").GetItem(Array(mo_DesignTemplate.Owner))
    If Not (lo_item Is Nothing) Then
      lb_Execute = lo_item.CurrentChecked
    End If
    If lb_Inherit Then
      If lb_Execute Then
        Call tvItem.NodeInfo(ao_Node).SetData(NODE_RIGHT, TV_IMAGE_INHERITEXECUTE)
      Else
        Call tvItem.NodeInfo(ao_Node).SetData(NODE_RIGHT, TV_IMAGE_INHERIT)
      End If
    Else
      If lb_Execute Then
        Call tvItem.NodeInfo(ao_Node).SetData(NODE_RIGHT, TV_IMAGE_EXECUTE)
      Else
        Call tvItem.NodeInfo(ao_Node).SetData(NODE_RIGHT, TV_IMAGE_NORIGHT)
      End If
    End If
    Call UpdateTVNode(ao_Node)
  End If
End Sub

Private Function FindReportData(as_Text As String) As Boolean
Dim lb_Found As Boolean
Dim ll_Row As Long
Dim ll_Col As Long
Dim ll_GridIndex As Long
Dim ll_StartRow As Long
Dim ll_StartCol As Long

On Error GoTo ErrorHandler
  lb_Found = False
  Call SetMousePointer(False)
  If as_Text <> "" Then
    ll_GridIndex = ActiveScreenIndex
    ll_StartRow = ml_LastFindRow
    ll_StartCol = ml_LastFindCol
    For ll_Row = ll_StartRow To grdlst(ll_GridIndex).Rows - 1
      For ll_Col = ll_StartCol To grdlst(ll_GridIndex).Cols - 1
        If InStr(1, grdlst(ll_GridIndex).Data(ll_Row, ll_Col), as_Text, vbTextCompare) > 0 Then
          grdlst(ll_GridIndex).Row = ll_Row
          grdlst(ll_GridIndex).Col = ll_Col
          lb_Found = True
          If ll_Col >= (grdlst(ll_GridIndex).Cols - 1) Then
            ml_LastFindCol = 1
            ml_LastFindRow = ll_Row + 1
            If ml_LastFindRow > grdlst(ll_GridIndex).Rows - 1 Then
              ml_LastFindRow = 0
            End If
          Else
            ml_LastFindCol = ll_Col + 1
            ml_LastFindRow = ll_Row
          End If
          Exit For
        End If
      Next
      ll_StartCol = 1
      If lb_Found Then Exit For
    Next
    If Not lb_Found Then
      If (ml_LastFindCol <> 0) Or (ml_LastFindRow <> 0) Then
        'try to search from the begining
        ml_LastFindCol = 1
        ml_LastFindRow = 0
        lb_Found = FindReportData(as_Text)
      Else
        ml_LastFindCol = 1
        ml_LastFindRow = 0
      End If
    End If
  End If
  Call SetMousePointer(True)
  FindReportData = lb_Found
  Exit Function
ErrorHandler:
    Call SetMousePointer(True)
    FindReportData = False
End Function

Private Sub EnableReportControl(ab_Enable As Boolean, ao_Frame As Frame)
Dim ll_GridIndex As Long

  tbsBar.Enabled = ab_Enable
  pbItem.Enabled = ab_Enable
  frm_Design.Enabled = ab_Enable
  frm_Exec.Enabled = ab_Enable
  frm_FieldsTemp.Enabled = ab_Enable
  grdlst(ActiveScreenIndex).Enabled = ab_Enable
  If Not (ao_Frame Is Nothing) Then
    ao_Frame.Visible = Not ab_Enable
  End If
End Sub

Private Function AddReportTab(as_ReportName As String) As Long
Dim lo_Tab As Object

On Error GoTo ErrorHandler
  Set lo_Tab = tbsBar.Tabs.Add(, "G" & ml_GridIndex, as_ReportName)
  Load grdlst(ml_GridIndex)
  Set grdlst(ml_GridIndex).Container = Me
  Call InitReportGrid(grdlst(ml_GridIndex), as_ReportName)
  Set tbsBar.SelectedItem = lo_Tab
  Call UserControl.Refresh
  AddReportTab = ml_GridIndex
  ml_GridIndex = ml_GridIndex + 1
  Exit Function
ErrorHandler:
  AddReportTab = 0
End Function

Private Function GetVisibleGrid() As ArmGrid
Dim ll_Index As Long

  Set GetVisibleGrid = Nothing
  ll_Index = ActiveScreenIndex
  If ll_Index >= 0 Then
    Set GetVisibleGrid = grdlst(ll_Index)
  End If
End Function

Private Property Get ActiveScreenIndex() As Long
    ActiveScreenIndex = GetScreenIndexFromTabIndex(tbsBar.SelectedItem.Index)
End Property

Private Function GetScreenIndexFromTabIndex(al_TabIndex As Long) As Long

  GetScreenIndexFromTabIndex = -1
  If (al_TabIndex >= 1) And (al_TabIndex <= tbsBar.Tabs.Count) Then
    GetScreenIndexFromTabIndex = Val(right(tbsBar.Tabs(al_TabIndex).Key, Len(tbsBar.Tabs(al_TabIndex).Key) - 1))
  End If
End Function

Private Function DeleteTabReport(al_TabIndex As Long) As Boolean
Dim ll_ScreenIndex As Long

  DeleteTabReport = False
  ll_ScreenIndex = GetScreenIndexFromTabIndex(al_TabIndex)
  If ll_ScreenIndex >= scrReport Then
    Call grdlst(ll_ScreenIndex).Unload_A_COM
    Unload grdlst(ll_ScreenIndex)
    Call tbsBar.Tabs.Remove(al_TabIndex)
    Set tbsBar.SelectedItem = tbsBar.Tabs(1)
    DeleteTabReport = True
  End If
End Function

Private Function ExecuteNewReport(as_Language As String) As Boolean
Dim ls_SQL As String
Dim ll_Cursor As Long
Dim ll_Index As Long
Dim ll_GridIndex As Long
Dim ll_codePage As Long
Dim ls_language As String
Dim ls_ReportName As String
Dim lt_Rpt_Log As Rpt_Log
Dim lb_Result As Boolean
Dim ls_sumPercGainCol As String

On Error GoTo ErrorHandler
  lb_Result = False
  Call SetMousePointer(False)
  ls_ReportName = mo_ExecTemplate.Rpt_Tpl_Name & " (" & pbItem.Language & ")"
  ls_ReportName = Trim(InputBox("Name: ", mo_ExecTemplate.Rpt_Tpl_Name, ls_ReportName))
  If ls_ReportName <> "" Then
    ll_GridIndex = -1
    For ll_Index = 1 To tbsBar.Tabs.Count
      If (CStr(tbsBar.Tabs(ll_Index).Tag) = "") And (StrComp(ls_ReportName, tbsBar.Tabs(ll_Index).Caption, vbTextCompare) = 0) Then
        If ASC_SendMessage(ms_Language, RPT_ERR_MSG + 23, "#Report of this name already exists, do you wish to replace?", , vbYesNo) = vbYes Then
          Set tbsBar.SelectedItem = tbsBar.Tabs(ll_Index)
          ll_GridIndex = GetScreenIndexFromTabIndex(ll_Index)
          Call UserControl.Refresh
        End If
        Exit For
      End If
    Next
    
    If ll_GridIndex < 0 Then
      ll_GridIndex = AddReportTab(ls_ReportName)
    End If
    
    If ll_GridIndex > 0 Then
      grdlst(ll_GridIndex).Font.Name = "Arial"
      ll_codePage = GetCodePage(as_Language)
      grdlst(ll_GridIndex).Font.Charset = GetCharSet(ll_codePage)
      grdlst(ll_GridIndex).LocalID = GetLCIDFromCodePage(ll_codePage)
      grdlst(ll_GridIndex).Codepage = ll_codePage
      
      mo_ExecTemplate.RepeatLines = chk_RepeatLines.Value = vbChecked
      mo_ExecTemplate.GrandTotal = chk_GrandTotal.Value = vbChecked
      
      ls_SQL = mo_ExecTemplate.GenerateSQL(chk_Distinct.Value = vbChecked)
      
      'TODO: remove in live version - save query to text file
      'Open App.Path & "\SQL.TXT" For Output Access Write As #1
      '  Print #1, ls_ReportName
      '  Print #1,
      '  Print #1, ls_SQL
      '  Print #1,
      'Close #1
      
      ls_language = pbItem.Language
      ls_SQL = Replace(ls_SQL, "$Lang$", "'" & ls_language & "'")
      ls_SQL = Replace(ls_SQL, "$UID$", "'" & ms_UserID & "'")
      
      lt_Rpt_Log.rpt_language = ls_language
      lt_Rpt_Log.rpt_sql = ls_SQL
      lt_Rpt_Log.rpt_success = "N"
      lt_Rpt_Log.rpt_tpl_list_ID = mo_ExecTemplate.Rpt_Tpl_ID
      lt_Rpt_Log.Rpt_Tpl_Name = mo_ExecTemplate.Rpt_Tpl_Name
      lt_Rpt_Log.rpt_userID = ms_UserID
      lt_Rpt_Log.rpt_time = timer
      
      lb_Result = FillGridRequest(ls_SQL, grdlst(ll_GridIndex), mo_ExecTemplate)
      grdlst(ll_GridIndex).TagVariant = mo_ExecTemplate.Generate_Criteria_List
      lt_Rpt_Log.rpt_time = timer - lt_Rpt_Log.rpt_time
      ls_sumPercGainCol = mo_ExecTemplate.GetMeasureCol("SUMPERCGAIN")
      If ls_sumPercGainCol <> "" Then
        Call CalculateSumPercGain(grdlst(ll_GridIndex), ls_sumPercGainCol, mo_ExecTemplate.GrandTotal, mo_ExecTemplate.RepeatLines)
      End If
      If lb_Result Then
        lt_Rpt_Log.rpt_success = "Y"
      Else
        Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 16, "#Error executing SQL query")
      End If
      
      Call ReportLog(lt_Rpt_Log)
    End If
  End If
  Call SetMousePointer(True)
  ExecuteNewReport = lb_Result
  Exit Function
ErrorHandler:
  Call SetMousePointer(True)
  ExecuteNewReport = False
End Function

Private Function CalculateSumPercGain(ByVal ao_Grid As ArmGrid, ByVal as_sumPercGainCol As String, ByVal ab_GrandTotal As Boolean, ByVal ab_RemoveRepeat As Boolean) As Boolean
Dim ll_RowIndex As Long
Dim ll_ColumnIndex As Long, ll_GroupIndex As Long
Dim ll_GroupCount As Long
Dim lv_SumPercGain() As Double, lv_SumPrice1() As Double, lv_SumTotalGain() As Double
Dim lo_PercGainCol As ArmColumn
Dim lo_Price1Col As ArmColumn
Dim lo_TotalGainCol As ArmColumn

On Error GoTo ErrorHandler
  
  CalculateSumPercGain = False
  
  Set lo_PercGainCol = ao_Grid.Columns(as_sumPercGainCol)
  If lo_PercGainCol Is Nothing Then
    ' column for percent gain not in report, we don't need to do custom calculation
    CalculateSumPercGain = True
    Exit Function
  End If
  
  If lo_PercGainCol.Measure <> MEASURE_UNKNOWN Then
    ' column for percent gain has not custom measure set, we don't need to do custom calculation
    CalculateSumPercGain = True
    Exit Function
  End If
  
  'Set lo_Price1Col = ao_Grid.Columns("SUM(BDGEXCH_rate*SASR.SASR_Sales_1*(1-@p1_GtoNPerc))") 'mw 1.8.2008
  Set lo_Price1Col = ao_Grid.Columns("SUM(SASR_Sales_1USD)") 'mw 27.10.2008
  If lo_Price1Col Is Nothing Then
    'Set lo_Price1Col = ao_Grid.Columns("BDGEXCH_rate*SASR.SASR_Sales_1*(1-@p1_GtoNPerc)") 'mw 1.8.2008
    Set lo_Price1Col = ao_Grid.Columns("SASR_Sales_1USD") 'mw 27.10.2008
  End If
  If lo_Price1Col Is Nothing Then
    Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 29, "#To calculate summary for field Percent Gain, fields 'Absolut gain (USD)' and 'Total price 1 USD' must be visible in report.")
    Exit Function
  End If
  
  'Set lo_TotalGainCol = ao_Grid.Columns("SUM(BDGEXCH_rate*SASR_Absolute_Gain)") mw 4.8.2008
  'Set lo_TotalGainCol = ao_Grid.Columns("SUM(BDGEXCH_rate*((SASR_Sales_1*(1-@p1_GtoNPerc)/SASR_Qty_For_Cubes_1)-(SASR_Sales_2*(1-@p2_GtoNPerc)/SASR_Qty_For_Cubes_2))*SASR_Qty_For_Cubes_1)")
  Set lo_TotalGainCol = ao_Grid.Columns("SUM(SASR_Absolute_Gain_Dollars)") 'mw 27.10.2008
  If lo_TotalGainCol Is Nothing Then
    ' Set lo_TotalGainCol = ao_Grid.Columns("BDGEXCH_rate*SASR_Absolute_Gain") mw 4.9.2008
    ' Set lo_TotalGainCol = ao_Grid.Columns("BDGEXCH_rate*((SASR_Sales_1*(1-@p1_GtoNPerc)/SASR_Qty_For_Cubes_1)-(SASR_Sales_2*(1-@p2_GtoNPerc)/SASR_Qty_For_Cubes_2))*SASR_Qty_For_Cubes_1")
    Set lo_TotalGainCol = ao_Grid.Columns("SASR_Absolute_Gain_Dollars") 'mw 27.10.2008
  End If
  If lo_TotalGainCol Is Nothing Then
    Call ASC_SendMessage(ms_Language, RPT_ERR_MSG + 29, "#To calculate summary for field Percent Gain, fields 'Absolut gain (USD)' and 'Total price 1 USD' must be visible in report.")
    Exit Function
  End If
  
  ll_GroupCount = 0
  For ll_ColumnIndex = 0 To ao_Grid.Cols - 1
    If ao_Grid.Columns(ll_ColumnIndex).Group Then ll_GroupCount = ll_GroupCount + 1
  Next
  
  If (ll_GroupCount = 0) And (Not ab_GrandTotal) Then
    'it has not sense calulate measure as there is no group column or grand total
    Exit Function
  End If
  'element 0 is always summary for grand total (even grand total not displayed in grid)
  ReDim lv_SumPercGain(ll_GroupCount)
  ReDim lv_SumPrice1(ll_GroupCount)
  ReDim lv_SumTotalGain(ll_GroupCount)
  For ll_GroupIndex = 0 To ll_GroupCount
    lv_SumPercGain(ll_GroupIndex) = 0
    lv_SumPrice1(ll_GroupIndex) = 0
    lv_SumTotalGain(ll_GroupIndex) = 0
  Next
  
  'stop refreshing grid
  ao_Grid.Redraw = False
  For ll_RowIndex = 0 To ao_Grid.Rows - 1
    ll_GroupIndex = ao_Grid.RowData(ll_RowIndex)
    If ll_GroupIndex = 0 Then
      For ll_ColumnIndex = 0 To ll_GroupCount
        lv_SumPercGain(ll_ColumnIndex) = lv_SumPercGain(ll_ColumnIndex) + lo_PercGainCol.GetData(ll_RowIndex)
        lv_SumPrice1(ll_ColumnIndex) = lv_SumPrice1(ll_ColumnIndex) + lo_Price1Col.GetData(ll_RowIndex)
        lv_SumTotalGain(ll_ColumnIndex) = lv_SumTotalGain(ll_ColumnIndex) + lo_TotalGainCol.GetData(ll_RowIndex)
      Next
    ElseIf ll_GroupIndex > 0 Then
      'calculate subtotal measure and fill grid cell
      If (lv_SumPrice1(0) - lv_SumTotalGain(0)) = 0 Then
        Call lo_PercGainCol.SetData(ll_RowIndex, 0)
      Else
        Call lo_PercGainCol.SetData(ll_RowIndex, lv_SumTotalGain(ll_GroupIndex) / (lv_SumPrice1(ll_GroupIndex) - lv_SumTotalGain(ll_GroupIndex)))
      End If
      'reset subtotal measure summary for group level
      lv_SumPercGain(ll_GroupIndex) = 0
      lv_SumPrice1(ll_GroupIndex) = 0
      lv_SumTotalGain(ll_GroupIndex) = 0
    Else
      ' calculate grand total measure
      If (lv_SumPrice1(0) - lv_SumTotalGain(0)) = 0 Then
        Call lo_PercGainCol.SetData(ll_RowIndex, 0)
      Else
        Call lo_PercGainCol.SetData(ll_RowIndex, lv_SumTotalGain(0) / (lv_SumPrice1(0) - lv_SumTotalGain(0)))
      End If
    End If
  Next
  ao_Grid.Redraw = True
  CalculateSumPercGain = True
  Exit Function
ErrorHandler:
  ao_Grid.Redraw = True
  CalculateSumPercGain = False
End Function


Private Function LoadOperators() As Boolean
Dim ll_Index As Long
Dim ll_Cursor As Long

  LoadOperators = False
  ReDim ma_Operators(0)
  ll_Cursor = OpenCursor("exec rpt_operator_sel")
  If (ll_Cursor <> 0) Then
    If mo_Db.RowCount(ll_Cursor) > 0 Then
      ReDim ma_Operators(mo_Db.RowCount(ll_Cursor) - 1)
      For ll_Index = 0 To mo_Db.RowCount(ll_Cursor) - 1
        ma_Operators(ll_Index).rpt_Operator = mo_Db.GetFieldsAt(ll_Cursor, ll_Index, "rpt_Operator")
        ma_Operators(ll_Index).rpt_Operand_Count = mo_Db.GetFieldsAt(ll_Cursor, ll_Index, "rpt_Operand_Count")
        ma_Operators(ll_Index).rpt_Operator_Clause = mo_Db.GetFieldsAt(ll_Cursor, ll_Index, "rpt_Operator_Clause")
        ma_Operators(ll_Index).rpt_Operator_Clause_Display = mo_Db.GetFieldsAt(ll_Cursor, ll_Index, "rpt_Operator_Clause_Display")
      Next
      LoadOperators = True
    End If
    Call CloseCursor(ll_Cursor)
  End If
End Function

Private Function GetOperator(as_Operator As String) As rpt_Operator
Dim lt_Operator As rpt_Operator
Dim ll_Index As Long

  lt_Operator.rpt_Operator = ""
  lt_Operator.rpt_Operand_Count = 0
  lt_Operator.rpt_Operator_Clause = ""
  For ll_Index = 0 To UBound(ma_Operators)
    If StrComp(as_Operator, ma_Operators(ll_Index).rpt_Operator, vbTextCompare) = 0 Then
      lt_Operator = ma_Operators(ll_Index)
      Exit For
    End If
  Next
  GetOperator = lt_Operator
End Function

Private Function ReportLog(at_rpt_Log As Rpt_Log) As Boolean
Dim ls_SQL As String

  ls_SQL = "exec rpt_log_ins " & _
    SqlLong(at_rpt_Log.rpt_tpl_list_ID) & "," & _
    SQLStr(at_rpt_Log.Rpt_Tpl_Name) & "," & _
    SQLStr(at_rpt_Log.rpt_userID) & "," & _
    SQLStr(at_rpt_Log.rpt_language) & "," & _
    SQLStr(at_rpt_Log.rpt_sql) & "," & _
    SqlTime(at_rpt_Log.rpt_time) & "," & _
    SQLStr(at_rpt_Log.rpt_success)
    
  Call SetMousePointer(False)
  ReportLog = mo_Db.ExecuteSQL(ls_SQL)
  Call SetMousePointer(True)
End Function

Public Function SQLStr(ByVal as_str As String) As String
    
  SQLStr = "'" & Replace(as_str, "'", "''") & "'"
End Function

Public Function SqlDate(ByVal as_Date As String) As String
    
  SqlDate = "'" & Format$(as_Date, "YYYY-MM-DD") & "'"
End Function

Public Function SqlTime(ByVal ad_Seconds As Double) As String
Dim ll_Hours As Long
Dim ll_Minutes As Long
Dim ll_Seconds As Long
  
  ll_Seconds = ad_Seconds
  ll_Hours = ll_Seconds \ 3600
  ll_Minutes = (ll_Seconds - (ll_Hours * 3600)) \ 60
  ll_Seconds = ll_Seconds Mod 60
  SqlTime = "'" & Format(ll_Hours, "00") & ":" & Format(ll_Minutes, "00") & ":" & Format(ll_Seconds, "00") & "'"
End Function

Public Function SqlLong(ByVal as_Long As String) As String
    
    SqlLong = Val(as_Long)
End Function

Public Function SQLDouble(ByVal ad_Double As Double) As String
  SQLDouble = Str(ad_Double)
End Function

Private Function ReplaceSQLPLaceholders(ByVal as_Sql As String) As String
  
  as_Sql = Replace(as_Sql, "$Lang$", SQLStr(ms_Language), , , vbTextCompare)
  as_Sql = Replace(as_Sql, "$UID$", SQLStr(ms_UserID), , , vbTextCompare)
  ReplaceSQLPLaceholders = as_Sql
End Function

'turn off on mouse pointer sand hour glass, use counter
Private Static Sub SetMousePointer(lb_Enable As Boolean)
Dim li_Count As Integer
Dim li_OldPointer As Integer

  If lb_Enable Then
    If li_Count > 0 Then li_Count = li_Count - 1
    If li_Count <= 0 Then
      'set back old state
      Screen.MousePointer = li_OldPointer
    End If
  Else
    li_Count = li_Count + 1
    'remember state of pointer before first change
    If li_Count = 1 Then li_OldPointer = Screen.MousePointer
    Screen.MousePointer = vbHourglass
  End If
End Sub

Private Sub ClearCollection(lo_Collection As Collection)

  If Not (lo_Collection Is Nothing) Then
    While lo_Collection.Count > 0
      Call lo_Collection.Remove(1)
    Wend
  End If
End Sub

Private Function OpenConnection(as_Server As String, as_Db As String, as_User As String, _
    as_Pwd As String, as_App As String) As Boolean
Dim lb_Result As Boolean

On Error GoTo ErrorHandler
  If IsConnected Then
    lb_Result = False
  Else
    mb_InternalConnection = True
    If mo_Db Is Nothing Then
      Set ArmDb = New ARMSYSCOMLib.ArmDb
    End If

    If (as_Server <> "") And (as_Db <> "") And (as_User <> "") Then
        lb_Result = mo_Db.Connect(as_Server, as_Db, as_User, as_Pwd, as_App)
    End If
  End If
  OpenConnection = lb_Result
  Exit Function
ErrorHandler:
  OpenConnection = False
End Function

Private Sub CloseConnection()

  If IsConnected Then
    Call mo_Db.Disconnect
    mb_InternalConnection = False
  End If
End Sub

Private Function OpenCursor(as_Request As String) As Long
  
On Error GoTo ErrorHandler
  
  Call SetMousePointer(False)
  OpenCursor = 0
  If Not IsConnected Then
    If Not OpenConnection(ms_Server, ms_Db, ms_User, ms_Pwd, ms_App) Then
      GoTo ErrorHandler
    End If
  End If
  OpenCursor = mo_Db.OpenSQL(as_Request)
  Call SetMousePointer(True)
  Exit Function
ErrorHandler:
  Call SetMousePointer(True)
End Function

Private Function CloseCursor(ByRef al_cursor As Long) As Boolean

  CloseCursor = False
  If al_cursor Then
    CloseCursor = mo_Db.Close(al_cursor)
    al_cursor = 0
  End If
End Function

' Get an error message
Private Function ASC_MsgText(ByVal as_LG_Code As String, ByVal ai_MsgID As Integer, Optional ByVal as_MsgDefault As String = "")
Dim lc_Msg As Long
Dim ls_Msg As String, ls_Request As String

    On Error GoTo Trace_Err
   
    ls_Request = "SELECT Message_Text FROM Error_Message WHERE Language_Code = '" & as_LG_Code & "' AND MsgID = " & ai_MsgID
    lc_Msg = OpenCursor(ls_Request)
    If lc_Msg = 0 Then
        GoTo Trace_End
    End If
    
    ls_Msg = mo_Db.GetFields(lc_Msg, "MESSAGE_TEXT")
    
Trace_End:
    Call CloseCursor(lc_Msg)
    ASC_MsgText = IIf(Len(ls_Msg) <> 0, ls_Msg, as_MsgDefault)
    Exit Function
    
Trace_Err:
    ASC_MsgText = ""
    Call mo_Db.Close(lc_Msg)
End Function

' Display an error message
Public Function ASC_SendMessage(ByVal as_LG_Code As String, ByVal ai_MsgCode As Integer, ByVal as_MsgDefault As String, Optional ByVal as_MsgCxt As String = "", Optional Buttons As VbMsgBoxStyle = vbOKOnly) As VbMsgBoxResult
Dim ls_Message As String
Dim ll_Mouse As Long

    On Error GoTo Trace_Err
    
    If mo_Db Is Nothing Then
        ls_Message = as_MsgDefault
    Else
        If mo_Db.IsConnected = False Then
            ls_Message = as_MsgDefault
        Else
            ls_Message = ASC_MsgText(as_LG_Code, ai_MsgCode, as_MsgDefault)
        End If
    End If
    ls_Message = ls_Message & vbCrLf & Trim(as_MsgCxt)
    ll_Mouse = Screen.MousePointer
    Screen.MousePointer = vbArrow
    ASC_SendMessage = MsgBox(ls_Message, Buttons)
    Screen.MousePointer = ll_Mouse
Trace_End:
    Exit Function
    
Trace_Err:
    ASC_SendMessage = vbAbort
End Function

' Load the labels of a containers
Private Sub LoadLabels(ByRef ao_Armdb As ArmDb, ByRef ao_Container As Object, ByVal as_ScreenName As String, ByVal as_Language As String)
Dim lc_Labels As Long       ' The cursor of the labels
Dim lc_Control As Control   ' A control of the container
Dim li_Idx As Integer, li_Count As Integer
Dim li_Label As Integer      ' A label idx
Dim ls_Request As String
    
    On Error GoTo Trace_Err
    Call SetMousePointer(False)
    
    ls_Request = "exec Screen_Csts '" & as_ScreenName & "','" & as_Language & "'"
    lc_Labels = ao_Armdb.OpenSQL(ls_Request, -1)
    
    If lc_Labels = 0 Then
        GoTo Trace_End
    End If
    
    If ao_Armdb.Find(lc_Labels, "FIELD_NAME", "GrandTotal", , 1) >= 0 Then
      ms_TextGrandTotal = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
    End If
    If ao_Armdb.Find(lc_Labels, "FIELD_NAME", "SubTotal", , 1) >= 0 Then
      ms_TextSubTotal = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
    End If
    
    On Error GoTo WithoutTag
    If ao_Container.Tag <> "" Then
        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", ao_Container.Tag, , 1)
        If li_Label >= 0 Then
            ao_Container.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
        End If
    End If
WithoutTag:
    
    On Error GoTo Trace_Err
    
    ' Iterate the container for loading the label of each element which has defined a tag
    For Each lc_Control In ao_Container
        Select Case UCase(TypeName(lc_Control))
            Case UCase("TabStrip") ' Component is a tabstrip, we load the caption of each tab defined
                Dim lo_Tbs As MSComctlLib.TabStrip
                Set lo_Tbs = lc_Control ' Cast for use of intellisense
                li_Count = lo_Tbs.Tabs.Count
                For li_Idx = 1 To li_Count
                    If lo_Tbs.Tabs(li_Idx).Tag <> "" Then
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_Tbs.Tabs(li_Idx).Tag, , 1)
                        If li_Label >= 0 Then
                            lo_Tbs.Tabs(li_Idx).Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                Next
                Set lo_Tbs = Nothing
            
            Case UCase("ListView") ' Component is a listview, we load the caption of each columns
                Dim lo_ListView As ListView
                Set lo_ListView = lc_Control
                li_Count = lo_ListView.ColumnHeaders.Count
                For li_Idx = 1 To li_Count
                    If lo_ListView.ColumnHeaders(li_Idx).Tag <> "" Then
                        li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_ListView.ColumnHeaders(li_Idx).Tag, , 1)
                        If li_Label >= 0 Then
                            lo_ListView.ColumnHeaders(li_Idx).Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                        End If
                    End If
                Next
                Set lo_ListView = Nothing
        
            Case UCase("TextBox")  ' Component is a textbox
                Dim lo_TextBox As TextBox
                Set lo_TextBox = lc_Control
                If lo_TextBox.Tag <> "" Then
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lo_TextBox.Tag, , 1)
                    If li_Label >= 0 Then
                        lo_TextBox.Text = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                End If
                Set lo_TextBox = Nothing
            
            Case UCase("Label"), UCase("Frame"), UCase("CommandButton"), UCase("CheckBox"), UCase("OptionButton")
                If lc_Control.Tag <> "" Then
                    li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lc_Control.Tag, , 1)
                    If li_Label >= 0 Then
                        lc_Control.Caption = ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT")
                    End If
                End If
            Case "ARMGRID"
                li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lc_Control.Tag, , 1)
                If li_Label >= 0 Then
                    Call lc_Control.LoadConstants(ptStatic, ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT"), ctColumns)
                End If
            Case "ARMCHECKVIEW"
                li_Label = ao_Armdb.Find(lc_Labels, "FIELD_NAME", lc_Control.Tag, , 1)
                If li_Label >= 0 Then
                  Call cv_Share.LoadConstants(CVptStatic, ao_Armdb.GetFields(lc_Labels, "LOCAL_TEXT"), CVctCombo)
                End If

        End Select
    Next
        
Trace_End:
    Call ao_Armdb.Close(lc_Labels)
    Call SetMousePointer(True)
    Exit Sub
    
Trace_Err:
    Call ao_Armdb.Close(lc_Labels)
    Call SetMousePointer(True)
      
End Sub

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

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


Private Sub ControlsClear(ByRef lo_Controls As Variant, ByRef lo_Container As Object)
    
    Dim ll_Index As Long
    Dim lo_Control As Control
    Dim lo_ListItem As ListItem
    
    For ll_Index = 0 To lo_Controls.Count - 1
        Set lo_Control = lo_Controls(ll_Index)
        If HasContainer(lo_Control, lo_Container) Then
            Select Case UCase(TypeName(lo_Control))
                Case "ARMCOMBOBOX"
                    Set lo_Control.SelectedItem = Nothing
                    lo_Control.Text = ""
                Case "CHECKBOX", "OPTIONBUTTON"
                    lo_Control.Value = 0
                Case "TEXTBOX"
                    lo_Control.Text = ""
                Case "ARMCHECKVIEW"
                    lo_Control.UnCheckAll
                Case "A_CALOCX"
                    Call lo_Control.reinit_cal
                Case "COMBOBOX"
                    lo_Control.ListIndex = -1
                    If lo_Control.Style = 0 Then lo_Control.Text = ""
                Case "LISTVIEW"
                    For Each lo_ListItem In lo_Control.ListItems
                      lo_ListItem.Checked = False
                    Next
            End Select
        End If
    Next
        
End Sub

Private Function ExecuteSQL(as_Request As String, ByRef av_Result As Variant) As Boolean
Dim ll_Cursor As Long

On Error GoTo ErrorHandler
  Call SetMousePointer(False)
  av_Result = Empty
  ExecuteSQL = False
  ll_Cursor = mo_Db.OpenSQL(as_Request)
  If ll_Cursor <> 0 Then
    If mo_Db.RowCount(ll_Cursor) = 1 Then
      av_Result = mo_Db.GetFields(ll_Cursor, 0)
      ExecuteSQL = True
    End If
    Call mo_Db.Close(ll_Cursor)
  End If
  Call SetMousePointer(True)
  Exit Function
ErrorHandler:
  Call SetMousePointer(True)
  ExecuteSQL = False
End Function

Private Function ChangeCharset(ByRef ao_Container As Object, Charset As Integer) As Boolean
Dim lc_Control As Control   ' A control of the container

On Error GoTo CleanUp:
  If Charset <> 0 Then
    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"
          'lc_Control.Font.Name = "Arial"
          lc_Control.Font.Charset = Charset
        End Select
    Next
  End If
  ChangeCharset = True
  Exit Function
CleanUp:
  ChangeCharset = False
End Function

Private Function GetCodePage(as_Language As String) As Long
Dim ll_Cursor As Long

  
  ll_Cursor = OpenCursor("SELECT Code_Page FROM language WHERE Language_Code='" & as_Language & "'")
  If ll_Cursor > 0 Then
    GetCodePage = mo_Db.GetFields(ll_Cursor, 0)
    Call CloseCursor(ll_Cursor)
  End If
End Function

Private Function GetCharSet(ByVal sCodePage As String) As Integer
   Select Case sCodePage
      Case "932" ' Japanese
         GetCharSet = 128
      Case "936" ' Simplified Chinese
         GetCharSet = 134
      Case "949" ' Korean
         GetCharSet = 129
      Case "950" ' Traditional Chinese
         GetCharSet = 136
      Case "1250" ' Eastern Europe
         GetCharSet = 238
      Case "1251" ' Russian
         GetCharSet = 204
      Case "1252" ' Western European Languages
         GetCharSet = 0
      Case "1253" ' Greek
         GetCharSet = 161
      Case "1254" ' Turkish
         GetCharSet = 162
      Case "1255" ' Hebrew
         GetCharSet = 177
      Case "1256" ' Arabic
         GetCharSet = 178
      Case "1257" ' Baltic
         GetCharSet = 186
      Case Else
         GetCharSet = 0
   End Select
End Function

Private Function GetLCIDFromCodePage(ByVal al_CodePage As Long) As Long

    Select Case al_CodePage
        Case 932 ' Japanese
            GetLCIDFromCodePage = 1041
        Case 936 ' Simplified Chinese
            GetLCIDFromCodePage = 2052
        Case 949 ' Korean
            GetLCIDFromCodePage = 1042
        Case 950 ' Traditional Chinese
            GetLCIDFromCodePage = 1028
        Case 1250 ' Eastern Europe
            GetLCIDFromCodePage = 1045
        Case 1251  ' Russian
            GetLCIDFromCodePage = 1049
        Case 1252  ' Western European Languages
            GetLCIDFromCodePage = 1033
        Case 1253 ' Greek
            GetLCIDFromCodePage = 1032
        Case 1254 ' Turkish
            GetLCIDFromCodePage = 1055
        Case 1255 ' Hebrew
            GetLCIDFromCodePage = 1037
        Case 1256 ' Arabic
            GetLCIDFromCodePage = 1025
        Case 1257 ' Baltic
            GetLCIDFromCodePage = 1061
        Case Else
            GetLCIDFromCodePage = 1033
    End Select
End Function


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

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

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

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

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

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

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


