<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-23T03:50:46.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-04-15T04:49:13.2740000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-23T03:50:29.0200000</UpdatedUtcDate>
    <ScriptId>HWID</ScriptId>
    <Description>Income Distribution</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_IncomeDistribution
Option Explicit On
Option Strict On

' #################################################################
' Income Distribution
'
' Version: 1.03 (23/09/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  03/03/2023  ISS      J030350   Created
'    1.01  07/02/2024  ISS      J032635   Added user fields 10-19
'          09/04/2024  ISS      J032054   Script Timeout set to unlimited
'    1.02  04/06/2024  ISS      J033561   Added Desktop Mode
'          12/06/2024  ISS      J033698   mIncomeDistribution.Progress &amp; mIncomeDistribution.ProgressRefresh Events are now included in the Status Messages
'    1.03  23/09/2024  ISS      J034286   Restricting the Batch Reference field to 20 characters
' #################################################################

' Constants
Private Const FORM_KEY As String = "IncomeDistribution"

' Objects
Private WithEvents mIncomeDistribution As finIncomeDistribution
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

' Other
Private mAutoCommit As Boolean
Private mDesktopMode As Boolean
Private mIsRefreshing As Boolean
Private mLastCaption As String
Private mProcessId As String
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus

Public Function Main(eventId As String, parametersJson As String, startUpParametersJson As String, hostingContext As isefinHtmlWidgetHostingContext, requestInfo As finScriptRequestInfo, ByRef returnValue As String) As Boolean

  ' Assume Success
  Main = True

  ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

  ' Get Combined Parameters (Startup Parameters updated with event Parameters)
  mCombinedParameters = mStartupParameters.Clone()
  mCombinedParameters.UpdateFromKeyValueList(mParameters, True)

  ' Get Parameters
  With mCombinedParameters
    mAutoCommit = .GetBoolean("AutoCommit")
    mDesktopMode = .GetBoolean("DesktopMode")    
    mProcessId = .GetString("ProcessId")
  End With

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      returnValue = ScriptInfo.TemplateText

    Case "BackgroundProcess.ExecuteCommit"
      ' Called by Web Services to execute a Background Process that was initially queued in the Widget's UI (via the Finish event)
      Main = BackgroundProcess_ExecuteCommit(returnValue)

    Case "BackgroundProcess.Refresh"
      ' Called by Web Services to execute a Background Process to refresh data that was initially queued in the Widget's UI
      Main = BackgroundProcess_Refresh(returnValue)

    Case "CancelBackgroundProcess"
      ' Cancel a Process
      Main = CancelBackgroundProcess(returnValue)

    Case "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, startUpParametersJson, returnValue)

    Case "GetBackgroundProcessStatus"
      ' Get Background Process Status
      Main = GetBackgroundProcessStatus(returnValue)

    Case "GetBatchId"
      ' Get Transaction Batch Id
      Main = GetBatchId(returnValue)
      
    Case "GetCurrentProcesses"
      ' Get Current Processes
      Main = GetCurrentProcesses(returnValue)

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)

    Case "GetTransactionDetails"
      ' Get Transaction Details
      Main = GetTransactionDetails(parametersJson, returnValue)
      
    Case "PrintIncomeDistributionList"
      ' Print Income Distribution List
      Main = PrintIncomeDistributionList(parametersJson, returnValue)
      
    Case "Refresh"
      ' Refresh (and Execute Commit, if in Auto Commit mode)
      Main = Refresh(parametersJson, startupParametersJson, returnValue)

    Case "UpdateRefreshData"
      ' Update Refresh Data
      Main = UpdateRefreshData(parametersJson)

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, returnValue)      
      
    Case Else
      finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
      Main = False
  End Select

End Function

''' &lt;summary&gt;
'''  Get Initialisation Information required for this wizard
''' &lt;/summary&gt;
Private Function GetInitialisationInfo(ByRef returnValue As String) As Boolean

  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim IncomeDistribution As finIncomeDistribution
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean
  Dim TransactionTypeRO As finTransactionTypeRO

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Validate
  Success = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)

  ' Validate Process Id
  If Success AndAlso Len(mProcessId) &lt;&gt; 0 Then
    Success = finBL.HtmlWidgetUtilities.BackgroundProcessStatusIsValid(mProcessId, isefinCloudConnectProcessType.HtmlWidgetBackground)
  End If

  ' Get finIncomeDistribution Object
  If Success Then
    Success = CreateIncomeDistribution(Nothing, IncomeDistribution)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId           
      
      ' Lists
      .AccountUsers.Add(New AccountUser(0))
      .AccountUsers.Add(New AccountUser(1))
      .AccountUsers.Add(New AccountUser(2))
      .AccountUsers.Add(New AccountUser(3))
      .AccountUsers.Add(New AccountUser(4))
      .AccountUsers.Add(New AccountUser(5))
      .AccountUsers.Add(New AccountUser(6))
      .AccountUsers.Add(New AccountUser(7))
      .AccountUsers.Add(New AccountUser(8))
      .AccountUsers.Add(New AccountUser(9))
      .AccountUsers.Add(New AccountUser(10))
      .AccountUsers.Add(New AccountUser(11))
      .AccountUsers.Add(New AccountUser(12))
      .AccountUsers.Add(New AccountUser(13))
      .AccountUsers.Add(New AccountUser(14))
      .AccountUsers.Add(New AccountUser(15))
      .AccountUsers.Add(New AccountUser(16))
      .AccountUsers.Add(New AccountUser(17))
      .AccountUsers.Add(New AccountUser(18))
      .AccountUsers.Add(New AccountUser(19))
        
      For Each TransactionTypeRO In finBL.TransactionTypes
        If TransactionTypeRO.Active Then
          .TransactionTypes.Add(New TransactionType(TransactionTypeRO))
        End If        
      Next 
      .TransactionTypeSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.TransactionTypes.GetDataViewFilter_IncomeDistribution())

      ' Advanced      
      .ShowAccountManagers = mCombinedParameters.GetString("ShowAccountManagers") : If Len(.ShowAccountManagers) = 0 Then .ShowAccountManagers = "Advanced"
      .ShowAccounts = mCombinedParameters.GetString("ShowAccounts") : If Len(.ShowAccounts) = 0 Then .ShowAccounts = "Advanced"
      .ShowAccountTypes = mCombinedParameters.GetString("ShowAccountTypes") : If Len(.ShowAccountTypes) = 0 Then .ShowAccountTypes = "Advanced"
      .ShowBranches = mCombinedParameters.GetString("ShowBranches") : If Len(.ShowBranches) = 0 Then .ShowBranches = "True"      
      .ShowDepartments = mCombinedParameters.GetString("ShowDepartments") : If Len(.ShowDepartments) = 0 Then .ShowDepartments = "Advanced"
      .ShowEntities = mCombinedParameters.GetString("ShowEntities") : If Len(.ShowEntities) = 0 Then .ShowEntities = "Advanced"
      .ShowBrokers = mCombinedParameters.GetString("ShowBrokers") : If Len(.ShowBrokers) = 0 Then .ShowBrokers = "Advanced"
      .ShowDealers = mCombinedParameters.GetString("ShowDealers") : If Len(.ShowDealers) = 0 Then .ShowDealers = "Advanced"
      .ShowPools = mCombinedParameters.GetString("ShowPools") : If Len(.ShowPools) = 0 Then .ShowPools = "True"
      .ShowProductTypes = mCombinedParameters.GetString("ShowProductTypes") : If Len(.ShowProductTypes) = 0 Then .ShowProductTypes = "Advanced"
      .ShowAccountUser = mCombinedParameters.GetString("ShowAccountUser") : If Len(.ShowAccountUser) = 0 Then .ShowAccountUser = "Advanced"

      ' Licence
      If Not finBL.Settings.AddOns.Branch Then .ShowBranches = "False"
      If Not finBL.Settings.AddOns.Entity Then .ShowEntities = "False"
      If Not finBL.Settings.AddOns.Pool Then .ShowPools = "False"
      If Not finBL.Settings.AddOns.ExternalPartyBrokers Then .ShowBrokers = "False"
      If Not finBL.Settings.AddOns.ExternalPartyDealers Then .ShowDealers = "False"
      If .AccountUsers.Count() = 0 Then .ShowAccountUser = "False"

      ' Ranges Heading
      If (.ShowAccountManagers = "True" OrElse .ShowAccounts = "True" OrElse .ShowAccountTypes = "True" OrElse .ShowBranches = "True" OrElse .ShowDepartments = "True" OrElse 
          .ShowEntities = "True" OrElse .ShowBrokers = "True" OrElse .ShowDealers = "True" OrElse .ShowPools = "True" OrElse .ShowProductTypes = "True" OrElse .ShowAccountUser = "True") Then
        .ShowRangesHeading = "True"
      ElseIf (.ShowAccountManagers = "False" AndAlso .ShowAccounts = "False" AndAlso .ShowAccountTypes = "False" AndAlso .ShowBranches = "False" AndAlso .ShowDepartments = "False" AndAlso 
              .ShowEntities = "False" AndAlso .ShowBrokers = "False" AndAlso .ShowDealers = "False" AndAlso .ShowPools = "False" AndAlso .ShowProductTypes = "False" AndAlso .ShowAccountUser = "False") Then
        .ShowRangesHeading = "False"
      Else
        .ShowRangesHeading = "Advanced"
      End If  
        
      ' General
      .PageGeneralHasAdvanced = (.ShowAccountManagers = "Advanced" OrElse .ShowAccounts = "Advanced" OrElse .ShowAccountTypes = "Advanced" OrElse .ShowBranches = "Advanced" OrElse 
                                 .ShowDepartments = "Advanced" OrElse .ShowEntities = "Advanced" OrElse .ShowBrokers = "Advanced" OrElse .ShowDealers = "Advanced" OrElse
                                 .ShowPools = "Advanced" OrElse .ShowProductTypes = "Advanced" OrElse .ShowAccountUser = "Advanced")

      ' Permissions
      .CanSaveToBatch = finBL.CurrentUser.Permissions.Allow("Account.IncomeDistribution.SaveToBatch")

      ' Configuration
      .AutoCommit = mAutoCommit
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    End With

    ' Get current and recent Background Processes for this User
    If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses) Then
      FormInitialisationInfo.CurrentProcesses = ProcessStatuses
    Else
      Success = False
    End If

    ' Serialise
    If Success Then
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, returnValue)
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account User Sql Where.
''' &lt;/summary&gt;
Private Shared Function GetAccountUserSqlWhere(userField As String) As String

  Dim sqb As ISSelectQueryBuilder
  
  ' Initialise
  sqb = finBLShared.Database.CreateSelectQueryBuilder()
  
  ' Build Query
  With sqb
    .DistinctType = iseSelectQueryDistinctType.Distinct
    .Table = "Account"
    .Fields.Add(userField)
  End With

  Return sqb.GetSql()
  
End Function

''' &lt;summary&gt;
'''  Request that a Background Process is Cancelled.
''' &lt;/summary&gt;
Private Function CancelBackgroundProcess(ByRef returnValue As String) As Boolean

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ProcessId = mCombinedParameters.GetString("ProcessId")

  ' Request Cancel
  Success = finBL.HtmlWidgetUtilities.CancelBackgroundProcess(processId)

  Return Success

End Function

''' &lt;summary&gt;
'''  Builds a finIncomeDistribution object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateIncomeDistribution(parameters As WizardFinishParameters,
                                          ByRef incomeDistribution As finIncomeDistribution) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  incomeDistribution = finBL.CreateIncomeDistribution()

  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With incomeDistribution
      .PeriodDateFrom = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.PeriodFrom)
      .PeriodDateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.PeriodTo)
      
      .IncomeReceived = parameters.IncomeReceived
      .ExpensesIncurred = parameters.ExpensesIncurred
      .InterimDistribution = parameters.InterimDistribution
      
      .RangeAccountManagers = parameters.RangeAccountManagers
      .RangeAccounts = parameters.RangeAccounts
      .RangeAccountTypes = parameters.RangeAccountTypes
      .RangeBranches = parameters.RangeBranches
      .RangeDepartments = parameters.RangeDepartments
      .RangeEntities = parameters.RangeEntities
      .RangeExternalPartiesBrokers = parameters.RangeExternalPartiesBrokers
      .RangeExternalPartiesDealers = parameters.RangeExternalPartiesDealers
      .RangePools = parameters.RangePools
      .RangeProductTypes = parameters.RangeProductTypes
      .RangeAccountUser(0) = parameters.RangeAccountUser0
      .RangeAccountUser(1) = parameters.RangeAccountUser1
      .RangeAccountUser(2) = parameters.RangeAccountUser2
      .RangeAccountUser(3) = parameters.RangeAccountUser3
      .RangeAccountUser(4) = parameters.RangeAccountUser4
      .RangeAccountUser(5) = parameters.RangeAccountUser5
      .RangeAccountUser(6) = parameters.RangeAccountUser6
      .RangeAccountUser(7) = parameters.RangeAccountUser7
      .RangeAccountUser(8) = parameters.RangeAccountUser8
      .RangeAccountUser(9) = parameters.RangeAccountUser9
      .RangeAccountUser(10) = parameters.RangeAccountUser10
      .RangeAccountUser(11) = parameters.RangeAccountUser11
      .RangeAccountUser(12) = parameters.RangeAccountUser12
      .RangeAccountUser(13) = parameters.RangeAccountUser13
      .RangeAccountUser(14) = parameters.RangeAccountUser14
      .RangeAccountUser(15) = parameters.RangeAccountUser15
      .RangeAccountUser(16) = parameters.RangeAccountUser16
      .RangeAccountUser(17) = parameters.RangeAccountUser17
      .RangeAccountUser(18) = parameters.RangeAccountUser18
      .RangeAccountUser(19) = parameters.RangeAccountUser19
      
      .TransactionTypeId = parameters.TransactionTypeId
      .TransactionBatchId = parameters.TransactionBatchId
      .TransactionDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.TransactionDate)
      .TransactionReference = parameters.TransactionReference
      .TransactionNotes = parameters.TransactionNotes
      
      .SaveToBatch = parameters.SaveToBatch
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Refresh, i.e., Queue Background Process.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Refresh(parametersJson As String,
                         startupParametersJson As String,
                         ByRef returnValue As String) As Boolean
                      
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  ' NOTE: Only required for validation purposes
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Validate
  If Success Then
    ' Not required
  End If
  
  ' Start Background Process to Refresh Data
  If Success Then
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript_Refresh(ScriptInfo.ScriptId, parametersJson, startupParametersJson, mAutoCommit, ProcessId, mDesktopMode)
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(ProcessId), returnValue)
  End If
  
  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Queue Background Process.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        startupParametersJson As String,
                        ByRef returnValue As String) As Boolean

  Dim CompleteMessage As String
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parse Parameters
  ' NOTE: Only required for validation purposes
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Validate
  If Success Then
    ' Not required
  End If
  
  ' Queue Background Process
  If mAutoCommit Then
    ' Queue "Refresh" - Execute Commit will occur automatically
    Success = Me.Refresh(parametersJson, startupParametersJson, returnValue)
  Else 
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript_ExecuteCommit(ScriptInfo.ScriptId, WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData, mDesktopMode)
    If Success Then
      ' Context-specific functionality - not supported
      CompleteMessage = ""
    End If
    
    ' Response
    If Success Then
      Data = New With {
        .ProcessId = WizardFinishParameters.ProcessId,
        .CompleteMessage = CompleteMessage
      }
    End If
  
    ' Finalise
    If Success Then
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Background Process Status.
''' &lt;/summary&gt;
Private Function GetBackgroundProcessStatus(ByRef returnValue As String) As Boolean

  Dim LastEventId As String
  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    LastEventId = .GetString("LastEventId")
    ProcessId = .GetString("ProcessId")
  End With

  ' Get Background Processes Status including Events
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusIncludingEventsJson(processId, lastEventId, returnValue)

  Return Success

