<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-07-25T23:27:45.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-05-16T21:56:51.6970000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-07-25T23:27:20.8500000</UpdatedUtcDate>
    <ScriptId>FRLPR</ScriptId>
    <Description>Floating Rate Loan Payment Review</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountFloatingRatePaymentReview
Option Explicit On
Option Strict On

' #################################################################
' Floating Rate Loan Payment Review
'
' Version: 1.01 (26/07/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  27/05/2024  ISS      J031337   Created
'    1.01  10/07/2024  ISS      J033839   Add "New First" column
'          26/07/2024  ISS      J033972   Moved shared functions to the Business Layer
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountFloatingRatePaymentReview"

' Objects
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

' Other
Private mDesktopMode As Boolean
Private mProcessId As String
Private mProcessStatus As finHtmlWidgetBackgroundProcessStatus
Private mReportColumnsToInclude As String

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
    mDesktopMode = .GetBoolean("DesktopMode")
    mProcessId = .GetString("ProcessId")
    mReportColumnsToInclude = .GetString("ReportColumnsToInclude")
  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 "GetAccountTypeDefaults"
      ' Get Account Type Defaults
      Main = GetAccountTypeDefaults(returnValue)
      
    Case "GetBackgroundProcessStatus"
      ' Get Background Process Status
      Main = GetBackgroundProcessStatus(returnValue)
      
    Case "GetCurrentProcesses"
      ' Get Current Processes
      Main = GetCurrentProcesses(returnValue)

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)    
      
    Case "GetItemPreview"
      ' Get the HTML Summary Page for the active row on the grid
      Main = GetItemPreview(parametersJson, returnValue)  
      
    Case "GetRegularPaymentEarliestDate"
      ' Get Regular Payment Earliest Date
      Main = GetRegularPaymentEarliestDate(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 AccountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' 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 finAccountFloatingRatePaymentReview Object
  If Success Then
    Success = CreateAccountFloatingRatePaymentReview(Nothing, AccountFloatingRatePaymentReview)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId
      
      .AccountTypeId = AccountFloatingRatePaymentReview.AccountTypeId
      .AdjustPaymentInstructionsOnly = AccountFloatingRatePaymentReview.AdjustPaymentInstructionsOnly
      .MaturityDateLessPeriod = AccountFloatingRatePaymentReview.MaturityDateLessPeriod
      .MaturityDatePlusPeriod = AccountFloatingRatePaymentReview.MaturityDatePlusPeriod
      .ArrangementDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(AccountFloatingRatePaymentReview.ArrangementDate)
      .ArrangementType = AccountFloatingRatePaymentReview.ArrangementType
      .OverrideInterestInstruction = AccountFloatingRatePaymentReview.OverrideInterestInstructionText
      .RegularPaymentEarliestDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(AccountFloatingRatePaymentReview.RegularPaymentEarliestDate)
      .PrintAdvice = AccountFloatingRatePaymentReview.PrintAdvice
      
      ' Lists
      .AccountTypeSqlWhere = finBL.AccountTypeFunctions.GetFloatingRateAccountTypeSqlWhere(True)
      .OverrideInterestInstructionList = finBL.Enums.isefinAccountFloatingRatePaymentReviewInstruction_ToCodeDescriptionList().ToJsonObject()
      .PeriodList = "7 Days,14 Days,21 Days,30 Days,1 Month,60 Days,2 Months,90 Days,3 Months,6 Months"

      ' Advanced      
      .ShowAccounts = mCombinedParameters.GetString("ShowAccounts") : If Len(.ShowAccounts) = 0 Then .ShowAccounts = "Advanced"
      .ShowAccountManagers = mCombinedParameters.GetString("ShowAccountManagers") : If Len(.ShowAccountManagers) = 0 Then .ShowAccountManagers = "Advanced"            
      .ShowBranches = mCombinedParameters.GetString("ShowBranches") : If Len(.ShowBranches) = 0 Then .ShowBranches = "Advanced"      
      .ShowBrokers = mCombinedParameters.GetString("ShowBrokers") : If Len(.ShowBrokers) = 0 Then .ShowBrokers = "Advanced"
      .ShowClients = mCombinedParameters.GetString("ShowClients") : If Len(.ShowClients) = 0 Then .ShowClients = "Advanced"
      .ShowClientGroups = mCombinedParameters.GetString("ShowClientGroups") : If Len(.ShowClientGroups) = 0 Then .ShowClientGroups = "Advanced"
      .ShowClientTypes = mCombinedParameters.GetString("ShowClientTypes") : If Len(.ShowClientTypes) = 0 Then .ShowClientTypes = "Advanced"
      .ShowDealers = mCombinedParameters.GetString("ShowDealers") : If Len(.ShowDealers) = 0 Then .ShowDealers = "Advanced"      
      .ShowDepartments = mCombinedParameters.GetString("ShowDepartments") : If Len(.ShowDepartments) = 0 Then .ShowDepartments = "Advanced"
      .ShowEntities = mCombinedParameters.GetString("ShowEntities") : If Len(.ShowEntities) = 0 Then .ShowEntities = "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.ExternalPartyBrokers Then .ShowBrokers = "False"
      If Not finBL.Settings.AddOns.ExternalPartyDealers Then .ShowDealers = "False"

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

      ' Permissions

      ' Configuration
      .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;
'''  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 finAccountFloatingRatePaymentReview object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateAccountFloatingRatePaymentReview(parameters As WizardFinishParameters,
                                                        ByRef accountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountFloatingRatePaymentReview = finBL.CreateAccountFloatingRatePaymentReview()

  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With accountFloatingRatePaymentReview
      .AccountTypeId = parameters.AccountTypeId
      .AdjustPaymentInstructionsOnly = parameters.AdjustPaymentInstructionsOnly
      .ArrangementDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.ArrangementDate)
      .ArrangementType = parameters.ArrangementType
      .MaturityDateLessPeriod = parameters.MaturityDateLessPeriod
      .MaturityDatePlusPeriod = parameters.MaturityDatePlusPeriod
      .OverrideInterestInstructionText = parameters.OverrideInterestInstruction
      .PrintAdvice = parameters.PrintAdvice
      .RegularPaymentEarliestDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.RegularPaymentEarliestDate)
      
      .RangeAccountManagers = parameters.RangeAccountManagers
      .RangeAccounts = parameters.RangeAccounts
      .RangeBranches = parameters.RangeBranches
      .RangeClientGroups = parameters.RangeClientGroups
      .RangeClients = parameters.RangeClients
      .RangeClientTypes = parameters.RangeClientTypes
      .RangeDepartments = parameters.RangeDepartments
      .RangeEntities = parameters.RangeEntities
      .RangeExternalPartiesBrokers = parameters.RangeExternalPartiesBrokers
      .RangeExternalPartiesBrokersIncludeSub = parameters.RangeExternalPartiesBrokersIncludeSub
      .RangeExternalPartiesDealers = parameters.RangeExternalPartiesDealers
      .RangeExternalPartiesDealersIncludeSub = parameters.RangeExternalPartiesDealersIncludeSub
    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

  ' Assume Success
  Success = True

  ' Parse Parameters

  ' 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, False, 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
  Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript_ExecuteCommit(ScriptInfo.ScriptId, WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData, mDesktopMode)
    
  ' Context-specific functionality - not supported
  If Success Then    
    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

  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 the HTML Summary Page for the active row on the grid.
''' &lt;/summary&gt;
Private Function GetItemPreview(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim AccountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview
  Dim AccountFloatingRatePaymentReviewItem As finAccountFloatingRatePaymentReviewItem
  Dim Found As Boolean
  Dim i As Integer
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise

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

  If Success AndAlso Len(WizardFinishParameters.AccountId) &lt;&gt; 0 Then
    ' Create Object
    Success = CreateAccountFloatingRatePaymentReview(WizardFinishParameters, AccountFloatingRatePaymentReview)
    
    ' Refresh for the single Account
    If Success Then
      AccountFloatingRatePaymentReview.RangeAccounts = WizardFinishParameters.AccountId
      Success = AccountFloatingRatePaymentReview.Refresh()
    End If    
    
    ' Get Summary
    If Success Then
      ' Find correct item by Account Id
      Found = False
      For i = 0 To AccountFloatingRatePaymentReview.Count - 1
        AccountFloatingRatePaymentReviewItem = AccountFloatingRatePaymentReview(i)
        
        If StrComp(AccountFloatingRatePaymentReviewItem.AccountId, WizardFinishParameters.AccountId, CompareMethod.Text) = 0 Then
          Found = True
          Exit For
        End If
      Next 
      
      ' Get Summary
      If Found Then
        returnValue = finBL.SummaryPageFunctions.AccountFloatingRatePaymentReviewSummary(False, AccountFloatingRatePaymentReview, i, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
      Else 
        Success = False
        finBL.Error.ErrorBeginFormat("Could not find Floating Rate Loan Payment for Account {0}.", WizardFinishParameters.AccountId)
      End If      
    End If
  End If

  ' Error
  If Not Success Then
    ' Error HTML
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
  End If

  Return Success

End Function


Private Function GetRegularPaymentEarliestDate(ByRef returnValue As String) As Boolean
  
  Dim AccountTypeId As String
  Dim ArrangementDate As Date
  Dim Data As Object
  Dim RegularPaymentEarliestDate As Date?
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Params
  With mCombinedParameters
    AccountTypeId = .GetString("AccountTypeId")
    ArrangementDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("ArrangementDate"))
  End With
  
  ' Get Regular Payment Earliest Date
  If finBL.AccountTypes.Exists(AccountTypeId) Then
    If Len(finBL.AccountTypes(AccountTypeId).InterestEarliestDateDefault) &lt;&gt; 0 AndAlso ArrangementDate &lt;&gt; Nothing Then
      RegularPaymentEarliestDate = finBL.Utilities.DateCycleGetTermEndDate(finBL.AccountTypes(AccountTypeId).InterestEarliestDateDefault, ArrangementDate)
    End If
  End If
  
  ' Finalise
  If Success Then
    Data = New With {
      .RegularPaymentEarliestDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(RegularPaymentEarliestDate)
    }
  End If
  
  ' Serialise
  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;
'''  Update a finAccountFloatingRatePaymentReview object from the AccountFloatingRatePaymentReview Json Class.
''' &lt;/summary&gt;
Private Function UpdateAccountFloatingRatePaymentReviewFromJsonClass(floatingRatePaymentReview As AccountFloatingRatePaymentReview,
                                                                     ByRef accountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview) As Boolean
  
  Dim AccountFloatingRatePaymentReviewItem As finAccountFloatingRatePaymentReviewItem
  Dim FloatingRatePaymentReviewItem As AccountFloatingRatePaymentReviewItem
  Dim MatchedRecordCount As Integer
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Initialise
  MatchedRecordCount = 0
  
  ' Update Account Floating Interest Rates Review Item with Json object
  If Success Then
    For Each FloatingRatePaymentReviewItem In floatingRatePaymentReview.Items
      For Each AccountFloatingRatePaymentReviewItem In accountFloatingRatePaymentReview
        With AccountFloatingRatePaymentReviewItem
          If FloatingRatePaymentReviewItem.AccountPk = .AccountPk Then
            MatchedRecordCount += 1
            .Include = FloatingRatePaymentReviewItem.Include
            Exit For
          End If
        End With
      Next 
    Next
    
    ' Validate
    If floatingRatePaymentReview.Items.Count &lt;&gt; MatchedRecordCount Then
      Success = False
      finBL.Error.ErrorBegin("Record mismatch. The collection may have changed since it was originally loaded. Please restart the Floating Rate Loan Payment Review Process again.")
    End If
  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 AccountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = 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 Pending Floating Interest Rate Review")
  End If
  
  ' Refresh Accounts
  If Success Then
    ' Create
    Success = CreateAccountFloatingRatePaymentReview(WizardFinishParameters, AccountFloatingRatePaymentReview)
    
    ' Refresh
    If Success Then Success = AccountFloatingRatePaymentReview.Refresh()
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New AccountFloatingRatePaymentReview(AccountFloatingRatePaymentReview), returnValue)    
  End If
  
  Return Success  
  
End Function

Private Function BackgroundProcess_ExecuteCommit(ByRef returnValue As String) As Boolean
  
  Dim AccountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview
  Dim AccountFloatingRatePaymentReviewItem As finAccountFloatingRatePaymentReviewItem
  Dim Cancelled As Boolean  
  Dim FileName As String
  Dim FloatingRatePaymentReview As AccountFloatingRatePaymentReview
  Dim obj As Object
  Dim RefreshData As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = 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)  
  
  ' Notify
  mProcessStatus.AddEvent_Information("Starting Commit")
  
  ' Get Account Floating Interest Rates Review
  If GetWizardFinishParameters(mParameters.ToSimpleJsonString(), WizardFinishParameters) Then
    Success = CreateAccountFloatingRatePaymentReview(WizardFinishParameters, AccountFloatingRatePaymentReview)
  Else 
    Success = False
  End If
  
  ' Get information 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(AccountFloatingRatePaymentReview), obj) Then
          FloatingRatePaymentReview = DirectCast(obj, AccountFloatingRatePaymentReview)
        Else 
          Success = False
        End If
      End If
    Else 
      Success = False
    End If
  End If  
  
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Refreshing Review Items")
  End If
  
  ' Refresh
  If Success Then
    Success = AccountFloatingRatePaymentReview.Refresh()
  End If
  
  ' Notify
  If Success Then
    mProcessStatus.AddEvent_Information("Setting Included Items")
  End If 
  
  ' Update Account Floating Interest Rates Review with Json object
  If Success Then
    Success = UpdateAccountFloatingRatePaymentReviewFromJsonClass(FloatingRatePaymentReview, AccountFloatingRatePaymentReview)
  End If 
  
  ' Commit
  If Success Then
    mProcessStatus.AddEvent_Information("Committing Floating Rate Loan Payments")
    Success = AccountFloatingRatePaymentReview.ExecuteCommit()
  End If
  
  ' Warnings
  If Success Then
    For Each AccountFloatingRatePaymentReviewItem In AccountFloatingRatePaymentReview
      With AccountFloatingRatePaymentReviewItem
        If .Include AndAlso (Not .Processed) AndAlso Len(.InvalidMessageResolved) &lt;&gt; 0 Then
          mProcessStatus.AddEvent_Warning(String.Format("Error for Account {0}, '{1}'", .AccountId, .AccountName), .InvalidMessageResolved)
        End If                
      End With    
    Next        
  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("AccountFloatingRatePaymentReview", "pdf")
    
    ' Create Summary
    If CreateAccountFloatingRatePaymentReviewPdf(AccountFloatingRatePaymentReview, 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

''' &lt;summary&gt;
'''  Generates the Account Floating Rate Payment Review Summary and produces a file.
''' &lt;/summary&gt;
Private Function CreateAccountFloatingRatePaymentReviewPdf(accountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview,
                                                           filename As String) As Boolean

  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
    Success = GetAccountFloatingRatePaymentReviewSummary(accountFloatingRatePaymentReview, SummaryTables)
  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("Processing options")
        .AddCaptionCodeDescription("Account Type:", accountFloatingRatePaymentReview.AccountTypeId, finBL.AccountTypes)
        .AddCheckBox("Include 'Adjust Payment' Instructions only?", accountFloatingRatePaymentReview.AdjustPaymentInstructionsOnly)
        .AddCaptionText("Shortened:", accountFloatingRatePaymentReview.MaturityDateLessPeriod)
        .AddCaptionText("Lengthened:", accountFloatingRatePaymentReview.MaturityDatePlusPeriod)
        
        .AddSectionHeading2("Update options")
        .AddCaptionDate("Date:", accountFloatingRatePaymentReview.ArrangementDate)
        .AddCaptionText("Type:", accountFloatingRatePaymentReview.ArrangementType)
        .AddCaptionText("Instruction:", accountFloatingRatePaymentReview.OverrideInterestInstructionText)
        .AddCaptionDate("Earliest date:", accountFloatingRatePaymentReview.RegularPaymentEarliestDate)
        .AddCheckBox("Print Advice?", accountFloatingRatePaymentReview.PrintAdvice)
        
        ' Ranges
        If Len(accountFloatingRatePaymentReview.RangeAccounts) &lt;&gt; 0 OrElse 
           Len(accountFloatingRatePaymentReview.RangeAccountManagers) &lt;&gt; 0 OrElse 
           Len(accountFloatingRatePaymentReview.RangeBranches) &lt;&gt; 0 OrElse
           Len(accountFloatingRatePaymentReview.RangeExternalPartiesBrokers) &lt;&gt; 0 OrElse
           Len(accountFloatingRatePaymentReview.RangeClients) &lt;&gt; 0 OrElse
           Len(accountFloatingRatePaymentReview.RangeClientGroups) &lt;&gt; 0 OrElse
           Len(accountFloatingRatePaymentReview.RangeClientTypes) &lt;&gt; 0 OrElse
           Len(accountFloatingRatePaymentReview.RangeExternalPartiesDealers) &lt;&gt; 0 OrElse
           Len(accountFloatingRatePaymentReview.RangeDepartments) &lt;&gt; 0 OrElse
           Len(accountFloatingRatePaymentReview.RangeEntities) &lt;&gt; 0 Then
            .AddSectionHeading2("Ranges")
        End If        
        If Len(accountFloatingRatePaymentReview.RangeAccounts) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.AccountsDeposits) &amp; ":", accountFloatingRatePaymentReview.RangeAccounts)  
        If Len(accountFloatingRatePaymentReview.RangeAccountManagers) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.AccountManagers) &amp; ":", accountFloatingRatePaymentReview.RangeAccountManagers)                 
        If Len(accountFloatingRatePaymentReview.RangeBranches) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Branches) &amp; ":", accountFloatingRatePaymentReview.RangeBranches)
        If Len(accountFloatingRatePaymentReview.RangeExternalPartiesBrokers) &lt;&gt; 0 Then 
          .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ExternalPartiesBrokers) &amp; ":", accountFloatingRatePaymentReview.RangeExternalPartiesBrokers)
          .AddCaptionTick("Include Sub Brokers?", accountFloatingRatePaymentReview.RangeExternalPartiesBrokersIncludeSub, True)
        End If
        If Len(accountFloatingRatePaymentReview.RangeClients) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Clients) &amp; ":", accountFloatingRatePaymentReview.RangeClients)
        If Len(accountFloatingRatePaymentReview.RangeClientGroups) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ClientGroups) &amp; ":", accountFloatingRatePaymentReview.RangeClientGroups)
        If Len(accountFloatingRatePaymentReview.RangeClientTypes) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ClientTypes) &amp; ":", accountFloatingRatePaymentReview.RangeClientTypes)
        If Len(accountFloatingRatePaymentReview.RangeExternalPartiesDealers) &lt;&gt; 0 Then 
          .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ExternalPartiesDealers) &amp; ":", accountFloatingRatePaymentReview.RangeExternalPartiesDealers)
          .AddCaptionTick("Include Sub Dealers?", accountFloatingRatePaymentReview.RangeExternalPartiesDealersIncludeSub, True)
        End If        
        If Len(accountFloatingRatePaymentReview.RangeDepartments) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Departments) &amp; ":", accountFloatingRatePaymentReview.RangeDepartments)
        If Len(accountFloatingRatePaymentReview.RangeEntities) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Entities) &amp; ":", accountFloatingRatePaymentReview.RangeEntities)                  
      End With
    End With
  End If

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

    ' Append Information
    sb.AppendH1("Floating Rate Loan Payment Review")
    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 Floating Rate Loan Payment Review Pdf.")
  End If

  Return Success

End Function


Private Function GetAccountTypeDefaults(ByRef returnValue As String) As Boolean
  
  Dim AccountTypeId As String
  Dim Success As Boolean
  Dim ArrangementDate As Date
  Dim Data As Object
  Dim RegularPaymentEarliestDate As Date?
  
  ' Assume Success
  Success = True
  
  ' Parameters
  With mCombinedParameters
    AccountTypeId = .GetString("AccountTypeId")
    ArrangementDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("ArrangementDate"))
  End With
  
  ' Update Earliest Repayment date
  If finBL.AccountTypes.Exists(AccountTypeId) Then
    If Len(finBL.AccountTypes(AccountTypeId).InterestEarliestDateDefault) = 0 OrElse ArrangementDate = Nothing Then
      ' No Date
    Else
      RegularPaymentEarliestDate = finBL.Utilities.DateCycleGetTermEndDate(finBL.AccountTypes(AccountTypeId).InterestEarliestDateDefault, ArrangementDate)
    End If
  Else
    RegularPaymentEarliestDate = Nothing
  End If
  
  ' Finalise
  If Success Then
    Data = New With {
      .RegularPaymentEarliestDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(RegularPaymentEarliestDate)
    }
  End If
  
  ' Serialise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
  
End Function


Private Function GetAccountFloatingRatePaymentReviewSummary(accountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview,
                                                            ByRef summaryTables As ISSummaryTables) As Boolean

  Dim AccountFloatingRatePaymentReviewItem As finAccountFloatingRatePaymentReviewItem
  Dim Columns As ISList  
  Dim DataRow As DataRow
  Dim dt As DataTable
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  summaryTables = finBL.CreateSummaryTables()

  ' Initialise
  Columns = finBL.Runtime.CreateList()
  dt = New DataTable()

  ' Columns to display
  If Len(mReportColumnsToInclude) = 0 Then
    Columns.Add("Include")
    Columns.Add("Account")
    Columns.Add("Name")
    Columns.Add("Payment")
    Columns.Add("Maturity")
    Columns.Add("Final")
    Columns.Add("Difference")
    Columns.Add("NewPayment")
    Columns.Add("NewFirst")
    Columns.Add("NewFinalPayment")
    Columns.Add("NewMaturity")
    Columns.Add("Change")
  Else 
    Columns.FromCsvString(mReportColumnsToInclude)
  End If
  
  ' DataTable
  With dt.Columns
    If Columns.Exists("Include") Then .Add("Include", GetType(Boolean))
    If Columns.Exists("Account") Then .Add("Account", GetType(String))
    If Columns.Exists("Name") Then .Add("Name", GetType(String))
    If Columns.Exists("Payment") Then .Add("Payment", GetType(Decimal))
    If Columns.Exists("Maturity") Then .Add("Maturity", GetType(Date))
    If Columns.Exists("Final") Then .Add("Final", GetType(Date))
    If Columns.Exists("Difference") Then .Add("Difference", GetType(String))
    If Columns.Exists("NewPayment") Then .Add("NewPayment", GetType(Decimal))
    If Columns.Exists("NewFirst") Then .Add("NewFirst", GetType(Date))
    If Columns.Exists("NewFinalPayment") Then .Add("NewFinalPayment", GetType(Decimal))
    If Columns.Exists("NewMaturity") Then .Add("NewMaturity", GetType(Date))
    If Columns.Exists("Change") Then .Add("Change", GetType(String))
  End With

  ' Add to Summary Table
  For Each AccountFloatingRatePaymentReviewItem In accountFloatingRatePaymentReview
    DataRow = dt.NewRow()
    With AccountFloatingRatePaymentReviewItem        
      If Columns.Exists("Include") Then DataRow!Include = .Include
      If Columns.Exists("Account") Then DataRow!Account = .AccountId
      If Columns.Exists("Name") Then DataRow!Name = .AccountName
      If Columns.Exists("Payment") Then DataRow!Payment = .CurrentRegularPayment
      If Columns.Exists("Maturity") Then DataRow!Maturity = .CurrentMaturityDate
      If Columns.Exists("Final") Then DataRow!Final = .CurrentFinalPaymentDate
      If Columns.Exists("Difference") Then DataRow!Difference = .FinalDateChangeText()
      If Columns.Exists("NewPayment") Then DataRow!NewPayment = .NewRegularPayment
      If Columns.Exists("NewFirst") Then DataRow!NewFirst = .NewFirstPaymentDate
      If Columns.Exists("NewFinalPayment") Then DataRow!NewFinalPayment = .NewFinalPayment
      If Columns.Exists("NewMaturity") Then DataRow!NewMaturity = .NewMaturityDate
      If Columns.Exists("Change") Then 
        If .CurrentMaturityDate = .NewMaturityDate Then
          If .CurrentRegularPayment = .NewRegularPayment Then
            DataRow!Change = ""
          ElseIf .CurrentRegularPayment &lt; .NewRegularPayment Then
            DataRow!Change = "+" &amp; finBLShared.FormatCurrency(.NewRegularPayment - .CurrentRegularPayment, True)
          Else
            DataRow!Change = "-" &amp; finBLShared.FormatCurrency(.CurrentRegularPayment - .NewRegularPayment, True)
          End If
        Else
          DataRow!Change = .MaturityDateChangeText
        End If
      End If
    End With
    
    ' Add Row
    dt.Rows.Add(DataRow)
  Next

  ' Convert DataTable to Summary Table
  If Success Then
    SummaryTable = finBL.Utilities.DataTableToSummaryTable(dt)
  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 Get Account Floating Interest Rates Review Summary.")
  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
  Public AccountTypeId As String
  Public AdjustPaymentInstructionsOnly As Boolean
  Public MaturityDateLessPeriod As String
  Public MaturityDatePlusPeriod As String
  Public ArrangementDate As Date?
  Public ArrangementType As String
  Public OverrideInterestInstruction As String
  Public RegularPaymentEarliestDate As Date?
  Public PrintAdvice As Boolean

  ' Lists
  Public AccountTypeSqlWhere As String
  Public OverrideInterestInstructionList As Object
  Public PeriodList As String 

  ' Advanced
  Public PageGeneralHasAdvanced As Boolean
  Public ShowAccounts As String
  Public ShowAccountManagers As String  
  Public ShowBranches As String
  Public ShowBrokers As String
  Public ShowClients As String
  Public ShowClientGroups As String
  Public ShowClientTypes As String
  Public ShowDealers As String
  Public ShowDepartments As String  
  Public ShowEntities As String  
  Public ShowRangesHeading As String

  ' Permissions
  Public CanSaveToBatch As Boolean

  ' Configuration
  Public PromptOnCommit As Boolean
  
End Class


''' &lt;summary&gt;
'''  Account Floating Rate Loan Payment Review.
''' &lt;/summary&gt;
Public Class AccountFloatingRatePaymentReview
  
  ' Properties
  Public AccountTypeId As String
  Public AdjustPaymentInstructionsOnly As Boolean
  Public ArrangementDate As Date
  Public ArrangementType As String
  Public MaturityDateLessPeriod As String
  Public MaturityDatePlusPeriod As String
  Public OverrideInterestInstruction As String
  Public PrintAdvice As Boolean
  Public RegularPaymentEarliestDate As Date?
  
  ' Ranges
  Public RangeAccountManagers As String
  Public RangeAccounts As String
  Public RangeBranches As String
  Public RangeClientGroups As String
  Public RangeClients As String
  Public RangeClientTypes 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 Items As New List(Of AccountFloatingRatePaymentReviewItem)
  
  Public Sub New()
  End Sub
  
  Public Sub New(accountFloatingRatePaymentReview As finAccountFloatingRatePaymentReview)
    
    Dim ReviewItem As finAccountFloatingRatePaymentReviewItem
    
    With accountFloatingRatePaymentReview
      Me.AccountTypeId = .AccountTypeId
      Me.AdjustPaymentInstructionsOnly = .AdjustPaymentInstructionsOnly
      Me.ArrangementDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.ArrangementDate)
      Me.ArrangementType = .ArrangementType
      Me.MaturityDateLessPeriod = .MaturityDateLessPeriod
      Me.MaturityDatePlusPeriod = .MaturityDatePlusPeriod
      Me.OverrideInterestInstruction = .OverrideInterestInstructionText
      Me.PrintAdvice = .PrintAdvice
      Me.RegularPaymentEarliestDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.RegularPaymentEarliestDate)
      
      Me.RangeAccountManagers = .RangeAccountManagers
      Me.RangeAccounts = .RangeAccounts
      Me.RangeBranches = .RangeBranches
      Me.RangeClientGroups = .RangeClientGroups
      Me.RangeClients = .RangeClients
      Me.RangeClientTypes = .RangeClientTypes
      Me.RangeDepartments = .RangeDepartments
      Me.RangeEntities = .RangeEntities
      Me.RangeExternalPartiesBrokers = .RangeExternalPartiesBrokers
      Me.RangeExternalPartiesBrokersIncludeSub = .RangeExternalPartiesBrokersIncludeSub
      Me.RangeExternalPartiesDealers = .RangeExternalPartiesDealers
      Me.RangeExternalPartiesDealersIncludeSub = .RangeExternalPartiesDealersIncludeSub
      
      ' Items
      For Each ReviewItem In accountFloatingRatePaymentReview
        Me.Items.Add(New AccountFloatingRatePaymentReviewItem(ReviewItem))
      Next 
    End With
    
  End Sub
  