End Function

''' &lt;summary&gt;
'''  Get current and recent Background Processes that for this User (these  are also returned in GetInitialisationInfo).
''' &lt;/summary&gt;
Private Function GetCurrentProcesses(ByRef returnValue As String) As Boolean

  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get current and recent Background Processes that for this User
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_HtmlWidgetScript(ScriptInfo.ScriptId, True, ProcessStatuses)

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ProcessStatuses, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Next Batch Id for a Transaction Type.
''' &lt;/summary&gt;
Private Function GetBatchId(ByRef returnValue As String) As Boolean
  
  Dim Success As Boolean
  Dim TransactionTypeId As String
  Dim BatchId As String
  
  ' Assume Success
  Success = True
  
  ' Parameters
  With mCombinedParameters
    TransactionTypeId = .GetString("TransactionTypeId")
  End With
  
  ' Get Batch Id
  BatchId = finBL.BatchFunctions.GetNextBatchIdFromTransactionType(TransactionTypeId)
  
  ' Error
  If Len(BatchId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Failed to create next Auto-sequenced Batch Id.")
  Else 
    returnValue = BatchId
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get Transaction Details.
''' &lt;/summary&gt;
Private Function GetTransactionDetails(parametersJson As String,
                                       ByRef returnValue As String) As Boolean
  
  Dim ActualDistribution As Decimal
  Dim Data As Object                                       
  Dim DistributionDifferenceText As String
  Dim DistributionRate As Double
  Dim IncomeDistribution As IncomeDistribution
  Dim obj As Object
  Dim PeriodDays As Integer
  Dim PeriodDaysText As String
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Deserialise
  If mAutoCommit Then
    With mCombinedParameters
      PeriodDays = CInt(DateDiff(DateInterval.Day, finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateFrom")), finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateTo")))) + 1
    End With
    
    ' Period Days
    If PeriodDays = 1 Then
      PeriodDaysText = "1 Day"
    Else 
      PeriodDaysText = PeriodDays &amp; " Days"
    End If 
  Else 
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(IncomeDistribution), obj) Then
      IncomeDistribution = DirectCast(obj, IncomeDistribution)
    Else 
      Success = False
    End If
    
    ' Perform Calculations
    If Success Then
      IncomeDistribution.GetCalculationValues(ActualDistribution, DistributionDifferenceText, DistributionRate, PeriodDaysText)
    End If
  End If
  
  ' Get Data
  If Success Then
    Data = New With {
      .ActualDistribution = ActualDistribution,
      .DistributionDifferenceText = DistributionDifferenceText,
      .DistributionRate = finBL.Runtime.NumberUtilities.RoundDouble(DistributionRate, 4),
      .PeriodDaysText = PeriodDaysText
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Deserialise
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
    wizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Update Refresh Data.
''' &lt;/summary&gt;
Private Function UpdateRefreshData(parametersJson As String) As Boolean

  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Update Process
  If Success Then
    Success = finBL.HtmlWidgetUtilities.UpdateBackgroundProcessRefreshData(WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean
                           
  Dim ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    PageId = .GetString("PageId")    
  End With

  ' Validate Page
  Select Case PageId
    Case "General"      
      ConfirmList = New List(Of String)
      Data = ConfirmList
      
    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Unhandled page '{0}' in WizardValidate.", PageId)
  End Select

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidateResponse(Data, FailedMessage, FailedControlId), returnValue)
  End If

  Return Success

End Function

Private Function BackgroundProcess_Refresh(ByRef returnValue As String) As Boolean

  Dim IncomeDistribution As finIncomeDistribution
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True
  
  ' Refreshing
  mIsRefreshing = True
  
  ' Get Background Process
  ' NOTE: This is required to add events and to check to see if the User has attempted to cancel this process (if supported)
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)
  
  ' Parse Parameters
  Success = GetWizardFinishParameters(mParameters.ToSimpleJsonString(), WizardFinishParameters)
  
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Refreshing Accounts for Income Distribution")
  End If
  
  ' Refresh Accounts
  If Success Then
    ' Create
    Success = CreateIncomeDistribution(WizardFinishParameters, IncomeDistribution)
    
    ' Refresh
    If Success Then Success = IncomeDistribution.Refresh()
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New IncomeDistribution(IncomeDistribution), returnValue)    
  End If
  
  ' Refreshing
  mIsRefreshing = False
  
  Return Success  
  
End Function

Private Function BackgroundProcess_ExecuteCommit(ByRef returnValue As String) As Boolean
  
  Dim Cancelled As Boolean
  Dim Distribution As IncomeDistribution    
  Dim obj As Object
  Dim RefreshData As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim FileName As String
  
  ' Assume Success
  Success = True
  
  ' Reset last caption
  mLastCaption = ""
  
  ' Get Background Process
  ' NOTE: This is required to add events and to check to see if the User has attempted to cancel this process (if supported)
  mProcessStatus = DirectCast(ScriptInfo.ContextData.GetObject("ProcessStatus"), finHtmlWidgetBackgroundProcessStatus)

  ' Notify
  mProcessStatus.AddEvent_Information("Starting Commit")
  
  ' Get Income Distribution  
  If GetWizardFinishParameters(mParameters.ToSimpleJsonString(), WizardFinishParameters) Then
    Success = CreateIncomeDistribution(WizardFinishParameters, mIncomeDistribution)
  Else 
    Success = False
  End If
  
  ' Get Distribution from the UI (where grid values may have updated)
  If Success Then
    If finBL.HtmlWidgetUtilities.GetBackgroundProcessRefreshData(mProcessStatus.ProcessId, RefreshData) Then
      If Len(RefreshData) = 0 Then
        Success = False
        finBL.Error.ErrorBegin("No Refresh Data available.")
      Else 
        If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(RefreshData, GetType(IncomeDistribution), obj) Then
          Distribution = DirectCast(obj, IncomeDistribution)
        Else 
          Success = False
        End If
      End If
    Else 
      Success = False
    End If
  End If

  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Setting Distribution Values")
  End If
  
  ' Refresh
  If Success Then
    Success = mIncomeDistribution.Refresh()
  End If
  
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Updating Transaction Details")
  End If 
  
  ' Update Income Distribution with Json object
  If Success Then
    Success = UpdateIncomeDistributionFromJsonClass(Distribution, mIncomeDistribution)
  End If 
  
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Committing Distribution")
  End If
  
  ' Commit
  If Success Then
    Success = mIncomeDistribution.ExecuteCommit()
  End If
  
  ' The above file has been saved to Downloads but, we can also attach it to any Success email
  If Success AndAlso Not Cancelled Then
    mProcessStatus.AddEvent_Information("Generating PDF Summary")
    
    FileName = finBL.Runtime.FileUtilities.GetTemporaryFileName("ProcessIncomeDistributionSummary", "pdf")
    
    ' Create Summary using a copy of the Distribution (as this function is shared by PrintIncomeDistributionList, which must be the Json Class)
    If CreateIncomeDistributionSummaryPdf(New IncomeDistribution(mIncomeDistribution), FileName) Then
      ' Attach File
      mProcessStatus.Attachments.AddDataFromFile(FileName, Nothing)
  
      ' Delete Temporary file
      finBL.Runtime.FileUtilities.DeleteFile(FileName)
    End If    
  End If
  
  Return Success  
  
End Function

Private Sub mIncomeDistribution_Progress(progress As Double, caption As String) Handles mIncomeDistribution.Progress

  Dim AddEvent As Boolean
  
  ' Filter Events - mostly to prevent multiple 'Committing Batch' events from being written
  If Len(mLastCaption) = 0 Then
    AddEvent = True
  ElseIf StrComp(caption, mLastCaption) = 0 Then
    AddEvent = False
  Else 
    AddEvent = True
  End If  
  
  ' Log Event
  If AddEvent Then
    mProcessStatus.AddEvent_Information(caption)
    
    ' Update last caption
    mLastCaption = caption
  End If  
  
End Sub

Private Sub mIncomeDistribution_ProgressRefresh(progress As Double, caption As String) Handles mIncomeDistribution.ProgressRefresh

  ' Log Event
  If mIsRefreshing Then
    ' Only log when Refreshing initially. This is required as another Refresh occurs during the commit, we don't want to add events during this secondary refresh
    mProcessStatus.AddEvent_Information(caption)
  End If  
  
End Sub

''' &lt;summary&gt;
'''  Generates the Income Distribution summary and produces a file.
''' &lt;/summary&gt;
''' &lt;param name="filename"&gt;
'''  The file name of the file to be written.
''' &lt;/param&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateIncomeDistributionSummaryPdf(incomeDistribution As IncomeDistribution,
                                                    filename As String) As Boolean

  Dim ActualDistribution As Decimal               
  Dim DistributionRate As Double
  Dim PeriodDaysText As String
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim SummaryTables As ISSummaryTables
  Dim SummaryTableHeaderInfo As ISSummaryTable

  ' Assume Success
  Success = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()
  SummaryTableHeaderInfo = finBL.CreateSummaryTable()

  ' Validate
  If Len(filename) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("A valid file name must be specified.")
  ElseIf StrComp(finBL.Runtime.FileUtilities.GetFileExtension(filename), "PDF", CompareMethod.Text) &lt;&gt; 0 Then
    Success = False
    finBL.Error.ErrorBegin("A valid PDF must be specified.")
  End If

  ' Get Data
  If Success Then
    If GetIncomeDistributionSummary(incomeDistribution, SummaryTables) Then
      incomeDistribution.GetCalculationValues(ActualDistribution, "", DistributionRate, PeriodDaysText)
    Else 
      Success = False
    End If
  End If

  ' Generate Header Info
  If Success Then
    SummaryTableHeaderInfo = finBL.CreateSummaryTable()
    With SummaryTableHeaderInfo
      .TableClass = iseSummaryTableClass.Information
      .Columns.AddText().WidthChars = 30
      .Columns.AddText()

      With .Rows
        .AddSectionHeading2("Distribution Period")
        .AddCaptionDate("Period From:", finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(incomeDistribution.PeriodFrom))
        .AddCaptionDate("Period To:", finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(incomeDistribution.PeriodTo))
        .AddCaptionText("Period:", PeriodDaysText)

        .AddSectionHeading2("Distribution Amounts")
        .AddCaptionCurrency("Income Received:", incomeDistribution.IncomeReceived)
        .AddCaptionCurrency("Less Expenses Incurred:", incomeDistribution.ExpensesIncurred)
        .AddCaptionCurrency("Funds Available:", incomeDistribution.FundsAvailableToDistribute).RowClass = iseSummaryTableRowClass.NormalBold
        .AddCaptionCurrency("Interim Distribution:", incomeDistribution.InterimDistribution)
        .AddCaptionCurrency("Net Distribution:", incomeDistribution.NetDistribution).RowClass = iseSummaryTableRowClass.FooterBold
        
        .AddCaptionCurrency("Actual Distribution:", ActualDistribution)
        .AddCaptionPercentage("Distribution Rate:", DistributionRate / 100, 4, True)
        
        ' Ranges
        If Len(incomeDistribution.RangeAccountManagers) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeAccounts) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeAccountTypes) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeBranches) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeDepartments) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeEntities) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeExternalPartiesBrokers) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeExternalPartiesDealers) &lt;&gt; 0 OrElse Len(incomeDistribution.RangePools) &lt;&gt; 0 OrElse Len(incomeDistribution.RangeProductTypes) &lt;&gt; 0 Then
          .AddSectionHeading2("Ranges")
        End If        
        If Len(incomeDistribution.RangeAccountManagers) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.AccountManagers) &amp; ":", incomeDistribution.RangeAccountManagers)
        If Len(incomeDistribution.RangeAccounts) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.AccountsDeposits) &amp; ":", incomeDistribution.RangeAccounts)   
        If Len(incomeDistribution.RangeAccountTypes) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.AccountTypesDeposits) &amp; ":", incomeDistribution.RangeAccountTypes)
        If Len(incomeDistribution.RangeBranches) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Branches) &amp; ":", incomeDistribution.RangeBranches)
        If Len(incomeDistribution.RangeDepartments) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Departments) &amp; ":", incomeDistribution.RangeDepartments)
        If Len(incomeDistribution.RangeEntities) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Entities) &amp; ":", incomeDistribution.RangeEntities)
        If Len(incomeDistribution.RangeExternalPartiesBrokers) &lt;&gt; 0 Then 
          .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ExternalPartiesBrokers) &amp; ":", incomeDistribution.RangeExternalPartiesBrokers)
          .AddCaptionTick("Include Sub Brokers?", incomeDistribution.RangeExternalPartiesBrokersIncludeSub, True)
        End If
        If Len(incomeDistribution.RangeExternalPartiesDealers) &lt;&gt; 0 Then 
          .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ExternalPartiesDealers) &amp; ":", incomeDistribution.RangeExternalPartiesDealers)
          .AddCaptionTick("Include Sub Dealers?", incomeDistribution.RangeExternalPartiesDealersIncludeSub, True)
        End If
        If Len(incomeDistribution.RangePools) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Pools) &amp; ":", incomeDistribution.RangePools)  
        If Len(incomeDistribution.RangeProductTypes) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ProductTypes) &amp; ":", incomeDistribution.RangeProductTypes)           
        If Len(incomeDistribution.RangeAccountUser0) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(0) &amp; ":", incomeDistribution.RangeAccountUser0)
        If Len(incomeDistribution.RangeAccountUser1) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(1) &amp; ":", incomeDistribution.RangeAccountUser1)
        If Len(incomeDistribution.RangeAccountUser2) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(2) &amp; ":", incomeDistribution.RangeAccountUser2)
        If Len(incomeDistribution.RangeAccountUser3) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(3) &amp; ":", incomeDistribution.RangeAccountUser3)
        If Len(incomeDistribution.RangeAccountUser4) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(4) &amp; ":", incomeDistribution.RangeAccountUser4)
        If Len(incomeDistribution.RangeAccountUser5) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(5) &amp; ":", incomeDistribution.RangeAccountUser5)
        If Len(incomeDistribution.RangeAccountUser6) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(6) &amp; ":", incomeDistribution.RangeAccountUser6)
        If Len(incomeDistribution.RangeAccountUser7) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(7) &amp; ":", incomeDistribution.RangeAccountUser7)
        If Len(incomeDistribution.RangeAccountUser8) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(8) &amp; ":", incomeDistribution.RangeAccountUser8)
        If Len(incomeDistribution.RangeAccountUser9) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(9) &amp; ":", incomeDistribution.RangeAccountUser9)
        If Len(incomeDistribution.RangeAccountUser10) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(10) &amp; ":", incomeDistribution.RangeAccountUser10)
        If Len(incomeDistribution.RangeAccountUser11) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(11) &amp; ":", incomeDistribution.RangeAccountUser11)
        If Len(incomeDistribution.RangeAccountUser12) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(12) &amp; ":", incomeDistribution.RangeAccountUser12)
        If Len(incomeDistribution.RangeAccountUser13) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(13) &amp; ":", incomeDistribution.RangeAccountUser13)
        If Len(incomeDistribution.RangeAccountUser14) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(14) &amp; ":", incomeDistribution.RangeAccountUser14)
        If Len(incomeDistribution.RangeAccountUser15) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(15) &amp; ":", incomeDistribution.RangeAccountUser15)
        If Len(incomeDistribution.RangeAccountUser16) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(16) &amp; ":", incomeDistribution.RangeAccountUser16)
        If Len(incomeDistribution.RangeAccountUser17) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(17) &amp; ":", incomeDistribution.RangeAccountUser17)
        If Len(incomeDistribution.RangeAccountUser18) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(18) &amp; ":", incomeDistribution.RangeAccountUser18)
        If Len(incomeDistribution.RangeAccountUser19) &lt;&gt; 0 Then .AddCaptionText(finBL.Settings.AccountUser(19) &amp; ":", incomeDistribution.RangeAccountUser19)
        
        ' Transaction Details        
        .AddSectionHeading2("Transaction Details")
        .AddCaptionCodeDescription("Transaction Type:", incomeDistribution.TransactionTypeId, finBL.TransactionTypes)
        .AddCaptionText("Batch Id:", incomeDistribution.TransactionBatchId)
        .AddCaptionDate("Date:", finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(incomeDistribution.TransactionDate))
        .AddCaptionText("Reference:", incomeDistribution.TransactionReference)
        .AddCaptionText("Notes:", incomeDistribution.TransactionNotes)
        
        .AddSectionHeading2("Distribution Saved to a Transaction Batch")
        .AddCaptionTick("Save Batch?", incomeDistribution.SaveToBatch, True)
      End With
    End With
  End If

  ' Build Summary Page
  If Success Then
    ' Initialise Summary Page
    sb.Initialise(iseSummaryPageTarget.WebServices)
    sb.HtmlHeaderBegin("IncomeDistribution", isefinSummaryPageStyle.Document)
    sb.HtmlHeaderEnd()

    ' Append Information
    sb.AppendH1("Income Distributions Processed")
    sb.AppendFormat("&lt;p&gt;Report generated &lt;b&gt;{0}&lt;/b&gt; by &lt;b&gt;{1}&lt;/b&gt;&lt;/p&gt;", finBL.FormatDateTimeLongWithTimeZone(finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime(), finBL.TimeZoneId), finBL.HtmlEncode(finBL.CurrentUser.UserId))
    sb.SummaryTableAppend(SummaryTableHeaderInfo)
    sb.AppendLine("&lt;br/&gt;")
    sb.SummaryTablesAppend(SummaryTables)

    ' Finalise
    sb.HtmlFinalise()
  End If

  ' Generate Temp file
  If Success Then
    Success = finBL.PdfUtilities.CreatePdfFileFromHtml(sb.ToString(True), filename)
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to Get Income Distribution Summary Pdf.")
  End If

  Return Success

End Function

Private Function GetIncomeDistributionSummary(incomeDistribution As IncomeDistribution,
                                              ByRef summaryTables As ISSummaryTables) As Boolean

  Dim DataRow As DataRow
  Dim dt As DataTable
  Dim IncomeDistributionItem As IncomeDistributionItem
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTableRow As ISSummaryTableRow
  Dim TotalDistribution As Decimal
  Dim TotalDistributionOriginal As Decimal

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  summaryTables = finBL.CreateSummaryTables()

  ' Initialise
  dt = New DataTable()
  TotalDistribution = 0
  TotalDistributionOriginal = 0

  ' DataTable
  With dt.Columns
    .Add("Account", GetType(String))
    .Add("Name", GetType(String))
    .Add("Description", GetType(String))
    .Add("Type", GetType(String))
    .Add("Balance", GetType(Decimal))
    .Add("AvgDailyBal", GetType(Decimal))
    .Add("Original", GetType(Decimal))
    .Add("Distribution", GetType(Decimal))
  End With

  ' Add to Summary Table
  For Each IncomeDistributionItem In incomeDistribution.Items
    DataRow = dt.NewRow()
    With IncomeDistributionItem
      DataRow!Account = .AccountId
      DataRow!Name = .Name
      DataRow!Description = .Description   
      DataRow!Type = .AccountTypeId
      DataRow!Balance = .Balance
      DataRow!AvgDailyBal = .AverageDailyBalance
      DataRow!Original = .DistributionOriginal
      DataRow!Distribution = .Distribution
    End With

    ' Totals
    TotalDistribution += IncomeDistributionItem.Distribution
    TotalDistributionOriginal += IncomeDistributionItem.DistributionOriginal
    
    ' Add Row
    dt.Rows.Add(DataRow)
  Next

  ' Convert DataTable to Summary Table
  If Success Then
    SummaryTable = finBL.Utilities.DataTableToSummaryTable(dt)
  End If

  ' Update colour for rows where the Distribution has been changed
  If Success Then
    For Each SummaryTableRow In SummaryTable.Rows
      If SummaryTableRow.RowClass = iseSummaryTableRowClass.None Then
        If CDec(SummaryTableRow.Cells.Item(6).Value) &lt;&gt; CDec(SummaryTableRow.Cells.Item(7).Value) Then
          SummaryTableRow.BackgroundColour = "#CAFACA"
          SummaryTableRow.Cells.Item(7).CellClass = iseSummaryTableCellClass.NormalBold
        End If
      End If
    Next 
  End If
  
  ' Totals Row
  If Success Then
    With SummaryTable.Rows.Add(iseSummaryTableRowClass.FooterBold).Cells
      .AddInteger(incomeDistribution.Items.Count).TextAlign = iseSummaryTableCellTextAlign.Left
      .AddText("")
      .AddText("")
      .AddText("")
      .AddCurrency(incomeDistribution.GetTotalBalance())
      .AddCurrency(incomeDistribution.GetTotalAverageDailyBalance())
      .AddCurrency(TotalDistributionOriginal)
      .AddCurrency(TotalDistribution)
    End With
  End If
  
  ' Add Summary Table
  If Success Then
    summaryTables.Add("Summary", SummaryTable)
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to get Income Distribution Summary.")
  End If

  Return Success

End Function
  
''' &lt;summary&gt;
'''  Update a finIncomeDistribution object from the IncomeDistribution Json Class.
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function UpdateIncomeDistributionFromJsonClass(distribution As IncomeDistribution,
                                                      ByRef incomeDistribution As finIncomeDistribution) As Boolean
  
  Dim DistributionItem As IncomeDistributionItem
  Dim IncomeDistributionItem As finIncomeDistributionItem
  Dim MatchedAccountCount As Integer
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise ByRef Parameters
  MatchedAccountCount = 0
  
  ' Reset all Distributions to 0 to ensure that any new items (i.e. in this Refresh, but not the previous) are NOT included. Valid items will be updated after this step
  If Success Then
    For Each IncomeDistributionItem In IncomeDistribution.IncomeDistributionItems
      IncomeDistributionItem.Distribution = 0
    Next 
  End If
  
  ' Update Income Distribution with Json object
  If Success Then
    For Each DistributionItem In Distribution.Items
      For Each IncomeDistributionItem In incomeDistribution.IncomeDistributionItems
        With IncomeDistributionItem
          If DistributionItem.AccountPk = .AccountPk Then
            MatchedAccountCount += 1
            .Distribution = DistributionItem.Distribution
            Exit For
          End If
        End With
      Next 
    Next
    
    ' Validate
    If distribution.Items.Count &lt;&gt; MatchedAccountCount Then
      Success = False
      finBL.Error.ErrorBegin("Record mismatch. The collection may have changed since it was originally loaded. Please restart the Income Distribution Process again.")
    End If
  End If
  
  ' Update Final Details
  If Success Then
    With incomeDistribution
      .TransactionTypeId = distribution.TransactionTypeId
      .TransactionBatchId = distribution.TransactionBatchId
      .TransactionDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(distribution.TransactionDate)
      .TransactionReference = distribution.TransactionReference
      .TransactionNotes = distribution.TransactionNotes
      .SaveToBatch = distribution.SaveToBatch
    End With
  End If
  
  Return Success
                                                    
End Function

''' &lt;summary&gt;
'''  Print Income Distribution List.
''' &lt;/summary&gt;
Private Function PrintIncomeDistributionList(parametersJson As String,
                                             ByRef returnValue As String) As Boolean

  Dim Distribution As IncomeDistribution
  Dim FileDownloadInfo As finFileDownloadInfo
  Dim FileName As String
  Dim IncomeDistribution As finIncomeDistribution
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = False
  
  ' Parse Parameters
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateIncomeDistribution(WizardFinishParameters, IncomeDistribution)
  Else 
    Success = False
  End If
  
  ' Get Income Distribution Object
  If Success Then
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(WizardFinishParameters.RefreshData, GetType(IncomeDistribution), obj) Then
      Distribution = DirectCast(obj, IncomeDistribution)
    Else 
      Success = False
    End If
  End If
  
  ' Get Summary
  If Success Then
    FileName = finBL.Runtime.FileUtilities.GetTemporaryFileName("ProcessIncomeDistributionSummary", "pdf")
    
    If CreateIncomeDistributionSummaryPdf(Distribution, FileName) Then
      FileDownloadInfo = finBL.CreateFileDownloadInfo()
      With FileDownloadInfo
        If .LoadFile(FileName) Then
          returnValue = .ToXmlString()
        Else
          Success = False
        End If
      End With
    Else 
      Success = False
    End If
    
    ' Delete temporary file
    If finBL.Runtime.FileUtilities.FileExists(FileName) Then
      finBL.Runtime.FileUtilities.DeleteFile(FileName, True)
    End If
  End If
  
  Return Success
                                             
End Function

  
''' &lt;summary&gt;
'''  Wizard Initialisation Information
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' Current Processes
  Public CurrentProcesses As New List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Public ProcessId As String

  ' Record

  ' Lists
  Public AccountUsers As New List(Of AccountUser)
  Public TransactionTypes As New List(Of TransactionType)
  Public TransactionTypeSqlWhere As String

  ' Advanced
  Public PageGeneralHasAdvanced As Boolean
  Public ShowAccountManagers As String
  Public ShowAccounts As String
  Public ShowAccountTypes As String
  Public ShowBranches As String  
  Public ShowDepartments As String
  Public ShowEntities As String
  Public ShowBrokers As String
  Public ShowDealers As String
  Public ShowPools As String
  Public ShowProductTypes As String
  Public ShowAccountUser As String
  Public ShowRangesHeading As String

  ' Permissions
  Public CanSaveToBatch As Boolean

  ' Configuration
  Public AutoCommit As Boolean
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean

End Class



''' &lt;summary&gt;
'''  Finish details.
''' &lt;/summary&gt;
Public Class WizardFinishDetails

  Public ProcessId As String

  Public Sub New(processId As String)

    Me.ProcessId = processId

  End Sub

End Class



''' &lt;summary&gt;
'''  Wizard Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters

  ' Parameters
  Public PeriodFrom As Date?
  Public PeriodTo As Date?

  Public IncomeReceived As Decimal
  Public ExpensesIncurred As Decimal
  Public InterimDistribution As Decimal
  
  Public TransactionTypeId As String
  Public TransactionBatchId As String
  Public TransactionDate As Date?
  Public TransactionReference As String
  Public TransactionNotes As String
  
  Public SaveToBatch As Boolean
  
  ' Ranges
  Public RangeAccountManagers As String
  Public RangeAccounts As String
  Public RangeAccountTypes As String
  Public RangeBranches As String
  Public RangeDepartments As String
  Public RangeEntities As String
  Public RangeExternalPartiesBrokers As String
  Public RangeExternalPartiesDealers As String
  Public RangePools As String
  Public RangeProductTypes As String
  Public RangeAccountUser0 As String
  Public RangeAccountUser1 As String
  Public RangeAccountUser2 As String
  Public RangeAccountUser3 As String
  Public RangeAccountUser4 As String
  Public RangeAccountUser5 As String
  Public RangeAccountUser6 As String
  Public RangeAccountUser7 As String
  Public RangeAccountUser8 As String
  Public RangeAccountUser9 As String
  Public RangeAccountUser10 As String
  Public RangeAccountUser11 As String
  Public RangeAccountUser12 As String
  Public RangeAccountUser13 As String
  Public RangeAccountUser14 As String
  Public RangeAccountUser15 As String
  Public RangeAccountUser16 As String
  Public RangeAccountUser17 As String
  Public RangeAccountUser18 As String
  Public RangeAccountUser19 As String

  ' Other
  Public ProcessId As String
  Public RefreshData As String

End Class