End Class


''' &lt;summary&gt;
'''  Account Floating Rate Payment Review Item.
''' &lt;/summary&gt;
Public Class AccountFloatingRatePaymentReviewItem
  
  ' Properties
  Public AccountId As String
  Public AccountName As String
  Public AccountPk As Integer
  Public CanCommit As Boolean
  Public Change As String
  Public CurrentDifference As String
  Public CurrentFinalPaymentDate As Date?
  Public CurrentMaturityDate As Date?
  Public CurrentRegularPayment As Decimal
  Public Include As Boolean
  Public InterestInstruction As String
  Public InvalidMessage As String
  Public NewFinalPayment As Decimal
  Public NewFirstPaymentDate As Date?
  Public NewMaturityDate As Date?
  Public NewRegularPayment As Decimal
  Public PaymentCycle As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(accountFloatingRatePaymentReviewItem As finAccountFloatingRatePaymentReviewItem)
    
    With accountFloatingRatePaymentReviewItem      
      Me.AccountId = .AccountId
      Me.AccountPk = .AccountPk
      Me.AccountName = .AccountName
      Me.CanCommit = .CanCommit()
      Me.CurrentDifference = .FinalDateChangeText()
      Me.CurrentFinalPaymentDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.CurrentFinalPaymentDate)
      Me.CurrentMaturityDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.CurrentMaturityDate)
      Me.CurrentRegularPayment = .CurrentRegularPayment
      Me.Include = .Include
      Me.InterestInstruction = .InterestInstructionText
      Me.InvalidMessage = .InvalidMessageResolved
      Me.PaymentCycle = .PaymentCycle
      
      ' Change
      If .NewMaturityDate = Nothing Then
        ' Do not set 'New' values
      Else 
        Me.NewRegularPayment = .NewRegularPayment
        Me.NewFirstPaymentDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.NewFirstPaymentDate)
        Me.NewFinalPayment = .NewFinalPayment      
        Me.NewMaturityDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.NewMaturityDate)
        
        If .CurrentMaturityDate = .NewMaturityDate Then
          If .CurrentRegularPayment = .NewRegularPayment Then
            Me.Change = ""
          ElseIf .CurrentRegularPayment &lt; .NewRegularPayment Then
            Me.Change = "+" &amp; finBLShared.FormatCurrency(.NewRegularPayment - .CurrentRegularPayment, True)
          Else
            Me.Change = "-" &amp; finBLShared.FormatCurrency(.CurrentRegularPayment - .NewRegularPayment, True)
          End If
        Else
          Me.Change = .MaturityDateChangeText
        End If
      End If
    End With
    
  End Sub
  
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 AccountTypeId As String
  Public AdjustPaymentInstructionsOnly As Boolean
  Public ArrangementDate As Date
  Public ArrangementType As String
  Public MaturityDateLessPeriod As String
  Public MaturityDatePlusPeriod As String
  Public OverrideInterestInstruction As String
  Public PrintAdvice As Boolean
  Public RegularPaymentEarliestDate As Date?
  
  ' Ranges
  Public RangeAccountManagers As String
  Public RangeAccounts As String
  Public RangeBranches As String
  Public RangeClientGroups As String
  Public RangeClients As String
  Public RangeClientTypes 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
  
  ' Other
  Public ProcessId As String
  Public RefreshData As String
  
  ' For Item Summary
  Public AccountId 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</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "AccountFloatingRatePaymentReview".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&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 Floating Rate Loan Payment Reviews you have processed."&gt;Recent Floating Rate Loan Payment Reviews&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Select the Processing options you wish to run."&gt;Processing options&lt;/li&gt;
        &lt;li tabId="Items" tooltipText="Choose whether to Update Floating Rate Loan Payments."&gt;Floating Rate Loan Payments&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:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountType"&gt;Select the Account Type&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOptions"&gt;Options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAdjustPaymentInstructionsOnly" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboMaturityDateLessPeriod"&gt;Shortened:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboMaturityDateLessPeriod" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboMaturityDatePlusPeriod"&gt;Lengthened:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboMaturityDatePlusPeriod" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblUpdateOptions"&gt;Update options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateArrangementDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateArrangementDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboArrangementType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboArrangementType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboOverrideInterestInstruction"&gt;Instruction:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboOverrideInterestInstruction" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateRegularPaymentEarliestDate"&gt;Earliest date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateRegularPaymentEarliestDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkPrintAdvice" type="checkbox" /&gt;&lt;/th&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="Accounts"&gt;
          &lt;th&gt;&lt;label for="txtRangeAccountsLoansFloatingRate"&gt;Accounts:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccountsLoansFloatingRate" lookupCaption="Accounts" /&gt;&lt;/td&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="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="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="Clients"&gt;
          &lt;th&gt;&lt;label for="txtRangeClients"&gt;Clients:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClients" lookupCaption="Clients" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ClientGroups"&gt;
          &lt;th&gt;&lt;label for="txtRangeClientGroups"&gt;Client Groups:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClientGroups" lookupCaption="Clients Groups" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="ClientTypes"&gt;
          &lt;th&gt;&lt;label for="txtRangeClientTypes"&gt;Client Types:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeClientTypes" lookupCaption="Clients Types" /&gt;&lt;/td&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="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;/table&gt;
    &lt;/div&gt;

    &lt;!-- Update Items --&gt;
    &lt;div id="pageItems"&gt;
      &lt;div class="is-dock-fill is-split-container split5050"&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridItems"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div id="wbSummary" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&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 mAccountFloatingRatePaymentReview;

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

  //   General
  lblAccountType: null,
  cboAccountType: null,

  lblOptions: null,
  chkAdjustPaymentInstructionsOnly: null,
  cboMaturityDateLessPeriod: null,
  cboMaturityDatePlusPeriod: null,
  
  lblUpdateOptions: null,
  dateArrangementDate: null,
  cboArrangementType: null,
  cboOverrideInterestInstruction: null,
  dateRegularPaymentEarliestDate: null,
  chkPrintAdvice: null,

  lblRanges: null,
  txtRangeAccountsLoansFloatingRate: null,
  txtRangeAccountManagers: null,
  txtRangeBranches: null,
  txtRangeExternalPartiesBrokers: null,
  chkRangeExternalPartiesBrokersIncludeSub: null,
  txtRangeClients: null,
  txtRangeClientGroups: null,
  txtRangeClientTypes: null,
  txtRangeExternalPartiesDealers: null,
  chkRangeExternalPartiesDealersIncludeSub: null,
  txtRangeDepartments: null,
  txtRangeEntities: null,

  //   Items
  gridItems: null,
  wbSummary: 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 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.lblAccountType = widget.UI.Label("lblAccountType", {});
  C.cboAccountType = widget.UI.DBCombo("cboAccountType", {
    allowBlank: false,
    limitToList: true,
    
    onChange: cboAccountType_Change,
  });

  C.lblOptions = widget.UI.Label("lblOptions", {});
  C.chkAdjustPaymentInstructionsOnly = widget.UI.CheckBox("chkAdjustPaymentInstructionsOnly", {
    caption: "Include 'Adjust Payment' Instructions only?",
    captionWrap: true,
    
    onChange: chkAdjustPaymentInstructionsOnly_Change,
  });
  C.cboMaturityDateLessPeriod = widget.UI.DateCycleComboBox("cboMaturityDateLessPeriod", {});
  C.cboMaturityDatePlusPeriod = widget.UI.DateCycleComboBox("cboMaturityDatePlusPeriod", {});
  
  C.lblUpdateOptions = widget.UI.Label("lblUpdateOptions", {});
  C.dateArrangementDate = widget.UI.DateBox("dateArrangementDate", {
    allowBlank: false,
    
    onChange: dateArrangementDate_Change,
  });
  C.cboArrangementType = widget.UI.InformationListComboBox("cboArrangementType", {});
  C.cboOverrideInterestInstruction = widget.UI.ComboBox("cboOverrideInterestInstruction", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_15,
    
    onChange: cboOverrideInterestInstruction_Change,
  });
  C.dateRegularPaymentEarliestDate = widget.UI.DateBox("dateRegularPaymentEarliestDate", {});
  C.chkPrintAdvice = widget.UI.CheckBox("chkPrintAdvice", {
    caption: "Print Advice?",
  });

  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?",
  });

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

  //   Items
  C.wbSummary = widget.UI.PreviewPane("wbSummary", {
    formActionHandler: Widget_NotificationHandler,
  });

  // 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: true,
    allowMultiRowSelect: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridItems_Action,
    onAfterRowActivate: gridItems_AfterRowActivate,
    onBeforeCellUpdate: gridItems_BeforeCellUpdate,
    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;
  mAccountFloatingRatePaymentReview = 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.OverrideInterestInstructionList, "Description");

      // 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 Floating Rate Loan Payment Review 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 Reviewing Floating Rate Loan Payments.", { heading: "Floating Rate Loan Payment Review 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
    C.cboAccountType.Text(mRecord.AccountTypeId);
    
    C.chkAdjustPaymentInstructionsOnly.Value(mRecord.AdjustPaymentInstructionsOnly);
    C.cboMaturityDateLessPeriod.Text(mRecord.MaturityDateLessPeriod);
    C.cboMaturityDatePlusPeriod.Text(mRecord.MaturityDatePlusPeriod);
    
    C.dateArrangementDate.Value(mRecord.ArrangementDate);
    C.cboArrangementType.Text(mRecord.ArrangementType);
    C.cboOverrideInterestInstruction.Text(mRecord.OverrideInterestInstruction);
    C.dateRegularPaymentEarliestDate.Value(mRecord.RegularPaymentEarliestDate);
    C.chkPrintAdvice.Value(mRecord.PrintAdvice);    
  }

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

  // Update Controls
  cboAccountType_Change();
  chkAdjustPaymentInstructionsOnly_Change();
  cboOverrideInterestInstruction_Change();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

  // Lists
  if (mRecord) {
    C.cboAccountType.RefreshFromStandardRange("AccountTypes", mRecord.AccountTypeSqlWhere);
    C.cboMaturityDateLessPeriod.ListFromCsvString(mRecord.PeriodList);
    C.cboMaturityDatePlusPeriod.ListFromCsvString(mRecord.PeriodList);
    C.cboArrangementType.SetComboFromInformationList("AccountPayReviewType", true, null, true);
    C.cboOverrideInterestInstruction.ListFromCollection(mRecord.OverrideInterestInstructionList, "Description");
  }

  // Controls
  if(mRecord) {
    // General
  
    // 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 (mAccountFloatingRatePaymentReview) {
    // Controls
    C.cboAccountType.Text(mAccountFloatingRatePaymentReview.AccountTypeId);
    
    C.chkAdjustPaymentInstructionsOnly.Value(mAccountFloatingRatePaymentReview.AdjustPaymentInstructionsOnly);
    C.cboMaturityDateLessPeriod.Text(mAccountFloatingRatePaymentReview.MaturityDateLessPeriod);
    C.cboMaturityDatePlusPeriod.Text(mAccountFloatingRatePaymentReview.MaturityDatePlusPeriod);
    
    C.dateArrangementDate.Value(mAccountFloatingRatePaymentReview.ArrangementDate);
    C.cboArrangementType.Text(mAccountFloatingRatePaymentReview.ArrangementType);
    C.cboOverrideInterestInstruction.Text(mAccountFloatingRatePaymentReview.OverrideInterestInstruction);
    C.dateRegularPaymentEarliestDate.Value(mAccountFloatingRatePaymentReview.RegularPaymentEarliestDate);
    C.chkPrintAdvice.Value(mAccountFloatingRatePaymentReview.PrintAdvice);

    // Ranges
    C.txtRangeAccountManagers.Text(mAccountFloatingRatePaymentReview.RangeAccountManagers);
    C.txtRangeAccountsLoansFloatingRate.Text(mAccountFloatingRatePaymentReview.RangeAccounts);    
    C.txtRangeBranches.Text(mAccountFloatingRatePaymentReview.RangeBranches);
    C.txtRangeClientGroups.Text(mAccountFloatingRatePaymentReview.RangeClientGroups);
    C.txtRangeClients.Text(mAccountFloatingRatePaymentReview.RangeClients);
    C.txtRangeClientTypes.Text(mAccountFloatingRatePaymentReview.RangeClientTypes);
    C.txtRangeDepartments.Text(mAccountFloatingRatePaymentReview.RangeDepartments);
    C.txtRangeEntities.Text(mAccountFloatingRatePaymentReview.RangeEntities);
    C.txtRangeExternalPartiesBrokers.Text(mAccountFloatingRatePaymentReview.RangeExternalPartiesBrokers);
    C.chkRangeExternalPartiesBrokersIncludeSub.Value(mAccountFloatingRatePaymentReview.RangeExternalPartiesBrokersIncludeSub);
    C.txtRangeExternalPartiesDealers.Text(mAccountFloatingRatePaymentReview.RangeExternalPartiesDealers);
    C.chkRangeExternalPartiesDealersIncludeSub.Value(mAccountFloatingRatePaymentReview.RangeExternalPartiesDealersIncludeSub);

    // Advanced
    if (!mAdvancedVisible) {
      var toggle = false;
      
      if (mAccountFloatingRatePaymentReview.RangeAccountManagers &amp;&amp; mAccountFloatingRatePaymentReview.RangeAccountManagers.length != 0 &amp;&amp; mRecord.ShowAccountManagers.toUpperCase() != "TRUE") toggle = true;
      if (mAccountFloatingRatePaymentReview.RangeAccounts &amp;&amp; mAccountFloatingRatePaymentReview.RangeAccounts.length != 0 &amp;&amp; mRecord.ShowAccounts.toUpperCase() != "TRUE") toggle = true;          
      if (mAccountFloatingRatePaymentReview.RangeBranches &amp;&amp; mAccountFloatingRatePaymentReview.RangeBranches.length != 0 &amp;&amp; mRecord.ShowBranches.toUpperCase() != "TRUE") toggle = true;      
      if (mAccountFloatingRatePaymentReview.RangeClientGroups &amp;&amp; mAccountFloatingRatePaymentReview.RangeClientGroups.length != 0 &amp;&amp; mRecord.ShowClientGroups.toUpperCase() != "TRUE") toggle = true;
      if (mAccountFloatingRatePaymentReview.RangeClients &amp;&amp; mAccountFloatingRatePaymentReview.RangeClients.length != 0 &amp;&amp; mRecord.ShowClients.toUpperCase() != "TRUE") toggle = true;   
      if (mAccountFloatingRatePaymentReview.RangeClientTypes &amp;&amp; mAccountFloatingRatePaymentReview.RangeClientTypes.length != 0 &amp;&amp; mRecord.ShowClientTypes.toUpperCase() != "TRUE") toggle = true;
      if (mAccountFloatingRatePaymentReview.RangeDepartments &amp;&amp; mAccountFloatingRatePaymentReview.RangeDepartments.length != 0 &amp;&amp; mRecord.ShowDepartments.toUpperCase() != "TRUE") toggle = true;     
      if (mAccountFloatingRatePaymentReview.RangeEntities &amp;&amp; mAccountFloatingRatePaymentReview.RangeEntities.length != 0 &amp;&amp; mRecord.ShowEntities.toUpperCase() != "TRUE") toggle = true;      
      if (mAccountFloatingRatePaymentReview.RangeExternalPartiesBrokers &amp;&amp; mAccountFloatingRatePaymentReview.RangeExternalPartiesBrokers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesBrokers.toUpperCase() != "TRUE") toggle = true;    
      if (mAccountFloatingRatePaymentReview.RangeExternalPartiesDealers &amp;&amp; mAccountFloatingRatePaymentReview.RangeExternalPartiesDealers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesDealers.toUpperCase() != "TRUE") toggle = true;           

      // Toggle
      if (toggle) AdvancedToggle();
    }
  }
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      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
      mAccountFloatingRatePaymentReview = 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;
  }
}

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

    accountTypeId: C.cboAccountType.Text(),
    
    adjustPaymentInstructionsOnly: C.chkAdjustPaymentInstructionsOnly.Value(),
    maturityDateLessPeriod: C.cboMaturityDateLessPeriod.Text(),
    maturityDatePlusPeriod: C.cboMaturityDatePlusPeriod.Text(),
    
    arrangementDate: C.dateArrangementDate.Value(),
    arrangementType: C.cboArrangementType.Text(),    
    overrideInterestInstruction: C.cboOverrideInterestInstruction.Text(),
    regularPaymentEarliestDate: C.dateRegularPaymentEarliestDate.Value(),
    printAdvice: C.chkPrintAdvice.Value(),

    rangeAccountManagers: C.txtRangeAccountManagers.Text(),    
    rangeAccounts: C.txtRangeAccountsLoansFloatingRate.Text(),   
    rangeBranches: C.txtRangeBranches.Text(),
    rangeClientGroups: C.txtRangeClientGroups.Text(),
    rangeClients: C.txtRangeClients.Text(),
    rangeClientTypes: C.txtRangeClientTypes.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(),
  }

  // Selected Accounts
  if (includeRefreshData &amp;&amp; mAccountFloatingRatePaymentReview) {
    params.RefreshData = JSON.stringify(mAccountFloatingRatePaymentReview);
  }

  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 = "";

      // Build Message
      message += "Are you sure you want to action these Payment changes?";

      // 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
      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 Floating Rate Loan Payment 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";
      }

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Floating Rate Loan Payment Review was successfully cancelled.");
          break;

        case "InProgressRefreshComplete":
          // Update Items
          mAccountFloatingRatePaymentReview = 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("Floating Rate Loan Payment Review Refresh is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          else {
            widget.UI.MsgBoxInfo("Floating Rate Loan Payment Review 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 (mAccountFloatingRatePaymentReview) mComplete = true;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Floating Rate Loan Payment Review 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 Floating Rate Loan Payment Review 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);
    }
  );
}

// ============
// 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 (mAccountFloatingRatePaymentReview) {
    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() {
  var ShowInvalidMessage = false;
  
  // Hide / Show Columns
  for (var i = 0; i &lt; mAccountFloatingRatePaymentReview.Items.length; i++) {
    var item = mAccountFloatingRatePaymentReview.Items[i];
    
    if (item.InvalidMessage) ShowInvalidMessage = true;
  }

  // Add Columns
  C.gridItems.ClearColumns();  
  C.gridItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true, });
  C.gridItems.AddColumnCode("AccountId", { caption: "Account" });
  C.gridItems.AddColumnString("AccountName", { caption: "Name" });
  C.gridItems.AddColumnCurrency("CurrentRegularPayment", { caption: "Payment" });
  C.gridItems.AddColumnDate("CurrentMaturityDate", { caption: "Maturity" });
  C.gridItems.AddColumnDate("CurrentFinalPaymentDate", { caption: "Final" });
  C.gridItems.AddColumnString("CurrentDifference", { caption: "Difference" });
  C.gridItems.AddColumnCurrency("NewRegularPayment", { caption: "New Payment", blankIfZero: true, });
  C.gridItems.AddColumnDate("NewFirstPaymentDate", { caption: "New First", blankIfZero: true, });
  C.gridItems.AddColumnCurrency("NewFinalPayment", { caption: "New Final Payment", blankIfZero: true, });
  C.gridItems.AddColumnDate("NewMaturityDate", { caption: "New Maturity", blankIfZero: true, });
  C.gridItems.AddColumnString("Change", { caption: "Change" });
  C.gridItems.AddColumnString("InvalidMessage", { caption: "Message", visible: ShowInvalidMessage });

  // Actions
  C.gridItems.Actions().Define([{ actionId: "Refresh", tooltipText: "Refresh Security Statements", icon: "Refresh"},
                                {},
                                { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                { actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },                                
                                { actionId: "SelectChecked", tooltipText: "Select all rows that are checked", icon: "Select_Checked" },
                                { actionId: "SelectUnchecked", tooltipText: "Select all rows that are not checked", icon: "Select_Unchecked" },                          
                                {},
                                { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" },
                               ]);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mAccountFloatingRatePaymentReview.Items.GetCacheKey = function (index) {
    var item = mAccountFloatingRatePaymentReview.Items[index];
    return item.AccountId;
  };
  mAccountFloatingRatePaymentReview.Items.GetPreviewFetchParameters = function (index) {
    var item = mAccountFloatingRatePaymentReview.Items[index];
    var o = CreateFinishParameters(false);
    o.AccountId = item.AccountId;
    return o;
  };

  // Refresh
  C.gridItems.VirtualDataRefresh(mAccountFloatingRatePaymentReview.Items);
  
  // Activate first row
  C.gridItems.ActivateFirstDataRow();
}

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

      // Refresh
      RefreshFloatingRatePaymentReview(true);
      break;      
    
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridItems.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mAccountFloatingRatePaymentReview.Items.length; i++) {
        if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
          indexes.push(i);
        }
        else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
          indexes.push(i);
        }
      }
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mAccountFloatingRatePaymentReview.Items.length; i++) {
        var item = mAccountFloatingRatePaymentReview.Items[i];
        indexes.push(i);
      }
      break;

    case "SELECTNONE":
      var indexes = [];
      break;
      
    case "SELECTCHECKED":
    case "SELECTUNCHECKED":
      var indexes = [];
      var selectedItem = mAccountFloatingRatePaymentReview.Items[C.gridItems.ActiveDataRowListIndex()];

      for (var i = 0; i &lt; mAccountFloatingRatePaymentReview.Items.length; i++) {
        var item = mAccountFloatingRatePaymentReview.Items[i];
        
        if (item.CanCommit) {
          if (actionId.toUpperCase() == "SELECTCHECKED" &amp;&amp; item.Include) indexes.push(i);
          if (actionId.toUpperCase() == "SELECTUNCHECKED" &amp;&amp; !item.Include) indexes.push(i);
        }        
      }
      break;
      
    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridItems.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
      var item = mAccountFloatingRatePaymentReview.Items[selectedItems[i]];
        if(item.CanCommit) item.Include = (actionId.toUpperCase() == "CHECK");
      }
      C.gridItems.VirtualDataRefresh(mAccountFloatingRatePaymentReview.Items, true, { retainSelectedRows: true });
      break;
  }

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

function gridItems_AfterRowActivate(e) {
  // Preview
  wbSummary_Preview();
}

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

  switch(e.columnKey) {
    case "Include":
      item.Include = e.newValue;    
      break;
  }
}

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

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

  // Read-Only
  if (!item.CanCommit) e.row.cells.Include.readOnly = true;

  // Style
  e.row.cells.AccountName.small = true;
  e.row.cells.InvalidMessage.small = true;
  e.row.cells.InvalidMessage.colour = "red";

  // Hyperlinks
  e.row.cells.AccountId.hyperlink = "app://FormShow?form=Accounts&amp;id=" + widget.UI.HtmlEncode(item.AccountId);
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Floating Rate Loan Payment Review 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" || mAccountFloatingRatePaymentReview)) {
    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 Floating Rate Loan Payment Review Processes will not be retained." });

    var options = {
      closeOnEscape: true,
      title: "Close Floating Rate Loan Payment Review 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)) {
        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() == "Items") {
    cmdFinish.prop("disabled", false);    
  }
  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":
        tabWizard_ValidatePost_General(validCallback);
        return;
        
      case "Items":
        var found = false;
        for (var i = 0; i &lt; mAccountFloatingRatePaymentReview.Items.length; i++) {
          var item = mAccountFloatingRatePaymentReview.Items[i];
          
          if (item.CanCommit &amp;&amp; item.Include) {
            found = true;
            break;
          }
        }
        
        // Error
        if (!found) {
          Ok = false;
          widget.UI.MsgBoxAlert("You have not selected any items to process.");
        }
        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
  RefreshFloatingRatePaymentReview();

  // Callback
  validCallback();
}

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

  // Enable form
  frmMain.FormEnable();
}

// ==============================
// Validates the specified Action
// ==============================
function ValidateAction(action) {
  for (var i = 0; i &lt; mRecord.ActionListValidation.length; i++) {
    var item = mRecord.ActionListValidation[i];    
    if (item == action) return true;
  }
  
  return false;
}

// ============================================
// Validates the specified Interest Instruction
// ============================================
function ValidateInterestInstruction(interestInstruction) {
  for (var i = 0; i &lt; mRecord.InterestInstructionListValidation.length; i++) {
    var item = mRecord.InterestInstructionListValidation[i];    
    if (item == interestInstruction) return true;
  }
  
  return false;
}

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

  // General
  AdvancedInitialiseSection("RangesHeading", mRecord.ShowRangesHeading);
  AdvancedInitialiseSection("Accounts", mRecord.ShowAccounts); 
  AdvancedInitialiseSection("AccountManagers", mRecord.ShowAccountManagers);
  AdvancedInitialiseSection("Branches", mRecord.ShowBranches);
  AdvancedInitialiseSection("Brokers", mRecord.ShowBrokers);
  AdvancedInitialiseSection("Clients", mRecord.ShowClients);
  AdvancedInitialiseSection("ClientGroups", mRecord.ShowClientGroups);
  AdvancedInitialiseSection("ClientTypes", mRecord.ShowClientTypes);
  AdvancedInitialiseSection("Dealers", mRecord.ShowDealers);  
  AdvancedInitialiseSection("Departments", mRecord.ShowDepartments);
  AdvancedInitialiseSection("Entities", mRecord.ShowEntities);    
}

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 RefreshFloatingRatePaymentReview(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 Floating Rate Loan Payments to review.&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 (mAccountFloatingRatePaymentReview &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 (mAccountFloatingRatePaymentReview &amp;&amp; mProcessId) {
          CancelRefreshCompleteBackgroundProcess(mProcessId, fromGridAction, RefreshFloatingRatePaymentReview_Post, function() {
            // Move back a page
            tabWizard_Move(-1);

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

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

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

function RefreshFloatingRatePaymentReview_Post() {
  // Running new process
  mMonitoringExisting = false;
  mAccountFloatingRatePaymentReview = null;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Floating Rate Loan Payment Review Refresh, please wait...");

  // 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 (Ok) {
    // Set Information from Process
    mProcessId = item.ProcessId;

    // Status-dependant
    switch (item.Status) {
      case "InProgressRefreshComplete":
        // Update Items
        mAccountFloatingRatePaymentReview = 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;
    }
  }
}

// ==============
// cboAccountType
// ==============
function cboAccountType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  if (C.cboAccountType.Text()) {
    // Block UI
    widget.UI.Block("Initialising, please wait...");
    
    // Params
    var params = {
      accountTypeId: C.cboAccountType.Text(),
      arrangementDate: C.dateArrangementDate.Value(),
    }
    
    // Default values (must be calculated as it depends on the Date Effective)
    widget.GetString("GetAccountTypeDefaults", params, cboAccountType_Change_Done, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();
      
      // Error Message
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }  
}

function cboAccountType_Change_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);

  // Update Controls
  if (data) {
    C.dateRegularPaymentEarliestDate.Value(data.RegularPaymentEarliestDate);
  }

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

// ==============================
// cboOverrideInterestInstruction
// ==============================
function cboOverrideInterestInstruction_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Get Selected item
  var item = mRecord.OverrideInterestInstructionList.GetItem(C.cboOverrideInterestInstruction.Text());
  if (item) {
    if (item.Code == "HoldPayment") {
      C.dateRegularPaymentEarliestDate.VisibleRow(false);
    }
    else {
      C.dateRegularPaymentEarliestDate.VisibleRow(true);
    }
  }
  else {
    C.dateRegularPaymentEarliestDate.VisibleRow(true);
  }  
}

// ================================
// chkAdjustPaymentInstructionsOnly
// ================================
function chkAdjustPaymentInstructionsOnly_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.cboOverrideInterestInstruction.VisibleRow(!C.chkAdjustPaymentInstructionsOnly.Value());
}

// ===================
// dateArrangementDate
// ===================
function dateArrangementDate_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Get default Regular Payment Earliest Date
  if (C.cboAccountType.Text() &amp;&amp; C.dateArrangementDate.Value()) {
    // Block UI
    widget.UI.Block("Initialising, please wait...");
  
    // Params
    var params = {
      accountTypeId: C.cboAccountType.Text(),
      arrangementDate: C.dateArrangementDate.Value(),
    }
    
    // Get Earliest Date
    widget.GetString("GetRegularPaymentEarliestDate", params, dateArrangementDate_Change_Done, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();
      
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }  
}

function dateArrangementDate_Change_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Update Controls
  if (data) {
    C.dateRegularPaymentEarliestDate.Value(data.RegularPaymentEarliestDate);
  }
  
  // Unblock UI
  widget.UI.Unblock();
}

// ========
// 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();
        }
      );
    }    
  }
}

// =========
// wbSummary
// =========
function wbSummary_Preview() {
  C.wbSummary.PreviewFromGridCollection(C.gridItems, mAccountFloatingRatePaymentReview.Items, "GetItemPreview");
}

// ============
// Get Schedule
// ============
function GetSchedule(params) {
  // Block UI
  widget.UI.Block("Initialising, please wait...");
  
  // Get Schedule
  widget.GetString("GetSchedule", params, GetSchedule_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();
    
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function GetSchedule_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Show Schedule
  widget.UI.Forms.ShowAccountSchedule({scheduleJson: data.Schedule, headingSummary: data.Heading, gotoDate: data.DateEffective });
  
  // Unblock
  widget.UI.Unblock();
}

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

    case "SHOWSCHEDULE":
      // Show Schedule
      var item = mAccountFloatingRatePaymentReview.Items[C.gridItems.ActiveDataRowListIndex()];
      
      if (item) {
        // Params
        var params = {
          accountId: item.AccountId,
          pk: item.Pk,
          dataUrl: data,
        }
        
        // Get Schedule
        GetSchedule(params);
      }
      else {
        widget.UI.MsgBoxAlert("Invalid item '" + C.gridItems.ActiveDataRowListIndex() + "'.");
      }
      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="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="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="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="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="ShowClients" 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="ShowClientGroups" 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="ShowClientTypes" 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="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="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="ReportColumnsToInclude" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Entered as a CSV string. Supported columns are: 
Include,Account,Name,Payment,Maturity,Final,Difference,PaymentNew,PaymentFinal,MaturityNew,Change</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>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DesktopMode" type="Boolean">
            <BlankTip />
            <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>