''' &lt;summary&gt;
'''  Validation details.
''' &lt;/summary&gt;
Public Class WizardValidateResponse

  Public Data As Object
  Public FailedControlId As String
  Public FailedMessage As String

  Public Sub New(data As Object,
                 failedMessage As String,
                 failedControlId As String)

    Me.Data = data
    Me.FailedMessage = failedMessage
    Me.FailedControlId = failedControlId

  End Sub

End Class



''' &lt;summary&gt;
'''  Income Distribution.
''' &lt;/summary&gt;
Public Class IncomeDistribution
  
  ' Properties
  Public PeriodFrom As Date
  Public PeriodTo As Date
  Public PeriodDays As Integer
  
  Public IncomeReceived As Decimal
  Public ExpensesIncurred As Decimal
  Public FundsAvailableToDistribute As Decimal
  Public InterimDistribution As Decimal
  Public NetDistribution As Decimal
  
  Public TransactionTypeId As String
  Public TransactionBatchId As String
  Public TransactionDate As Date?
  Public TransactionReference As String
  Public TransactionNotes As String
  
  Public SaveToBatch As Boolean
  
  ' Ranges
  Public RangeAccountManagers As String
  Public RangeAccounts As String
  Public RangeAccountTypes As String
  Public RangeBranches As String
  Public RangeDepartments As String
  Public RangeEntities As String
  Public RangeExternalPartiesBrokers As String
  Public RangeExternalPartiesBrokersIncludeSub As Boolean
  Public RangeExternalPartiesDealers As String
  Public RangeExternalPartiesDealersIncludeSub As Boolean
  Public RangePools As String
  Public RangeProductTypes As String
  Public RangeAccountUser0 As String
  Public RangeAccountUser1 As String
  Public RangeAccountUser2 As String
  Public RangeAccountUser3 As String
  Public RangeAccountUser4 As String
  Public RangeAccountUser5 As String
  Public RangeAccountUser6 As String
  Public RangeAccountUser7 As String
  Public RangeAccountUser8 As String
  Public RangeAccountUser9 As String
  Public RangeAccountUser10 As String
  Public RangeAccountUser11 As String
  Public RangeAccountUser12 As String
  Public RangeAccountUser13 As String
  Public RangeAccountUser14 As String
  Public RangeAccountUser15 As String
  Public RangeAccountUser16 As String
  Public RangeAccountUser17 As String
  Public RangeAccountUser18 As String
  Public RangeAccountUser19 As String
  
  ' Distribution Items
  Public Items As New List(Of IncomeDistributionItem)
  
  ' Flags
  Public ReportRequiresPrinting As Boolean
  
  Public Sub New()
  End Sub
  
  Public Sub New(incomeDistribution As finIncomeDistribution)
    
    Dim IncomeDistributionItem As finIncomeDistributionItem
    
    With incomeDistribution
      Me.PeriodFrom = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.PeriodDateFrom)
      Me.PeriodTo = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.PeriodDateTo)
      Me.PeriodDays = .PeriodDays
      
      Me.IncomeReceived = .IncomeReceived
      Me.ExpensesIncurred = .ExpensesIncurred
      Me.FundsAvailableToDistribute = .FundsAvailableToDistribute
      Me.InterimDistribution = .InterimDistribution
      Me.NetDistribution = .NetDistribution
      
      Me.TransactionTypeId = .TransactionTypeId
      Me.TransactionBatchId = .TransactionBatchId
      Me.TransactionDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.TransactionDate)
      Me.TransactionReference = .TransactionReference
      Me.TransactionNotes = .TransactionNotes
      
      Me.SaveToBatch = .SaveToBatch
      
      Me.RangeAccountManagers = .RangeAccountManagers
      Me.RangeAccounts = .RangeAccounts
      Me.RangeAccountTypes = .RangeAccountTypes
      Me.RangeBranches = .RangeBranches
      Me.RangeDepartments = .RangeDepartments
      Me.RangeEntities = .RangeEntities
      Me.RangeExternalPartiesBrokers = .RangeExternalPartiesBrokers
      Me.RangeExternalPartiesBrokersIncludeSub = .RangeExternalPartiesBrokersIncludeSub
      Me.RangeExternalPartiesDealers = .RangeExternalPartiesDealers
      Me.RangeExternalPartiesDealersIncludeSub = .RangeExternalPartiesDealersIncludeSub
      Me.RangePools = .RangePools
      Me.RangeProductTypes = .RangeProductTypes
      Me.RangeAccountUser0 = .RangeAccountUser(0)
      Me.RangeAccountUser1 = .RangeAccountUser(1)
      Me.RangeAccountUser2 = .RangeAccountUser(2)
      Me.RangeAccountUser3 = .RangeAccountUser(3)
      Me.RangeAccountUser4 = .RangeAccountUser(4)
      Me.RangeAccountUser5 = .RangeAccountUser(5)
      Me.RangeAccountUser6 = .RangeAccountUser(6)
      Me.RangeAccountUser7 = .RangeAccountUser(7)
      Me.RangeAccountUser8 = .RangeAccountUser(8)
      Me.RangeAccountUser9 = .RangeAccountUser(9)
      Me.RangeAccountUser10 = .RangeAccountUser(10)
      Me.RangeAccountUser11 = .RangeAccountUser(11)
      Me.RangeAccountUser12 = .RangeAccountUser(12)
      Me.RangeAccountUser13 = .RangeAccountUser(13)
      Me.RangeAccountUser14 = .RangeAccountUser(14)
      Me.RangeAccountUser15 = .RangeAccountUser(15)
      Me.RangeAccountUser16 = .RangeAccountUser(16)
      Me.RangeAccountUser17 = .RangeAccountUser(17)
      Me.RangeAccountUser18 = .RangeAccountUser(18)
      Me.RangeAccountUser19 = .RangeAccountUser(19)
      
      ' Items
      For Each IncomeDistributionItem In incomeDistribution.IncomeDistributionItems
        Me.Items.Add(New IncomeDistributionItem(IncomeDistributionItem))
      Next
      
      ' Flags
      Me.ReportRequiresPrinting = True
    End With
    
  End Sub
  
  ''' &lt;summary&gt;
  '''  Get Values from the Distribution which require calculation.
  ''' &lt;/summary&gt;
  Public Sub GetCalculationValues(ByRef actualDistribution As Decimal,
                                  ByRef distributionDifferenceText As String,
                                  ByRef distributionRate As Double,
                                  ByRef periodDaysText As String)
    
    Dim DistributionItem As IncomeDistributionItem  
    Dim TotalAverageDailyBalance As Decimal
                             
    ' Initialise ByRef Parameters
    actualDistribution = 0
    distributionDifferenceText = ""
    distributionRate = 0    
    periodDaysText = ""
    
    ' Perform Calculations
    For Each DistributionItem In Me.Items
      actualDistribution += DistributionItem.Distribution
      
      If DistributionItem.Distribution &lt;&gt; 0 Then
        TotalAverageDailyBalance += DistributionItem.AverageDailyBalance
      End If
    Next  
    
    ' Distribution Difference
    If actualDistribution - Me.NetDistribution &lt;&gt; 0 Then
      DistributionDifferenceText = "difference " &amp; finBLShared.FormatCurrency(actualDistribution - Me.NetDistribution, True, False)
    End If
    
    ' Distribution Rate
    If Me.PeriodDays = 0 OrElse TotalAverageDailyBalance = 0 Then
      distributionRate = 0
    Else 
      distributionRate = (actualDistribution / TotalAverageDailyBalance * 365 / Me.PeriodDays * 100)
    End If
    
    ' Period Days
    If Me.PeriodDays = 1 Then
      periodDaysText = "1 Day"
    Else 
      periodDaysText = Me.PeriodDays &amp; " Days"
    End If 
  End Sub
  
  ''' &lt;summary&gt;
  '''  Get the total Average Daily Balance for the Income Distribution.
  ''' &lt;/summary&gt;
  Public Function GetTotalAverageDailyBalance() As Decimal
    
    Dim Item As IncomeDistributionItem
    Dim Total As Decimal
    
    ' Initialise
    Total = 0
    
    ' Sum Distribution
    For Each Item In Me.Items
      If Item.Distribution &lt;&gt; 0 Then
        Total += Item.AverageDailyBalance
      End If
    Next
    
    Return Total
    
  End Function
  
  ''' &lt;summary&gt;
  '''  Get the total Balance for the Income Distribution.
  ''' &lt;/summary&gt;
  Public Function GetTotalBalance() As Decimal
    
    Dim Item As IncomeDistributionItem
    Dim Total As Decimal
    
    ' Initialise
    Total = 0
    
    ' Sum Distribution
    For Each Item In Me.Items
      If Item.Distribution &lt;&gt; 0 Then
        Total += Item.Balance
      End If
    Next
    
    Return Total
    
  End Function
  
End Class



''' &lt;summary&gt;
'''  Income Distribution Items.
''' &lt;/summary&gt;
Public Class IncomeDistributionItem
  
  ' Properties
  Public AccountId As String
  Public AccountPk As Integer
  Public AccountTypeId As String
  Public AverageDailyBalance As Decimal
  Public Balance As Decimal
  Public Description As String
  Public Distribution As Decimal
  Public DistributionOriginal As Decimal
  Public Name As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(incomeDistributionItem As finIncomeDistributionItem)
    
    With incomeDistributionItem
      Me.AccountId = .AccountId
      Me.AccountPk = .AccountPk
      Me.AverageDailyBalance = .AverageDailyBalance
      Me.Balance = .BalanceClosing
      Me.Description = .AccountDescription
      Me.Distribution = .Distribution
      Me.DistributionOriginal = .DistributionOriginal
      Me.Name = .AccountName
      
      If finBLShared.AccountTypes.ExistsPk(.AccountTypePk) Then
        Me.AccountTypeId = finBLShared.AccountTypes.ItemByPk(.AccountTypePk).AccountTypeId
      End If  
    End With
    
  End Sub
  
End Class


''' &lt;summary&gt;
'''  Represents an Account User field
''' &lt;/summary&gt;
Public Class AccountUser
  
  Public Caption As String
  Public IdField As String
  Public RangeLookupSql As String
  
  Public Sub New(index As Integer)
    
    Me.Caption = finBLShared.Settings.AccountUser(index)
    Me.IdField = "User" &amp; index            
    Me.RangeLookupSql = finBLShared.HtmlWidgetUtilities.EncryptSql(GetAccountUserSqlWhere(Me.IdField))
                 
  End Sub
  
End Class


''' &lt;summary&gt;
'''  Transaction Type.
''' &lt;/summary&gt;
Public Class TransactionType
  
  Public TransactionTypeId As String
  Public Reference As String
  Public Notes As String
  
  Public Sub New(transactionTypeRO As finTransactionTypeRO)
    
    With transactionTypeRO
      Me.TransactionTypeId = .TransactionTypeId
      Me.Reference = .TransactionReferenceResolved
      Me.Notes = .TransactionNotesResolved
    End With
    
  End Sub
  
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "IncomeDistribution".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
/* Total Summary */
.value-summary {
  display:flex;
  flex-direction:row;

  div {
    font-size:11px;

    &gt; b {
      font-size:14px;
    }
  }
}

/* Small device portrait */
@media screen and (max-width:640px) {
  .value-summary {
    flex-direction:column;
    font-size:12px;
  }
}
&lt;/style&gt;

&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Income Distributions you have processed."&gt;Recent Income Distribution Processing&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Select Income Distribution options."&gt;Income Distribution options&lt;/li&gt;
        &lt;li tabId="Items" tooltipText="Review the Account Distributions."&gt;Income Distribution&lt;/li&gt;
        &lt;li tabId="TransactionDetails" tooltipText="Enter Income Distribution Transaction details."&gt;Transaction Details&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Current Processes --&gt;
    &lt;div id="pageCurrentProcesses"&gt;
      &lt;div id="gridCurrentProcesses"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:14em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDistributionPeriod"&gt;Specify the Distribution Period&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePeriodFrom"&gt;Period From:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePeriodFrom" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePeriodTo"&gt;Period To:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePeriodTo" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDistributionAmount"&gt;Specify Distribution Amounts&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numIncomeReceived"&gt;Income Received:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numIncomeReceived" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numExpensesIncurred"&gt;Less Expenses Incurred:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numExpensesIncurred" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numFundsAvailableToDistribute"&gt;Funds Available:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numFundsAvailableToDistribute" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numInterimDistribution"&gt;Interim Distribution:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numInterimDistribution" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numNetDistribution"&gt;Net Distribution:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numNetDistribution" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="RangesHeading"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRanges"&gt;Enter ranges to filter information&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountManagers"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountManagers"&gt;Account&amp;nbsp;Managers:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountManagers" lookupCaption="Account Managers" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Accounts"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccounts"&gt;Accounts:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccounts" lookupCaption="Accounts" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountTypes"&gt;Account&amp;nbsp;Types:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountTypes" lookupCaption="Account Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Branches"&gt;
          &lt;th&gt;&lt;label for="txtRangeBranches"&gt;Branches:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeBranches" lookupCaption="Branches" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Departments"&gt;
          &lt;th&gt;&lt;label for="txtRangeDepartments"&gt;Departments:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeDepartments" lookupCaption="Departments" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Entities"&gt;
          &lt;th&gt;&lt;label for="txtRangeEntities"&gt;Entities:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeEntities" lookupCaption="Entities" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Brokers"&gt;
          &lt;th&gt;&lt;label for="txtRangeExternalPartiesBrokers"&gt;Brokers:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeExternalPartiesBrokers" lookupCaption="Brokers" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Brokers"&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRangeExternalPartiesBrokersIncludeSub" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Dealers"&gt;
          &lt;th&gt;&lt;label for="txtRangeExternalPartiesDealers"&gt;Dealers:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeExternalPartiesDealers" lookupCaption="Dealers" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Dealers"&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRangeExternalPartiesDealersIncludeSub" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="Pools"&gt;
          &lt;th&gt;&lt;label for="txtRangePools"&gt;Pools:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangePools" lookupCaption="Pools" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ProductTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeProductTypes"&gt;Product&amp;nbsp;Types:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeProductTypes" lookupCaption="Product Types" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser0"&gt;Account&amp;nbsp;User&amp;nbsp;0:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser0" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser1"&gt;Account&amp;nbsp;User&amp;nbsp;1:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser1" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser2"&gt;Account&amp;nbsp;User&amp;nbsp;2:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser2" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser3"&gt;Account&amp;nbsp;User&amp;nbsp;3:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser3" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser4"&gt;Account&amp;nbsp;User&amp;nbsp;4:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser4" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser5"&gt;Account&amp;nbsp;User&amp;nbsp;5:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser5" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser6"&gt;Account&amp;nbsp;User&amp;nbsp;6:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser6" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser7"&gt;Account&amp;nbsp;User&amp;nbsp;7:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser7" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser8"&gt;Account&amp;nbsp;User&amp;nbsp;8:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser8" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser9"&gt;Account&amp;nbsp;User&amp;nbsp;9:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser9" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser10"&gt;Account&amp;nbsp;User&amp;nbsp;10:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser10" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser11"&gt;Account&amp;nbsp;User&amp;nbsp;11:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser11" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser12"&gt;Account&amp;nbsp;User&amp;nbsp;12:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser12" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser13"&gt;Account&amp;nbsp;User&amp;nbsp;13:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser13" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser14"&gt;Account&amp;nbsp;User&amp;nbsp;14:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser14" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser15"&gt;Account&amp;nbsp;User&amp;nbsp;15:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser15" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser16"&gt;Account&amp;nbsp;User&amp;nbsp;16:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser16" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser17"&gt;Account&amp;nbsp;User&amp;nbsp;17:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser17" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser18"&gt;Account&amp;nbsp;User&amp;nbsp;18:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser18" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="AccountUser"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountUser19"&gt;Account&amp;nbsp;User&amp;nbsp;19:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountUser19" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Update Items --&gt;
    &lt;div id="pageItems"&gt;
      &lt;div id="gridItems"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Transaction Details --&gt;
    &lt;div id="pageTransactionDetails"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:14em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDistributionPeriodRO"&gt;Distribution Period&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePeriodFromRO"&gt;Period From:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePeriodFromRO" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePeriodToRO"&gt;Period To:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePeriodToRO" /&gt; &lt;span id="spanPeriodDaysText" style="padding-left:4px;"&gt;&lt;/span&gt;&lt;/td&gt;
        &lt;/tr&gt;     
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDistributionAmountRO"&gt;Distribution Amounts&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;   
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numNetDistributionRO"&gt;Net Distribution:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numNetDistributionRO" /&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numTotalDistributionRO"&gt;Actual Distribution:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numTotalDistributionRO" /&gt; &lt;span id="spanDistributionDiff" style="padding-left:4px;"&gt;&lt;/span&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numDistributionRate"&gt;Distribution Rate:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numDistributionRate" /&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblTransaction"&gt;Specify the Transaction details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboTransactionType"&gt;Transaction Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboTransactionType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtTransactionBatchId"&gt;Batch Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtTransactionBatchId" /&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateTransaction"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateTransaction" /&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtTransactionReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtTransactionReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtTransactionNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtTransactionNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSaveToBatch"&gt;Save Distribution to a Transaction Batch?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkSaveToBatch" type="checkbox" &gt;&lt;/th&gt;
        &lt;/tr&gt; 
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPrint"&gt;Print the Income Distribution List Report&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;button id="cmdPrint" class="is-button small"&gt;Print&lt;/button&gt;&lt;/th&gt;
        &lt;/tr&gt; 
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Progress --&gt;
    &lt;div id="pageProgress" style="display:flex"&gt;
      &lt;div id="divProgress" class="progress-events"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdHistory" class="is-button" style="float:left"&gt;Recent&lt;/button&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Commit&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;

&lt;script&gt;
// Properties
var mRecord;
var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;

var mIncomeDistribution;

// Controls
var C = {
  //   Current Processes
  gridCurrentProcesses: null,

  //   General
  lblDistributionPeriod: null,
  datePeriodFrom: null,
  datePeriodTo: null,
  
  lblDistributionAmount: null,
  numIncomeReceived: null,
  numExpensesIncurred: null,
  numFundsAvailableToDistribute: null,
  numInterimDistribution: null,
  numNetDistribution: null,

  lblRanges: null,
  txtRangeAccountManagers: null,
  txtRangeAccounts: null,
  txtRangeAccountTypes: null,
  txtRangeBranches: null,
  txtRangeDepartments: null,
  txtRangeEntities: null,
  txtRangeExternalPartiesBrokers: null,
  chkRangeExternalPartiesBrokersIncludeSub: null,
  txtRangeExternalPartiesDealers: null,
  chkRangeExternalPartiesDealersIncludeSub: null,
  txtRangePools: null,
  txtRangeProductTypes: null,
  txtRangeAccountUser0: null,
  txtRangeAccountUser1: null,
  txtRangeAccountUser2: null,
  txtRangeAccountUser3: null,
  txtRangeAccountUser4: null,
  txtRangeAccountUser5: null,
  txtRangeAccountUser6: null,
  txtRangeAccountUser7: null,
  txtRangeAccountUser8: null,
  txtRangeAccountUser9: null,
  txtRangeAccountUser10: null,
  txtRangeAccountUser11: null,
  txtRangeAccountUser12: null,
  txtRangeAccountUser13: null,
  txtRangeAccountUser14: null,
  txtRangeAccountUser15: null,
  txtRangeAccountUser16: null,
  txtRangeAccountUser17: null,
  txtRangeAccountUser18: null,
  txtRangeAccountUser19: null,

  //   Items
  gridItems: null,

  //   Transaction Details
  lblDistributionPeriodRO: null,
  datePeriodFromRO: null,
  datePeriodToRO: null,
  spanPeriodDaysText: null,
  
  lblDistributionAmountRO: null,
  numNetDistributionRO: null,
  numTotalDistributionRO: null,
  spanDistributionDiff: null,
  numDistributionRate: null,
  
  lblTransaction: null,
  cboTransactionType: null,
  txtTransactionBatchId: null,
  dateTransaction: null,
  txtTransactionReference: null,
  txtTransactionNotes: null,
  
  lblSaveToBatch: null,
  chkSaveToBatch: null,
  
  lblPrint: null,
  cmdPrint: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

// Wizard Buttons
var cmdCancel;
var cmdBack;
var cmdNext;
var cmdFinish;

var cmdHistory;
var cmdAdvanced;

// Other
var mAccounts;
var mAdvancedVisible = false;
var mComplete = false;
var mFromRecent = false;
var mLastEventId = "";
var mLastProcessStatus = "";
var mLastRefreshParametersJson = "";
var mLastProcessSummaryJson = "";
var mMonitoringExisting = false;
var mProcessId;

// Initialise
$(function () {
  // Mobile optimisations
  $(window).resize(Form_Resize);

  // Controls
  //   General
  C.lblDistributionPeriod = widget.UI.Label("lblDistributionPeriod", {});
  C.datePeriodFrom = widget.UI.DateBox("datePeriodFrom", {
    allowBlank: false,
  });
  C.datePeriodTo = widget.UI.DateBox("datePeriodTo", {
    allowBlank: false,
  });
  
  C.lblDistributionAmount = widget.UI.Label("lblDistributionAmount", {});
  C.numIncomeReceived = widget.UI.NumberBox("numIncomeReceived", {
    allowBlank: false,
    minValue: 0,
    maxValue: 9999999999,
    
    onChange: Calculate,
  });
  C.numExpensesIncurred = widget.UI.NumberBox("numExpensesIncurred", {
    minValue: 0,
    maxValue: 9999999999,
    
    onChange: Calculate,
  });
  C.numFundsAvailableToDistribute = widget.UI.NumberBox("numFundsAvailableToDistribute", {
    readOnly: true,
    minValue: 0,
    maxValue: 9999999999,
  });
  C.numInterimDistribution = widget.UI.NumberBox("numInterimDistribution", {
    minValue: 0,
    maxValue: 9999999999,
    
    onChange: Calculate,
  });
  C.numNetDistribution = widget.UI.NumberBox("numNetDistribution", {
    fontBold: true,
    readOnly: true,    
    minValue: 0,
    maxValue: 9999999999,
  });

  C.lblRanges = widget.UI.Label("lblRanges", {});
  C.chkRangeExternalPartiesBrokersIncludeSub = widget.UI.CheckBox("chkRangeExternalPartiesBrokersIncludeSub", {
    caption: "Include Sub Brokers?",
  });
  C.chkRangeExternalPartiesDealersIncludeSub = widget.UI.CheckBox("chkRangeExternalPartiesDealersIncludeSub", {
    caption: "Include Sub Dealers?",
  });

  //   Transaction Details
  C.lblDistributionPeriodRO = widget.UI.Label("lblDistributionPeriodRO", {});
  C.datePeriodFromRO = widget.UI.DateBox("datePeriodFromRO", {
    readOnly: true,
  });
  C.datePeriodToRO = widget.UI.DateBox("datePeriodToRO", {
    readOnly: true,
  });
  C.spanPeriodDaysText = $("#spanPeriodDaysText");
  
  C.lblDistributionAmountRO = widget.UI.Label("lblDistributionAmountRO", {});
  C.numNetDistributionRO = widget.UI.NumberBox("numNetDistributionRO", {
    readOnly: true,
  });
  C.numTotalDistributionRO = widget.UI.NumberBox("numTotalDistributionRO", {
    readOnly: true,
  });
  C.spanDistributionDiff = $("#spanDistributionDiff");
  C.numDistributionRate = widget.UI.NumberBox("numDistributionRate", {
    decimals: 4,
    percentage: true,
    readOnly: true,
    width: "9em",
  });
  
  C.lblTransaction = widget.UI.Label("lblTransaction", {});
  C.cboTransactionType = widget.UI.DBCombo("cboTransactionType", {
    allowBlank: false,
    
    onChange: cboTransactionType_Change,
  });
  C.txtTransactionBatchId = widget.UI.TextBox("txtTransactionBatchId", {
    allowBlank: false,
    maxLength: 20,  
    
    onButtonClick: txtTransactionBatchId_ButtonClick,  
    onChange: txtTransactionBatchId_Change,
  });
  C.txtTransactionBatchId.ButtonsDefine([{ id: "Auto", icon: "Refresh", tooltipText: "Automatically generate a Batch Id and insert it into the field" }]);
  C.dateTransaction = widget.UI.DateBox("dateTransaction", {
    allowBlank: false,
    
    onChange: dateTransaction_Change,
  });
  C.txtTransactionReference = widget.UI.TextBox("txtTransactionReference", {
    maxLength: 20,
    
    onChange: txtTransactionReference_Change,
  });
  C.txtTransactionNotes = widget.UI.TextBox("txtTransactionNotes", {
    multiLine: true,
    rows: 2,
    
    onChange: txtTransactionNotes_Change,
  });
  
  C.lblSaveToBatch = widget.UI.Label("lblSaveToBatch", {});
  C.chkSaveToBatch = widget.UI.CheckBox("chkSaveToBatch", {
    caption: "Save Batch?",
    
    onChange: chkSaveToBatch_Change,
  });
  
  C.lblPrint = widget.UI.Label("lblPrint", {});
  C.cmdPrint = $("#cmdPrint");
  C.cmdPrint.click(PrintIncomeDistributionList);

  //   Progress
  C.divProgress = $("#divProgress");

  // Ranges
  for(var k in C) {
    if (k.startsWith("txtRange")) {
      C[k] = widget.UI.TextBox(k, {
        maxLength: 255,
        onButtonClick: txtRange_ButtonClick,
      });
      var buttons = [];

      // Lookup button
      buttons.push({id: "Lookup", icon: "Find", tooltipText: "Lookup"});

      // Define buttons
      C[k].ButtonsDefine(buttons);
    }
  }

  // Grids
  C.gridCurrentProcesses = widget.UI.Grid("gridCurrentProcesses", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridCurrentProcesses_Action,
    onAfterRowActivate: gridCurrentProcesses_AfterRowActivate,
    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

  C.gridItems = widget.UI.Grid("gridItems", {
    allowCellSelect: false,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridItems_Action,
    onAfterRowActivate: gridItems_AfterRowActivate,
    onBeforeCellUpdate: gridItems_BeforeCellUpdate,
    onFooterCellFormat: gridItems_FooterCellFormat,
    onInitialiseRow: gridItems_InitialiseRow,
  });

  // Create Widget form
  // NOTE: Hide by default for a cleaner startup
  frmMain = new widget.UI.Form("frmMain", { visible: false });

  // Create Tabs
  tabWizard = new widget.UI.Tabs("tabWizard", { style: "wizard" });

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdBack = $("#cmdBack");
  cmdNext = $("#cmdNext");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabWizard_Cancel);
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  cmdHistory = $("#cmdHistory");
  cmdHistory.click(function() { Form_ExecuteAction("Recent"); });

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(AdvancedToggle);

  // Handle Notifications
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Reset
  Form_Reset();
});

// ==========
// Form Reset
// ==========
function Form_Reset() {
  // Defaults

  // Set Tab
  tabWizard.SelectedTabId("General");

  // Resize
  Form_Resize();

  // Load Record (i.e., initialise wizard)
  Record_Load();
}

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mAccounts = null;
  mIncomeDistribution = null;

  // Hide content
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Initialising, please wait...");

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_CurrentProcesses = mRecord.CurrentProcesses;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mRecord.TransactionTypes, "TransactionTypeId");

      // Load Fields
      Fields_Load();

      // Notify if there are Current Processes
      var countCurrent = 0;
      var processIndex = -1;
      for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
        var item = mRecord_CurrentProcesses[i];

        // Process
        if (mRecord.ProcessId &amp;&amp; mRecord.ProcessId == item.ProcessId) {
          processIndex = i;
        }

        // Status
        switch (item.Status) {
          case "Pending":
          case "PendingCommit":
          case "InProgress":
          case "InProgressRefreshComplete":
          case "InProgressCancelRequested":
            countCurrent += 1;
            break;
        }
      }
      if (processIndex != -1) {
        ViewExistingProcess(processIndex);
      }
      else if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing incomplete Income Distribution Processes that you have started and are not yet complete.\n\nYou can review these or use the 'Next &gt;' button to begin a new instance of Income Distribution.", { heading: "Income Distribution still Processing", icon: "MonitorCategory"} );
      }
    },

    // Fail
    function (message) {
      widget.UI.MsgBoxAlert("fail: " + message);
      Fields_Load();
    }
  );
}

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // Current Processes
    // NOTE: Bind here since this is the first page
    gridCurrentProcesses_Refresh();

    // General    
  }

  // Unblock UI
  widget.UI.Unblock();

  // Update Controls
  Calculate();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// =============
// Fields Update
// =============
function Fields_Update() {
  // Information Lists

  // Lists
  if (mRecord) {
    C.cboTransactionType.RefreshFromStandardRange("TransactionTypes", mRecord.TransactionTypeSqlWhere);
  }

  // Controls
  if(mRecord) {
    // General
    if (mRecord.ShowAccountUser != "False") {
      (mRecord.AccountUsers[0].Caption) ? C.txtRangeAccountUser0.Caption(mRecord.AccountUsers[0].Caption + ":") : C.txtRangeAccountUser0.VisibleRow(false);
      (mRecord.AccountUsers[1].Caption) ? C.txtRangeAccountUser1.Caption(mRecord.AccountUsers[1].Caption + ":") : C.txtRangeAccountUser1.VisibleRow(false);
      (mRecord.AccountUsers[2].Caption) ? C.txtRangeAccountUser2.Caption(mRecord.AccountUsers[2].Caption + ":") : C.txtRangeAccountUser2.VisibleRow(false);
      (mRecord.AccountUsers[3].Caption) ? C.txtRangeAccountUser3.Caption(mRecord.AccountUsers[3].Caption + ":") : C.txtRangeAccountUser3.VisibleRow(false);
      (mRecord.AccountUsers[4].Caption) ? C.txtRangeAccountUser4.Caption(mRecord.AccountUsers[4].Caption + ":") : C.txtRangeAccountUser4.VisibleRow(false);
      (mRecord.AccountUsers[5].Caption) ? C.txtRangeAccountUser5.Caption(mRecord.AccountUsers[5].Caption + ":") : C.txtRangeAccountUser5.VisibleRow(false);
      (mRecord.AccountUsers[6].Caption) ? C.txtRangeAccountUser6.Caption(mRecord.AccountUsers[6].Caption + ":") : C.txtRangeAccountUser6.VisibleRow(false);
      (mRecord.AccountUsers[7].Caption) ? C.txtRangeAccountUser7.Caption(mRecord.AccountUsers[7].Caption + ":") : C.txtRangeAccountUser7.VisibleRow(false);
      (mRecord.AccountUsers[8].Caption) ? C.txtRangeAccountUser8.Caption(mRecord.AccountUsers[8].Caption + ":") : C.txtRangeAccountUser8.VisibleRow(false);
      (mRecord.AccountUsers[9].Caption) ? C.txtRangeAccountUser9.Caption(mRecord.AccountUsers[9].Caption + ":") : C.txtRangeAccountUser9.VisibleRow(false);
      (mRecord.AccountUsers[10].Caption) ? C.txtRangeAccountUser10.Caption(mRecord.AccountUsers[10].Caption + ":") : C.txtRangeAccountUser10.VisibleRow(false);
      (mRecord.AccountUsers[11].Caption) ? C.txtRangeAccountUser11.Caption(mRecord.AccountUsers[11].Caption + ":") : C.txtRangeAccountUser11.VisibleRow(false);
      (mRecord.AccountUsers[12].Caption) ? C.txtRangeAccountUser12.Caption(mRecord.AccountUsers[12].Caption + ":") : C.txtRangeAccountUser12.VisibleRow(false);
      (mRecord.AccountUsers[13].Caption) ? C.txtRangeAccountUser13.Caption(mRecord.AccountUsers[13].Caption + ":") : C.txtRangeAccountUser13.VisibleRow(false);
      (mRecord.AccountUsers[14].Caption) ? C.txtRangeAccountUser14.Caption(mRecord.AccountUsers[14].Caption + ":") : C.txtRangeAccountUser14.VisibleRow(false);
      (mRecord.AccountUsers[15].Caption) ? C.txtRangeAccountUser15.Caption(mRecord.AccountUsers[15].Caption + ":") : C.txtRangeAccountUser15.VisibleRow(false);
      (mRecord.AccountUsers[16].Caption) ? C.txtRangeAccountUser16.Caption(mRecord.AccountUsers[16].Caption + ":") : C.txtRangeAccountUser16.VisibleRow(false);
      (mRecord.AccountUsers[17].Caption) ? C.txtRangeAccountUser17.Caption(mRecord.AccountUsers[17].Caption + ":") : C.txtRangeAccountUser17.VisibleRow(false);
      (mRecord.AccountUsers[18].Caption) ? C.txtRangeAccountUser18.Caption(mRecord.AccountUsers[18].Caption + ":") : C.txtRangeAccountUser18.VisibleRow(false);
      (mRecord.AccountUsers[19].Caption) ? C.txtRangeAccountUser19.Caption(mRecord.AccountUsers[19].Caption + ":") : C.txtRangeAccountUser19.VisibleRow(false);
    }
    
    // Transaction Details
    if (!mRecord.CanSaveToBatch) {
      C.lblSaveToBatch.VisibleRow(false);
      C.chkSaveToBatch.VisibleRow(false);
    }
  
    // Initialise Advanced
    AdvancedInitialise();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

  // Show content
  frmMain.Visible(mRecord != null);

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess() {
  if (mIncomeDistribution) {
    // Controls
    C.datePeriodFrom.Value(mIncomeDistribution.PeriodFrom);
    C.datePeriodTo.Value(mIncomeDistribution.PeriodTo);
    
    C.numIncomeReceived.Value(mIncomeDistribution.IncomeReceived);
    C.numExpensesIncurred.Value(mIncomeDistribution.ExpensesIncurred);
    C.numFundsAvailableToDistribute.Value(mIncomeDistribution.FundsAvailableToDistribute);
    C.numInterimDistribution.Value(mIncomeDistribution.InterimDistribution);
    C.numNetDistribution.Value(mIncomeDistribution.NetDistribution);

    // Ranges
    C.txtRangeAccountManagers.Text(mIncomeDistribution.RangeAccountManagers);
    C.txtRangeAccounts.Text(mIncomeDistribution.RangeAccounts);   
    C.txtRangeAccountTypes.Text(mIncomeDistribution.RangeAccountTypes); 
    C.txtRangeBranches.Text(mIncomeDistribution.RangeBranches);   
    C.txtRangeDepartments.Text(mIncomeDistribution.RangeDepartments);
    C.txtRangeEntities.Text(mIncomeDistribution.RangeEntities); 
    C.txtRangeExternalPartiesBrokers.Text(mIncomeDistribution.RangeExternalPartiesBrokers);
    C.chkRangeExternalPartiesBrokersIncludeSub.Value(mIncomeDistribution.RangeExternalPartiesBrokersIncludeSub);
    C.txtRangeExternalPartiesDealers.Text(mIncomeDistribution.RangeExternalPartiesDealers);
    C.chkRangeExternalPartiesDealersIncludeSub.Value(mIncomeDistribution.RangeExternalPartiesDealersIncludeSub);
    C.txtRangePools.Text(mIncomeDistribution.RangePools);
    C.txtRangeProductTypes.Text(mIncomeDistribution.RangeProductTypes);
    C.txtRangeAccountUser0.Text(mIncomeDistribution.RangeAccountUser0);
    C.txtRangeAccountUser1.Text(mIncomeDistribution.RangeAccountUser1);
    C.txtRangeAccountUser2.Text(mIncomeDistribution.RangeAccountUser2);
    C.txtRangeAccountUser3.Text(mIncomeDistribution.RangeAccountUser3);
    C.txtRangeAccountUser4.Text(mIncomeDistribution.RangeAccountUser4);
    C.txtRangeAccountUser5.Text(mIncomeDistribution.RangeAccountUser5);
    C.txtRangeAccountUser6.Text(mIncomeDistribution.RangeAccountUser6);
    C.txtRangeAccountUser7.Text(mIncomeDistribution.RangeAccountUser7);
    C.txtRangeAccountUser8.Text(mIncomeDistribution.RangeAccountUser8);
    C.txtRangeAccountUser9.Text(mIncomeDistribution.RangeAccountUser9);
    C.txtRangeAccountUser10.Text(mIncomeDistribution.RangeAccountUser10);
    C.txtRangeAccountUser11.Text(mIncomeDistribution.RangeAccountUser11);
    C.txtRangeAccountUser12.Text(mIncomeDistribution.RangeAccountUser12);
    C.txtRangeAccountUser13.Text(mIncomeDistribution.RangeAccountUser13);
    C.txtRangeAccountUser14.Text(mIncomeDistribution.RangeAccountUser14);
    C.txtRangeAccountUser15.Text(mIncomeDistribution.RangeAccountUser15);
    C.txtRangeAccountUser16.Text(mIncomeDistribution.RangeAccountUser16);
    C.txtRangeAccountUser17.Text(mIncomeDistribution.RangeAccountUser17);
    C.txtRangeAccountUser18.Text(mIncomeDistribution.RangeAccountUser18);
    C.txtRangeAccountUser19.Text(mIncomeDistribution.RangeAccountUser19);

    // Advanced
    if (!mAdvancedVisible) {
      var toggle = false;
      
      if (mIncomeDistribution.RangeAccountManagers &amp;&amp; mIncomeDistribution.RangeAccountManagers.length != 0 &amp;&amp; mRecord.ShowAccountManagers.toUpperCase() != "TRUE") toggle = true;
      if (mIncomeDistribution.RangeAccounts &amp;&amp; mIncomeDistribution.RangeAccounts.length != 0 &amp;&amp; mRecord.ShowAccounts.toUpperCase() != "TRUE") toggle = true;   
      if (mIncomeDistribution.RangeAccountTypes &amp;&amp; mIncomeDistribution.RangeAccountTypes.length != 0 &amp;&amp; mRecord.ShowAccountTypes.toUpperCase() != "TRUE") toggle = true;   
      if (mIncomeDistribution.RangeBranches &amp;&amp; mIncomeDistribution.RangeBranches.length != 0 &amp;&amp; mRecord.ShowBranches.toUpperCase() != "TRUE") toggle = true;            
      if (mIncomeDistribution.RangeDepartments &amp;&amp; mIncomeDistribution.RangeDepartments.length != 0 &amp;&amp; mRecord.ShowDepartments.toUpperCase() != "TRUE") toggle = true;      
      if (mIncomeDistribution.RangeEntities &amp;&amp; mIncomeDistribution.RangeEntities.length != 0 &amp;&amp; mRecord.ShowEntities.toUpperCase() != "TRUE") toggle = true;      
      if (mIncomeDistribution.RangeExternalPartiesBrokers &amp;&amp; mIncomeDistribution.RangeExternalPartiesBrokers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesBrokers.toUpperCase() != "TRUE") toggle = true;    
      if (mIncomeDistribution.RangeExternalPartiesDealers &amp;&amp; mIncomeDistribution.RangeExternalPartiesDealers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesDealers.toUpperCase() != "TRUE") toggle = true;    
      if (mIncomeDistribution.RangePools &amp;&amp; mIncomeDistribution.RangePools.length != 0 &amp;&amp; mRecord.ShowPools.toUpperCase() != "TRUE") toggle = true;   
      if (mIncomeDistribution.RangeProductTypes &amp;&amp; mIncomeDistribution.RangeProductTypes.length != 0 &amp;&amp; mRecord.ShowProductTypes.toUpperCase() != "TRUE") toggle = true;   

      // Toggle
      if (toggle) AdvancedToggle();
    }
    
    // Transaction Details
    C.cboTransactionType.Text(mIncomeDistribution.TransactionTypeId);
    C.txtTransactionBatchId.Text(mIncomeDistribution.TransactionBatchId);
    C.dateTransaction.Value(mIncomeDistribution.TransactionDate);
    C.txtTransactionReference.Text(mIncomeDistribution.TransactionReference);
    C.txtTransactionNotes.Text(mIncomeDistribution.TransactionNotes);
    C.chkSaveToBatch.Value(mIncomeDistribution.SaveToBatch);
  }
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "TransactionDetails":
        pageTransactionDetails_Refresh();
        break;
        
      default:
        break;
    }
  }

  // Always Refresh Current Processes, even when moving back
  if (newTab == 0) {
    if (!mRecord_CurrentProcesses) pageCurrentProcesses_Refresh();
  }

  // Make Tab it
  tabWizard.SelectedTabIndex(newTab);

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "CurrentProcesses":
      // Reset from recent flag
      mFromRecent = false;

      // Reset Objects
      mIncomeDistribution = null;
      mLastRefreshParametersJson = null;
      mProcessId = null;
      break;

    case "Items":
      // Refesh Update Items
      pageItems_Refresh();
      break;

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

  // Back, Next command buttons valid?
  tabWizard_UpdateButtons();

  // Resize Wizard
  tabWizard_Resize();

  // Focus
  switch (tabWizard.SelectedTabId()) {
    default:
      tabWizard.FocusFirst();
      break;
  }
}

// =========
// Calculate
// =========
function Calculate() {
  var total = C.numIncomeReceived.Value();
  
  total = (total - C.numExpensesIncurred.Value());  
  
  C.numFundsAvailableToDistribute.Value(total);
  
  total = (total - C.numInterimDistribution.Value());  
  
  C.numNetDistribution.Value(total);
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters(includeRefreshData) {
  var params = {
    processId: mProcessId,

    periodFrom: C.datePeriodFrom.Value(),
    periodTo: C.datePeriodTo.Value(),

    incomeReceived: C.numIncomeReceived.Value(),
    expensesIncurred: C.numExpensesIncurred.Value(),    
    interimDistribution: C.numInterimDistribution.Value(),    

    rangeAccountManagers: C.txtRangeAccountManagers.Text(),    
    rangeAccounts: C.txtRangeAccounts.Text(),
    rangeAccountTypes: C.txtRangeAccountTypes.Text(),
    rangeBranches: C.txtRangeBranches.Text(),
    rangeDepartments: C.txtRangeDepartments.Text(),
    rangeEntities: C.txtRangeEntities.Text(),
    rangeExternalPartiesBrokers: C.txtRangeExternalPartiesBrokers.Text(),
    rangeRangeExternalPartiesBrokersIncludeSub: C.chkRangeExternalPartiesBrokersIncludeSub.Value(),
    rangeExternalPartiesDealers: C.txtRangeExternalPartiesDealers.Text(),
    rangeRangeExternalPartiesDealersIncludeSub: C.chkRangeExternalPartiesDealersIncludeSub.Value(),
    rangePools: C.txtRangePools.Text(),
    rangeProductTypes: C.txtRangeProductTypes.Text(),
    rangeAccountUser0: C.txtRangeAccountUser0.Text(),
    rangeAccountUser1: C.txtRangeAccountUser1.Text(),
    rangeAccountUser2: C.txtRangeAccountUser2.Text(),
    rangeAccountUser3: C.txtRangeAccountUser3.Text(),
    rangeAccountUser4: C.txtRangeAccountUser4.Text(),
    rangeAccountUser5: C.txtRangeAccountUser5.Text(),
    rangeAccountUser6: C.txtRangeAccountUser6.Text(),
    rangeAccountUser7: C.txtRangeAccountUser7.Text(),
    rangeAccountUser8: C.txtRangeAccountUser8.Text(),
    rangeAccountUser9: C.txtRangeAccountUser9.Text(),
    rangeAccountUser10: C.txtRangeAccountUser10.Text(),
    rangeAccountUser11: C.txtRangeAccountUser11.Text(),
    rangeAccountUser12: C.txtRangeAccountUser12.Text(),
    rangeAccountUser13: C.txtRangeAccountUser13.Text(),
    rangeAccountUser14: C.txtRangeAccountUser14.Text(),
    rangeAccountUser15: C.txtRangeAccountUser15.Text(),
    rangeAccountUser16: C.txtRangeAccountUser16.Text(),
    rangeAccountUser17: C.txtRangeAccountUser17.Text(),
    rangeAccountUser18: C.txtRangeAccountUser18.Text(),
    rangeAccountUser19: C.txtRangeAccountUser19.Text(),
    
    transactionTypeId: C.cboTransactionType.Text(),
    transactionBatchId: C.txtTransactionBatchId.Text(),
    transactionDate: C.dateTransaction.Value(),
    transactionReference: C.txtTransactionReference.Text(),
    transactionNotes: C.txtTransactionNotes.Text(),
    
    saveToBatch: C.chkSaveToBatch.Value(),
  }

  // Selected Accounts
  if (includeRefreshData &amp;&amp; mIncomeDistribution) {
    // Update Income Distribution with last-minute details
    mIncomeDistribution.TransactionTypeId = C.cboTransactionType.Text();
    mIncomeDistribution.TransactionBatchId = C.txtTransactionBatchId.Text();
    mIncomeDistribution.TransactionDate = C.dateTransaction.Value();
    mIncomeDistribution.TransactionReference = C.txtTransactionReference.Text();
    mIncomeDistribution.TransactionNotes = C.txtTransactionNotes.Text();  
    mIncomeDistribution.SaveToBatch  = C.chkSaveToBatch.Value();

    // Set Refresh Data
    params.RefreshData = JSON.stringify(mIncomeDistribution);
  }

  return params;
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      if (mComplete) {
        widget.Close();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

    case "RECENT":
      // Recent
      tabWizard_Refresh(tabWizard.GetTabIndexById("CurrentProcesses"));
      break;

    default:
      window.alert(mViewName + ".Form_ExecuteAction: Unhandled action '" + actionId + "'");
      break;
  }
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "Stop") {
    // Stop Process?
    //widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?\n\nNOTE: This may not take effect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
    widget.UI.MsgBoxAlert("Stopping this process is not supported.");
  }
  else {
    // Validate
    tabWizard_Validate(function () {
      // Confirmation Message
      var message = "";
      var showPrompt = (mIncomeDistribution &amp;&amp; mIncomeDistribution.ReportRequiresPrinting);

      // Build Message
      message += "Are you sure you want to Process Income Distribution?";

      // Background Process
      message += "\n\nNOTE: This may take some time. You can close this form at any time and open it again to monitor progress.";

      // Confirm
      if (showPrompt) {
        var list = [];
        list.push("Income Distribution List Report not printed. Continue without printing the Income Distribution List Report?");
        widget.UI.MsgBoxConfirmList(message, list, {}, Form_ExecuteAction_FinishPost);
      }
      else {
        widget.UI.MsgBoxConfirm(message, {}, Form_ExecuteAction_FinishPost, null);
      }      
    });
  }
}

function Form_ExecuteAction_FinishPost() {
  // Running new process
  mMonitoringExisting = false;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Income Distribution Processing, please wait...");

  // Create Parameters
  var params = CreateFinishParameters(true);

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      // Parse
      data = JSON.parse(data);

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Enable Form
      widget.UI.Unblock();

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },

    function (error) {
      // Show Error
      widget.UI.MsgBoxAlert(error);

      // Enable Form
      widget.UI.Unblock();
    }
  );
}

function Form_ExecuteAction_FinishStop() {
  // Continue
  widget.GetString("CancelBackgroundProcess", { processId: mProcessId },
    function (data) {
      widget.UI.MsgBoxInfo("The process has been requested to stop.");
    },

    function (error) {
      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  var InProgressRefreshComplete = false;

  // Just in case!
  if (!mProcessId) return;

  // Continue
  widget.GetString("GetBackgroundProcessStatus", { processId: mProcessId, lastEventId: mLastEventId },
    function (data) {
      data = JSON.parse(data);

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

      // Override Status
      if (Status == "InProgressRefreshComplete" &amp;&amp; mFromRecent) {
        InProgressRefreshComplete = true;
        Status = "Complete";
      }
      if (Status == "InProgressRefreshComplete" &amp;&amp; mRecord.AutoCommit) {
        Status = "Pending";
      }

      // Handle Status
      switch(Status) {
        case "Cancelled":
          // Cancelled
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Income Distribution was successfully cancelled.");
          break;

        case "InProgressRefreshComplete":
          // Update Items
          mIncomeDistribution = JSON.parse(mRecord_BackgroundProcessStatus.RefreshData);

          // Save parameters
          mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters(false));

          // Refresh Complete
          mRecord_BackgroundProcessStatus = null;

          // Set Tab
          tabWizard.SelectedTabId("Items");
          tabWizard_Refresh();
          break;

        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":
          // Complete
          mComplete = true;
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          if (InProgressRefreshComplete) {
            widget.UI.MsgBoxInfo("Income Distribution Refresh is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          else {
            widget.UI.MsgBoxInfo("Income Distribution is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          break;

        case "Failed":
          // Failed
          mRecord_BackgroundProcessStatus = null;

          // Ensure if phase 2 has failed we are not prompted to Save and Close
          if (mIncomeDistribution) mComplete = true;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Income Distribution failed to complete.");
          break;

        default:
          // Continue Polling
          window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 2500);

          // Prevent finPOWER Connect Cloud UI signing the User out
          widget.NotifyBusy();
      }
    },

    function (error) {
      // Show Error
      widget.UI.MsgBoxAlert(error);

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();
    }
  );
}

// ====================
// pageCurrentProcesses
// ====================
function pageCurrentProcesses_Refresh() {
  // Reset flags
  mComplete = false;

  // Block UI
  widget.UI.Block("Refreshing Recent Income Distribution Processes, please wait...");

  // Fetch
  widget.GetString("GetCurrentProcesses", {},
    function (data) {
      // Parse
      mRecord_CurrentProcesses = JSON.parse(data);

      // Unblock UI
      widget.UI.Unblock();

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

    function (error) {
      // Unblock UI
      widget.UI.Unblock();

      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

// ======================
// pageTransactionDetails
// ======================
function pageTransactionDetails_Refresh() {
  // Block UI
  widget.UI.Block("Initialising, please wait...");
  
  // Params
  var params;
  if (mRecord.AutoCommit) {
    params = {
      dateFrom: C.datePeriodFrom.Value(),
      dateTo: C.datePeriodTo.Value(),
    };
  }
  else {
    params = JSON.parse(JSON.stringify(mIncomeDistribution));
  }

  // Get data  
  widget.GetString("GetTransactionDetails", params, pageTransactionDetails_Refresh_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();
    
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function pageTransactionDetails_Refresh_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Update Controls
  if (data) {
    C.datePeriodFromRO.Value(C.datePeriodFrom.Value());
    C.datePeriodToRO.Value(C.datePeriodTo.Value());
    C.spanPeriodDaysText.html(widget.UI.HtmlEncode(data.PeriodDaysText));
    
    C.dateTransaction.Value(C.datePeriodTo.Value());
  
    if (mRecord.AutoCommit) {
      C.lblDistributionAmountRO.VisibleRow(false);
      C.numNetDistributionRO.VisibleRow(false);
      C.numTotalDistributionRO.VisibleRow(false);
      C.numDistributionRate.VisibleRow(false);
      
      C.lblPrint.VisibleRow(false);
      C.cmdPrint.hide();
    }
    else {      
      C.numNetDistributionRO.Value(mIncomeDistribution.NetDistribution);
      C.numTotalDistributionRO.Value(data.ActualDistribution);
  
      if (data.DistributionDifferenceText) {      
        C.spanDistributionDiff.html(widget.UI.HtmlEncode(data.DistributionDifferenceText));
      }
      else {
        C.spanDistributionDiff.html("");
      }
      
      C.numDistributionRate.Value(data.DistributionRate);            
    }
  }
  
  // Unblock
  widget.UI.Unblock();
}

// ============
// pageProgress
// ============
function pageProgress_Refresh(clear) {
  if (clear) {    
    mLastProcessStatus = "";
    mLastEventId = "";
    mRecord_BackgroundProcessStatus = null;
    mRecord_CurrentProcesses = null;
  }
  else if (mRecord_BackgroundProcessStatus) {
    // Retrieve Last Process Status
    mLastProcessStatus = mRecord_BackgroundProcessStatus.StatusText;
  }

  // Build Progress
  mLastEventId = widget.UI.BuildBackgroundProcessProgress(C.divProgress, clear, mRecord_BackgroundProcessStatus, mLastEventId);

  // Stop button valid?
  tabWizard_UpdateButtons()

  // Update Heading
  if (tabWizard.SelectedTabId() == "Progress") {
    if (mLastProcessStatus &amp;&amp; mLastProcessStatus.length != 0) {
      frmMain.RefreshHeading(mLastProcessStatus, "Processing progress.");
    }
    else {
      frmMain.RefreshHeading("Progress", "Processing progress.");
    }
  }
}

function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ===============
// pageItems
// ===============
function pageItems_Refresh() {
  // Refresh Grid
  if (mIncomeDistribution) {
    gridItems_Refresh();
  }
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  // Add Columns
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnString("StatusText", { caption: "Status" });
    C.gridCurrentProcesses.AddColumnDateTime("CreatedDate", { caption: "Started" });

    // Actions
    C.gridCurrentProcesses.Actions().Define([{ actionId: "Cancel", caption: "Cancel", tooltipText: "Cancel the selected 'Refresh Complete' row", icon: "Trash" }]);
  }

  // Determine if Actions should be visible
  var found = false;
  for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
    var item = mRecord_CurrentProcesses[i];

    if (item.Status == "InProgressRefreshComplete") {
      found = true;
      break;
    }
  }
  C.gridCurrentProcesses.Actions().SetVisible("Cancel", found);

  // Refresh
  C.gridCurrentProcesses.VirtualDataRefresh(mRecord_CurrentProcesses);

  // Activate no rows
  C.gridCurrentProcesses.ActiveDataRowIndex(-1);
}

function gridCurrentProcesses_Action(actionId) {
  var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];

  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      CancelRefreshCompleteBackgroundProcess(item.ProcessId, false, pageCurrentProcesses_Refresh);
      break;

    default:
      window.alert("Unhandled grid action '" + actionId + "'.");
      break;
  }
}

function gridCurrentProcesses_AfterRowActivate(e) {
  // Refresh Buttons
  gridCurrentProcesses_RefreshButtons();
}

function gridCurrentProcesses_RefreshButtons() {
  if (C.gridCurrentProcesses.ActiveDataRowListIndex() == -1) {
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", false);
  }
  else {
    var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", item.Status == "InProgressRefreshComplete");
  }

  C.gridCurrentProcesses.RefreshButtons();
}

function gridCurrentProcesses_InitialiseRow(e) {
  var item = mRecord_CurrentProcesses[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Styles
  switch(item.Status) {
    case "Complete":
      e.row.cells.StatusText.colour = "green";
      break;

    case "CompleteWithErrors":
      e.row.cells.StatusText.colour = "darkred";
      break;

    case "CompleteWithWarnings":
      e.row.cells.StatusText.colour = "orange";
      break;

    case "Failed":
      e.row.cells.StatusText.colour = "red";
      break;

    case "Pending":
    case "InProgress":
    case "InProgressCancelRequested":
    case "InProgressRefreshComplete":
      e.row.bold = true;
      break;
  }
}

function gridCurrentProcesses_RowDrilldown(e) {
  ViewExistingProcess(e.row.listIndex);
}

// =========
// gridItems
// =========
function gridItems_Refresh() {
  // Add Columns
  C.gridItems.ClearColumns();  
  C.gridItems.AddColumnCode("AccountId", { caption: "Account" });
  C.gridItems.AddColumnString("Name", { caption: "Name" });
  C.gridItems.AddColumnString("Description", { caption: "Description" });
  C.gridItems.AddColumnString("AccountTypeId", { caption: "Type" });
  C.gridItems.AddColumnCurrency("Balance", { caption: "Balance", summary: "custom" });
  C.gridItems.AddColumnCurrency("AverageDailyBalance", { caption: "Avg Daily Bal", summary: "custom" });
  C.gridItems.AddColumnCurrency("DistributionOriginal", { caption: "Original", summary: "sum" });
  C.gridItems.AddColumnCurrency("Distribution", { caption: "Distribution", allowEdit: true, summary: "sum" });

  // Actions
  C.gridItems.Actions().Define([{ actionId: "Refresh", tooltipText: "Refresh Security Statements", icon: "Refresh"}]);

  // Refresh
  C.gridItems.VirtualDataRefresh(mIncomeDistribution.Items);

  // Select first row
  C.gridItems.ActivateFirstDataRow();
}

function gridItems_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "REFRESH":
      // Clear Cache
      mLastRefreshParametersJson = "";

      // Refresh
      RefreshIncomeDistribution(true);
      break;      
  }

  // Set Indexes
  if(indexes) {
    C.gridItems.SetSelectedRowIndexes(indexes, true);
  }
}

function gridItems_AfterRowActivate(e) {
}

function gridItems_BeforeCellUpdate(e) {
  var item = mIncomeDistribution.Items[e.row.listIndex];

  switch(e.columnKey) {
    case "Distribution":
      item.Distribution = e.newValue;
      
      // Refresh
      C.gridItems.VirtualDataRefresh(mIncomeDistribution.Items);
      break;
  }
}

function gridItems_FooterCellFormat(e) {
  switch (e.key) {
    case "Balance":
    case "AverageDailyBalance":
      var AverageDailyBalance = 0;
      var Balance = 0;      
      
      // Only include values if there is a Distribution value
      for (var i = 0; i &lt; mIncomeDistribution.Items.length; i++) {
        var item = mIncomeDistribution.Items[i];
        
        if (item.Distribution != 0) {
          AverageDailyBalance += item.AverageDailyBalance;
          Balance += item.Balance;          
        }
      }
      
      // Set summary
      if (e.key == "Balance" ) {
        e.cellText = widget.FormatCurrency(Balance, false, false, false)
      }
      else {
        e.cellText = widget.FormatCurrency(AverageDailyBalance, false, false, false)
      }
      break;
  }
}

function gridItems_InitialiseRow(e) {
  var item = mIncomeDistribution.Items[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Read-Only
  e.row.cells.AccountId.readOnly = true;
  e.row.cells.Name.readOnly = true;
  e.row.cells.Description.readOnly = true;
  e.row.cells.AccountTypeId.readOnly = true;
  e.row.cells.Balance.readOnly = true;
  e.row.cells.AverageDailyBalance.readOnly = true;
  e.row.cells.DistributionOriginal.readOnly = true;

  // Hyperlinks
  e.row.cells.AccountId.hyperlink = "app://FormShow?form=Accounts&amp;id=" + widget.UI.HtmlEncode(item.AccountId);
  
  // Highlight updated rows
  if (item.Distribution != item.DistributionOriginal) {
    e.row.backgroundColour = "#CAFACA";
  }
  else {
    e.row.backgroundColour = "";
  }
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Income Distribution Processing is still running.\n\nThis will continue to run and you can re-open this form at any time to check on its status.\n\n\Close this form?", {}, tabWizard_Cancel_Post);
  }
  else if (mProcessId &amp;&amp; (tabWizard.SelectedTabId() == "Items" || mIncomeDistribution)) {
    var list = [];
    list.push({ key: "CLOSE", caption: "Suspend and Close", icon: "Window_Close", details: "This will close the wizard but retain the list which can be reviewed later by re-opening this wizard." });
    list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close the wizard and cancel this process. The list of Income Distribution Processes will not be retained." });

    var options = {
      closeOnEscape: true,
      title: "Close Income Distribution Processing",
      showClose: true
    };

    widget.UI.MsgBoxList("Select an option below to close", list, options, function(key) {
      switch (key) {
        case "CLOSE":
          tabWizard_Cancel_Save();
          break;

        case "CANCEL":
          CancelRefreshCompleteBackgroundProcess(mProcessId, false, tabWizard_Cancel_Post);
          break;
      }
    });
  }
  else {
    tabWizard_Cancel_Post();
  }
}

function tabWizard_Cancel_Save() {
  // Block UI
  widget.UI.Block("Saving, please wait...");

  // Parameters
  var params = CreateFinishParameters(true);

  // Update Refresh Data
  widget.GetString("UpdateRefreshData", params, tabWizard_Cancel_Post, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function tabWizard_Cancel_Post() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

function tabWizard_Move(direction) {
  var Ok;

  // Validate
  if (direction &gt; 0) {
    tabWizard_Validate(function () { tabWizard_MovePost(direction); });
  }
  else {
    // Can always move backwards
    tabWizard_MovePost(direction);
  }
}

function tabWizard_MovePost(direction) {
  var Ok = true;

  // Find Next Tab to Move To
  if (Ok) {
    var found = false;
    var newTab = tabWizard.SelectedTabIndex();

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "Items":
          found = !mRecord.AutoCommit;
          break;

        default:
          found = true;
          break;
      }

      // Found?
      if (found) {
        break;
      }
      else if (newTab == tabWizard.TabCount() - 1) {
        // Just in case!
        widget.UI.MsgBoxAlert("tabWizard_MovePost: Tab not handled!");
        break;
      }
    }
    while (true);

    // Refresh the New Tab
    tabWizard_Refresh(newTab);
  }
}

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  // Back and Next Buttons?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 1);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 2);

  // Finish Button
  if (tabWizard.SelectedTabId() == "TransactionDetails") {
    cmdFinish.prop("disabled", false);
  }
  else if (mRecord.AutoCommit &amp;&amp; tabWizard.SelectedTabId() == "TransactionDetails") {
    cmdFinish.prop("disabled", false);
    cmdNext.prop("disabled", true);
  }
  else {
    cmdFinish.prop("disabled", true);
  }

  // Page Exceptions
  if (mRecord_BackgroundProcessStatus) {
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
    cmdBack.prop("disabled", true);
    cmdHistory.prop("disabled", true);

    switch(mRecord_BackgroundProcessStatus.Status) {
      case "Pending":
      case "InProgress":
        cmdFinish.text("Stop");
        cmdFinish.prop("disabled", false);
        cmdFinish.addClass("negative");
        break;

      default:
        cmdFinish.text("Process");
        cmdFinish.prop("disabled", true);
        cmdFinish.removeClass("negative");
    }
  }
  else {
    cmdFinish.text("Process");
    cmdHistory.prop("disabled", false);
  }

  // Only show Advanced button on relevant pages
  if (mRecord) {
    cmdAdvanced.hide()
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (mRecord.PageGeneralHasAdvanced) cmdAdvanced.show();
        break;
    }
  }
  else {
    cmdAdvanced.hide();
  }

  // Never allow moving back from Progress page
  if (tabWizard.SelectedTabId() == "Progress") cmdBack.prop("disabled", true);

  // Recent Page exceptions
  if (mFromRecent) {
    cmdHistory.prop("disabled", false);

    cmdBack.prop("disabled", true);
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", true);
  }

  if (mComplete) {
    // Complete, i.e., Finish now closes the wizard
    cmdFinish.text("Close");
    cmdFinish.prop("disabled", false);

    // Allow viewing recent list
    cmdHistory.prop("disabled", false);
  }
}

function tabWizard_Validate(validCallback) {
  // Validate
  var Ok = tabWizard.Validate(true);

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (widget.CompareDates(C.datePeriodFrom.Value(), C.datePeriodTo.Value()) == 1) {
          Ok = false;
          widget.UI.MsgBoxAlert("'From' date cannot be after the 'To' date.");
          C.datePeriodFrom.Focus();
        }
      
        if (Ok) {
          tabWizard_ValidatePost_General(validCallback);
          return; 
        }
        break;
    
      case "Items":
      //TODO: ???
//        var found = false;
//        for (var i = 0; i &lt; mIncomeDistribution.Items.length; i++) {
//          var item = mIncomeDistribution.Items[i];
//          if (item.Include) {
//            found = true;
//            break;
//          }
//        }

//        if (!found) {
//          Ok = false;
//          widget.UI.MsgBoxAlert("At least one item must be included to continue.");
//        }
        break;

      default:
        // No validation
        validCallback();
        return;
    }
  }

  // Server-side validation
  if (Ok) {
    var params;

    switch (tabWizard.SelectedTabId()) {
      default:
        break;
    }

    if (params) {
      // Disable Form
      frmMain.FormDisable("Validating");

      // Extend parameters
      params.pageId = tabWizard.SelectedTabId();

      // Call WizardValidate method in Script
      widget.GetString("WizardValidate",
                       params,
                       function (data) { tabWizard_ValidatePost(validCallback, data); },
                       tabWizard_ValidateFail);
    }
    else {
      // No server-side validation
      validCallback();
    }
  }
}

function tabWizard_ValidatePost(validCallback, data) {
  // Enable form
  frmMain.FormEnable();

  // Parse Data
  var o = {};
  if (data) o = JSON.parse(data);

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { tabWizard_ValidatePost_General(validCallback); },
                                      null);
        }
        else {
          tabWizard_ValidatePost_General(validCallback);
        }
        return;
    }

    // Callback
    validCallback();
  }
}

function tabWizard_ValidatePost_General(validCallback) {
  // Refresh
  if (!mRecord.AutoCommit) RefreshIncomeDistribution();

  // Callback
  validCallback();
}

function tabWizard_ValidateFail(errorMessage)
{
  widget.UI.MsgBoxAlert(errorMessage);

  // Enable form
  frmMain.FormEnable();
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks

  // General
  AdvancedInitialiseSection("RangesHeading", mRecord.ShowRangesHeading);
  AdvancedInitialiseSection("AccountManagers", mRecord.ShowAccountManagers); 
  AdvancedInitialiseSection("Accounts", mRecord.ShowAccounts); 
  AdvancedInitialiseSection("AccountTypes", mRecord.ShowAccountTypes); 
  AdvancedInitialiseSection("Branches", mRecord.ShowBranches);
  AdvancedInitialiseSection("Departments", mRecord.ShowDepartments);
  AdvancedInitialiseSection("Entities", mRecord.ShowEntities);
  AdvancedInitialiseSection("Brokers", mRecord.ShowBrokers);
  AdvancedInitialiseSection("Dealers", mRecord.ShowDealers);
  AdvancedInitialiseSection("Pools", mRecord.ShowPools);
  AdvancedInitialiseSection("ProductTypes", mRecord.ShowProductTypes);
  AdvancedInitialiseSection("AccountUser", mRecord.ShowAccountUser);
}

function AdvancedInitialiseSection(id, option) {
  // Get elements
  var els=$("*[advancedId='" + id + "']");

  // Update
  switch(option.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      break;

    case "FALSE":
      // Never show
      els.hide();
      break;

    case "ADVANCED":
      // Only show in 'Advanced' mode
      els.addClass("advanced");
      break;
  }
}

function AdvancedToggle() {
  // Toggle Advanced
  mAdvancedVisible = !mAdvancedVisible;

  // Update Controls
  if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

  // Other
  switch (tabWizard.SelectedTabId()) {
    default:
      break;
  }

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

// =======
// Refresh
// =======
function RefreshIncomeDistribution(fromGridAction) {
  if (mLastRefreshParametersJson == JSON.stringify(CreateFinishParameters(false))) {
    // Parameters have not changed, so do not kick off another refresh
  }
  else {
    // Hide content
    frmMain.Visible(false);

    // Confirmation Message
    var message = "";

    // Build Message
    message += "&lt;p&gt;Click OK to build a list of Accounts to distribute income to.&lt;/p&gt;";

    // Background Process
    message += "&lt;p&gt;NOTE: This may take some time. You can close this form at any time and open it again to monitor progress.&lt;/p&gt;";

    // Process already in progress, warn this will be cancelled
    if (mIncomeDistribution &amp;&amp; mProcessId) {
      message += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Accounts have already been refreshed. Continuing will cancel the existing process, and begin a new one.&lt;/p&gt;"
    }

    // Confirm
    var options = {
      heading: "Refresh Accounts",
      messageIsHtml: true,
      icon: "Table|Refresh"
    }
    widget.UI.MsgBoxConfirm(message, options,
      function () {
        if (mIncomeDistribution &amp;&amp; mProcessId) {
          CancelRefreshCompleteBackgroundProcess(mProcessId, fromGridAction, RefreshIncomeDistribution_Post, function() {
            // Move back a page
            tabWizard_Move(-1);

            // Show content
            frmMain.Visible(true);
          })
        }
        else {
          RefreshIncomeDistribution_Post();
        }
      },

      function() {
        // Move back a page
        if (!fromGridAction) {
          tabWizard_Move(-1);
        }

        // Show content
        frmMain.Visible(true);
      }
    );
  }
}

function RefreshIncomeDistribution_Post() {
  // Running new process
  mMonitoringExisting = false;
  mIncomeDistribution = null;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Income Distribution Refresh, please wait...");

  // Reset fields
  ResetTransactionDetailControls();

  // Create Parameters
  var params = CreateFinishParameters(true);

  // Refresh
  widget.GetString("Refresh", params,
    function (data) {
      // Show content
      frmMain.Visible(true);

      // Parse
      data = JSON.parse(data);

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Enable Form
      widget.UI.Unblock();

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },

    function (error) {
      // Show Error
      widget.UI.MsgBoxAlert(error);

      // Show content
      frmMain.Visible(true);

      // Enable Form
      widget.UI.Unblock();
    }
  );
}

// ==========================================
// Cancel Refresh Complete Background Process
// ==========================================
function CancelRefreshCompleteBackgroundProcess(processId, noPrompt, callback, cancelCallback) {
  if (noPrompt) {
    // Cancel immediately
    CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
  }
  else {
    // Prompt
    widget.UI.MsgBoxConfirm("Are you sure you want to cancel this Background Process?", {},
      function() {
        CancelRefreshCompleteBackgroundProcess_Execute(processId, callback);
      },

      cancelCallback
    );
  };
}

function CancelRefreshCompleteBackgroundProcess_Execute(processId, callback) {
  // Block
  widget.UI.Block("Cancelling Background Process, please wait...");

  // Params
  var params = {
    processId: processId,
  }

  widget.GetString("CancelBackgroundProcess", params, function() { callback(); }, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();

    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

// ===================================
// View an existing Background Process
// ===================================
function ViewExistingProcess(itemIndex) {
  var item = mRecord_CurrentProcesses[itemIndex];
  var Ok = true;

  // Validate
  if (item.Status == "InProgressRefreshComplete" &amp;&amp; mRecord.AutoCommit) {
    Ok = false;
    widget.UI.MsgBoxInfo("Cannot resume a two-phase Process when this HTML Widget is configured to run in single-phase (Auto Commit) mode.");
  }

  if (Ok) {
    // Set Information from Process
    mProcessId = item.ProcessId;

    // Reset fields
    ResetTransactionDetailControls();

    // Status-dependant
    switch (item.Status) {
      case "InProgressRefreshComplete":
        // Update Items
        mIncomeDistribution = JSON.parse(item.RefreshData);

        // Update Controls
        Fields_Update_FromBackgroundProcess();

        // Save parameters
        mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters(false));

        // Set Tab
        tabWizard.SelectedTabId("Items");
        tabWizard_Refresh();
        break;

      default:
        mFromRecent = true;
        mMonitoringExisting = true;

        // Switch to Progress Page
        tabWizard_Refresh(tabWizard.GetTabIndexById("Progress"));
        pageProgress_Refresh(true);

        // Start monitoring
        Form_ExecuteAction_GetBackgroundProcessStatus();
        break;
    }
  }
}

// ========
// txtRange
// ========
function txtRange_ButtonClick(sender, e) {
  if (e.id == "Lookup") {
    var caption = sender.Element().attr("lookupCaption");
    var range = sender.Element().attr("id");
    var sql = "";
    var idField = "";

    range = range.substr(8);
    if(range.startsWith("Payee")) range = "ExternalParties" + range.substr(5);
    
    if (range.startsWith("AccountUser")) {
      // Find the correct Account User options
      for (var i = 0; i &lt; mRecord.AccountUsers.length; i++) {
        var item = mRecord.AccountUsers[i];
        
        if (range == "Account" + item.IdField) {
          caption = item.Caption;
          sql = item.RangeLookupSql;
          idField = item.IdField;
          break;
        }
      }
      
      // Show Lookup
      if (idField) {
        widget.UI.Forms.ShowRangeLookupFromDatabase(sender.Text(), { idField: idField, rangeLookupSql: sql, caption: caption },
          function (newRange) {
            sender.Text(newRange);
            sender.Focus();
          }
        );
      }
      else {
        widget.UI.MsgBoxAlert("Could not determine Range Lookup for the selected Account User field.");
      }      
    }
    else {
      widget.UI.Forms.ShowRangeLookupFromStandardRange(range, sender.Text(), { caption: "Lookup " + caption},
        function (newRange) {
          sender.Text(newRange);
          sender.Focus();
        }
      );
    }    
  }
}

// ==================
// cboTransactionType
// ==================
function cboTransactionType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Reference and Notes
  var transactionType = mRecord.TransactionTypes.GetItem(C.cboTransactionType.Text());
  if (transactionType) {
    C.txtTransactionReference.Text(transactionType.Reference);
    C.txtTransactionNotes.Text(transactionType.Notes);
  }
  
  // Report Requires reprinting
  if (mIncomeDistribution) mIncomeDistribution.ReportRequiresPrinting = true;
}

// =====================
// txtTransactionBatchId
// =====================
function txtTransactionBatchId_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Report Requires reprinting
  if (mIncomeDistribution) mIncomeDistribution.ReportRequiresPrinting = true;
}

// ===============
// dateTransaction
// ===============
function dateTransaction_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Report Requires reprinting
  if (mIncomeDistribution) mIncomeDistribution.ReportRequiresPrinting = true;
}

// =======================
// txtTransactionReference
// =======================
function txtTransactionReference_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Report Requires reprinting
  if (mIncomeDistribution) mIncomeDistribution.ReportRequiresPrinting = true;
}

// ===================
// txtTransactionNotes
// ===================
function txtTransactionNotes_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Report Requires reprinting
  if (mIncomeDistribution) mIncomeDistribution.ReportRequiresPrinting = true;
}

// ==============
// chkSaveToBatch
// ==============
function chkSaveToBatch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Report Requires reprinting
  if (mIncomeDistribution) mIncomeDistribution.ReportRequiresPrinting = true;
}

// =====================
// txtTransactionBatchId
// =====================
function txtTransactionBatchId_ButtonClick(source, e) {
  switch(e.id) {
    case "Auto":
      if (!C.cboTransactionType.Text()) {
        C.cboTransactionType.Focus();
      }
      else if (C.txtTransactionBatchId.Text()) {
        widget.UI.MsgBoxConfirm("Are you sure you want to overwrite this Batch Id with a new, auto-generated Batch Id?\n\nNOTE: Misusing this button may cause gaps to appear in Batch Id sequences.", {}, txtTransactionBatchId_ButtonClick_Post);
      }
      else {
        txtTransactionBatchId_ButtonClick_Post();
      }
  }
}

function txtTransactionBatchId_ButtonClick_Post() {
  // Block UI
  widget.UI.Block("Getting next Batch Id, please wait...");
  
  // Params
  var params = {
    transactionTypeId: C.cboTransactionType.Text()
  }
  
  // Get Batch Id
  widget.GetString("GetBatchId", params, 
    function(data) {
      if (data) { 
        C.txtTransactionBatchId.Text(data);        
        txtTransactionBatchId_Change();
      }
      
      // Unblock
      widget.UI.Unblock();
    }, 
  
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();
      
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}

// ==============================
// Print Income Distribution List
// ==============================
function PrintIncomeDistributionList() {
  // Create Parameters
  var params = CreateFinishParameters(true);
  
  // Download File
  widget.DownloadFile("PrintIncomeDistributionList", params);
  
  // Report no longer requires printing
  if (mIncomeDistribution) mIncomeDistribution.ReportRequiresPrinting = false;
}

// =================================
// Reset Transaction Detail Controls
// =================================
function ResetTransactionDetailControls() {
  C.cboTransactionType.Text("");
  C.txtTransactionBatchId.Text("");
  C.dateTransaction.Value(C.datePeriodTo.Value());
  C.txtTransactionReference.Text("");
  C.txtTransactionNotes.Text("");
  C.chkSaveToBatch.Value(false);
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "FORMCLOSE":
      // Closing Form
      tabWizard_Cancel();
      break;

    default:
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>0</TimeoutSeconds>
    <UniqueId>yUFQGePfpEyTBAlyv0kLiw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowAccountManagers" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccounts" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccountTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowBranches" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowDepartments" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowEntities" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowBrokers" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowDealers" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowPools" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowProductTypes" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowAccountUser" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AutoCommit" type="Boolean">
            <BlankTip />
            <Caption>Auto Commit?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ProcessId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>50</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DesktopMode" type="Boolean">
            <BlankTip />
            <Caption>Running from Desktop?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>