<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-07-25T23:28:05.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-04-25T22:42:34.0630000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-07-25T23:26:56.2200000</UpdatedUtcDate>
    <ScriptId>FIRC</ScriptId>
    <Description>Floating Interest Rate Change</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountFloatingInterestRateChange
Option Explicit On
Option Strict On

' #################################################################
' Account Floating Interest Rate Change
'
' Version: 1.01 (26/07/2024)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  16/05/2024  ISS      J031335   Created
'    1.01  26/07/2024  ISS      J033972   Moved shared functions to the Business Layer
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountFloatingInterestRateChange"

' Objects
Private WithEvents mAccountFloatingInterestRateChange As finAccountFloatingInterestRateChange
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.Execute"
      ' Called by Web Services to execute a Background Process that was initially queued in the Widget's UI (via the Finish event)
      Main = BackgroundProcess_Execute(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 "GetDateEarliestNewPayment"
      ' Get Date Earliest New Payment
      Main = GetDateEarliestNewPayment(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 "PrintFloatingInterestRateChangeList"
      ' Print Floating Interest Rate Change List
      Main = PrintFloatingInterestRateChangeList(parametersJson, returnValue)

    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 AccountFloatingInterestRateChange As finAccountFloatingInterestRateChange
  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 finAccountFloatingInterestRateChange Object
  If Success Then
    Success = CreateAccountFloatingInterestRateChange(Nothing, AccountFloatingInterestRateChange)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .ProcessId = mProcessId                 
      .AccountTypeId = AccountFloatingInterestRateChange.AccountTypeId
      
      ' Lists   
      .AccountTypeSqlWhere = finBL.AccountTypeFunctions.GetFloatingRateAccountTypeSqlWhere(True)

      ' 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 = "True"    
      .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" OrElse .ShowAccountManagers = "False" OrElse .ShowBranches = "False" OrElse .ShowBrokers = "False" OrElse .ShowClients = "False" OrElse .ShowClientGroups = "False" OrElse
          .ShowClientTypes = "False" OrElse .ShowDealers = "False" OrElse .ShowDepartments = "False" OrElse .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 finAccountFloatingInterestRateChange object from the Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function CreateAccountFloatingInterestRateChange(parameters As WizardFinishParameters,
                                                         ByRef accountFloatingInterestRateChange As finAccountFloatingInterestRateChange) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountFloatingInterestRateChange = finBL.CreateAccountFloatingInterestRateChange()

  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With accountFloatingInterestRateChange
      .AccountTypeId = parameters.AccountTypeId
      
      .DateEffective = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateEffective)
      .DateEffectiveOrEarliestNewPayment = parameters.DateEffectiveOrEarliestNewPayment
      .InterestRate = parameters.InterestRate
      
      .DateEarliestNewPayment = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateEarliestNewPayment)
      
      .Reference = parameters.Reference
      
      .ExecuteReportOnly = parameters.ExecuteReportOnly
      
      .RangeAccounts = parameters.RangeAccounts
      .RangeAccountManagers = parameters.RangeAccountManagers
      .RangeBranches = parameters.RangeBranches
      .RangeExternalPartiesBrokers = parameters.RangeExternalPartiesBrokers
      .RangeExternalPartiesBrokersIncludeSub = parameters.RangeExternalPartiesBrokersIncludeSub
      .RangeClients = parameters.RangeClients
      .RangeClientGroups = parameters.RangeClientGroups
      .RangeClientTypes = parameters.RangeClientTypes
      .RangeExternalPartiesDealers = parameters.RangeExternalPartiesDealers
      .RangeExternalPartiesDealersIncludeSub = parameters.RangeExternalPartiesDealersIncludeSub
      .RangeDepartments = parameters.RangeDepartments
      .RangeEntities = parameters.RangeEntities
    End With
  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
  
  ' Queue Background Process
  Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_HtmlWidgetScript(ScriptInfo.ScriptId, mParameters.ToSimpleJsonString(), mStartupParameters.ToSimpleJsonString(), WizardFinishParameters.ProcessId, mDesktopMode)
    
  If Success Then
    ' Context-specific functionality - not supported
    CompleteMessage = ""
  End If
  
  ' Response
  If Success Then
    Data = New With {
      .ProcessId = WizardFinishParameters.ProcessId,
      .CompleteMessage = CompleteMessage
    }
  End If

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

  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 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;
'''  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_Execute(ByRef returnValue As String) As Boolean
    
  Dim CountCommitted As Integer
  Dim FileName As String
  Dim FloatingInterestRateChange As AccountFloatingInterestRateChange
  Dim Json As String
  Dim strTemp 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 Floating Interest Rate Change Process")
  
  ' Get Account Floating Interest Rate Change
  If GetWizardFinishParameters(mParameters.ToSimpleJsonString(), WizardFinishParameters) Then
    Success = CreateAccountFloatingInterestRateChange(WizardFinishParameters, mAccountFloatingInterestRateChange)
  Else 
    Success = False
  End If

  ' Notify
  If Success Then
    If mAccountFloatingInterestRateChange.ExecuteReportOnly Then
      mProcessStatus.AddEvent_Information("Process Option: PREVIEW (Interest Rates NOT updated)")
    Else 
      mProcessStatus.AddEvent_Information("Process Option: PROCESS (Interest Rates updated)")
    End If    
  End If
    
  ' Commit
  If Success Then
    Success = mAccountFloatingInterestRateChange.Execute()
  End If
  
  ' Get JSON version of the Object
  If Success AndAlso (Not mAccountFloatingInterestRateChange.IsCancelled) Then
    FloatingInterestRateChange = New AccountFloatingInterestRateChange(mAccountFloatingInterestRateChange)
    
    mProcessStatus.AddEvent_Information("Saving Floating Interest Rate Change details")
    
    ' Save Floating Interest Rate Change details
    If finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FloatingInterestRateChange, Json) Then
      mProcessStatus.OtherDetails.SetString("FloatingInterestRateChangeJson", Json)
    Else 
      Success = False
    End If   
  End If  
  
  ' The above file has been saved to Downloads but, we can also attach it to any Success email
  If Success AndAlso (Not mAccountFloatingInterestRateChange.IsCancelled) Then
    mProcessStatus.AddEvent_Information("Generating PDF Summary")
    
    FileName = finBL.Runtime.FileUtilities.GetTemporaryFileName("AccountFloatingInterestRateChangeSummary", "pdf")
    
    ' Create Summary
    If CreateAccountFloatingInterestRateChangeSummaryPdf(FloatingInterestRateChange, FileName) Then
      ' Attach File
      mProcessStatus.Attachments.AddDataFromFile(FileName, Nothing)
  
      ' Delete Temporary file
      finBL.Runtime.FileUtilities.DeleteFile(FileName, True)
    End If
  End If
  
  ' Warnings exist?
  If Success Then
    If mAccountFloatingInterestRateChange.IsCancelled Then
      If mAccountFloatingInterestRateChange.Errors.Count &lt;= 1 Then
        mProcessStatus.AddEvent_Information("Account Floating Interest Rate Change was CANCELLED.")
      Else
        strTemp = String.Format("Account Floating Interest Rate Change was CANCELLED with {0} error{1} occuring.", mAccountFloatingInterestRateChange.Errors.Count - 1, IIf(mAccountFloatingInterestRateChange.Errors.Count - 1 = 1, "", "s"))        
        mProcessStatus.AddEvent_Warning(strTemp, String.Format("Interest Rates were {0}updated.", IIf(mAccountFloatingInterestRateChange.ExecuteReportOnly, "NOT ", "")))
      End If
    Else 
      If mAccountFloatingInterestRateChange.Errors.Count = 0 Then
        If mAccountFloatingInterestRateChange.ExecuteReportOnly Then 
          strTemp = "Interest Rates were NOT updated."
        Else 
          strTemp = "Interest Rates were updated."
        End If      
        mProcessStatus.AddEvent_Information("Account Floating Interest Rate Change completed successfully. " &amp; strTemp)
      Else          
        CountCommitted = (mAccountFloatingInterestRateChange.CountProcessed - mAccountFloatingInterestRateChange.Errors.Count)
        If mAccountFloatingInterestRateChange.ExecuteReportOnly Then
          strTemp = String.Format("Interest Rates were NOT updated, however {0} were identified as 'Pending'.", mAccountFloatingInterestRateChange.Errors.Count)
        Else
          strTemp = String.Format("{0} Interest Rate change{1} committed, {2} left 'Pending'.", CountCommitted, IIf(CountCommitted = 1, "", "s"), mAccountFloatingInterestRateChange.Errors.Count)
        End If
        mProcessStatus.AddEvent_Warning("Account Floating Interest Rate Change completed.", strTemp)
      End If
    End If    
  ElseIf mAccountFloatingInterestRateChange IsNot Nothing Then
    ' Error occurred (but object was still initialised)
    If mAccountFloatingInterestRateChange.CountProcessed &lt;&gt; 0 AndAlso (Not mAccountFloatingInterestRateChange.ExecuteReportOnly) Then
      mProcessStatus.AddEvent_Warning(String.Format("{0} change{1} were committed.", mAccountFloatingInterestRateChange.CountProcessed, IIf(mAccountFloatingInterestRateChange.CountProcessed = 1, "", "s")))
    End If
  End If
  
  Return Success
  
End Function

Private Sub mAccountFloatingInterestRateChange_Progress(progress As Double, caption As String) Handles mAccountFloatingInterestRateChange.Progress

  ' Record Event
  If Len(caption) &lt;&gt; 0 Then
    mProcessStatus.AddEvent_Information(caption)
  End If  

  ' Cancel Requested?
  If Not mAccountFloatingInterestRateChange.IsCancelled Then
    ' Cancel
    If mProcessStatus.IsCancelRequested() Then
      mAccountFloatingInterestRateChange.Cancel()
    End If      
  End If

End Sub


Private Function CreateAccountFloatingInterestRateChangeSummaryPdf(accountFloatingInterestRateChange As AccountFloatingInterestRateChange,
                                                                   filename As String) As Boolean

  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim SummaryTableHeaderInfo As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' 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 = GetAccountFloatingInterestRateChangeSummary(accountFloatingInterestRateChange, 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("Report options")
        .AddCaptionCodeDescription("Account Type:", accountFloatingInterestRateChange.AccountTypeId, finBL.AccountTypes)
        .AddCaptionPercentage("Interest Rate:", accountFloatingInterestRateChange.InterestRate / 100, 4, True)        
        .AddCaptionDate("Effective Date:", finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(accountFloatingInterestRateChange.DateEffective))
        .AddCheckBox("Or earliest payment date?", accountFloatingInterestRateChange.DateEffectiveOrEarliestNewPayment)
        .AddCaptionDate("Earliest Date:", finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(accountFloatingInterestRateChange.DateEarliestNewPayment))

        If accountFloatingInterestRateChange.ExecuteReportOnly Then
          .AddCaptionText("Process Option:", "PREVIEW (Interest Rates NOT updated)", iseSummaryTableCellClass.NormalBold)
        Else 
          .AddCaptionText("Process Option:", "PROCESS (Interest Rates updated)", iseSummaryTableCellClass.NormalBold)
        End If
        
        ' Ranges
        If Len(accountFloatingInterestRateChange.RangeAccounts) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeAccountManagers) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeBranches) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeExternalPartiesBrokers) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeClients) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeClientGroups) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeClientTypes) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeExternalPartiesDealers) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeDepartments) &lt;&gt; 0 OrElse Len(accountFloatingInterestRateChange.RangeEntities) &lt;&gt; 0 Then
          .AddSectionHeading2("Ranges")
        End If        
        If Len(accountFloatingInterestRateChange.RangeAccounts) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.AccountsDeposits) &amp; ":", accountFloatingInterestRateChange.RangeAccounts)  
        If Len(accountFloatingInterestRateChange.RangeAccountManagers) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.AccountManagers) &amp; ":", accountFloatingInterestRateChange.RangeAccountManagers)  
        If Len(accountFloatingInterestRateChange.RangeBranches) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Branches) &amp; ":", accountFloatingInterestRateChange.RangeBranches)
        If Len(accountFloatingInterestRateChange.RangeExternalPartiesBrokers) &lt;&gt; 0 Then 
          .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ExternalPartiesBrokers) &amp; ":", accountFloatingInterestRateChange.RangeExternalPartiesBrokers)
          .AddCaptionTick("Include Sub Brokers?", accountFloatingInterestRateChange.RangeExternalPartiesBrokersIncludeSub, True)
        End If
        If Len(accountFloatingInterestRateChange.RangeClients) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Clients) &amp; ":", accountFloatingInterestRateChange.RangeClients)
        If Len(accountFloatingInterestRateChange.RangeClientGroups) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ClientGroups) &amp; ":", accountFloatingInterestRateChange.RangeClientGroups)
        If Len(accountFloatingInterestRateChange.RangeClientTypes) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ClientTypes) &amp; ":", accountFloatingInterestRateChange.RangeClientTypes)  
        If Len(accountFloatingInterestRateChange.RangeExternalPartiesDealers) &lt;&gt; 0 Then 
          .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.ExternalPartiesDealers) &amp; ":", accountFloatingInterestRateChange.RangeExternalPartiesDealers)
          .AddCaptionTick("Include Sub Dealers?", accountFloatingInterestRateChange.RangeExternalPartiesDealersIncludeSub, True)
        End If        
        If Len(accountFloatingInterestRateChange.RangeDepartments) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Departments) &amp; ":", accountFloatingInterestRateChange.RangeDepartments)
        If Len(accountFloatingInterestRateChange.RangeEntities) &lt;&gt; 0 Then .AddCaptionText(finBL.Enums.isefinStandardRange_ToString(isefinStandardRange.Entities) &amp; ":", accountFloatingInterestRateChange.RangeEntities)        
      End With
    End With
  End If

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

    ' Append Information
    If accountFloatingInterestRateChange.ExecuteReportOnly Then
      sb.AppendH1("Floating Interest Range Changes Previewed")
    Else 
      sb.AppendH1("Floating Interest Range Changes Processed")
    End If    
    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 Account Floating Interest Rate Change Summary Pdf.")
  End If

  Return Success

End Function

Private Function GetAccountFloatingInterestRateChangeSummary(accountFloatingInterestRateChange As AccountFloatingInterestRateChange,
                                                             ByRef summaryTables As ISSummaryTables) As Boolean

  Dim Account As AccountFloatingRateChangeProcessAccount
  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("Account")
    Columns.Add("Name")
    Columns.Add("EffectiveDate")
    Columns.Add("InterestRate")
    Columns.Add("Pending")
    Columns.Add("Message")
  Else 
    Columns.FromCsvString(mReportColumnsToInclude)
  End If
  
  ' DataTable
  With dt.Columns
    If Columns.Exists("Account") Then .Add("Account", GetType(String))
    If Columns.Exists("Name") Then .Add("Name", GetType(String))    
    If Columns.Exists("EffectiveDate") Then .Add("EffectiveDate", GetType(Date))
    If Columns.Exists("InterestRate") Then .Add("InterestRate", GetType(Double))
    If Columns.Exists("PremiumRate") Then .Add("PremiumRate", GetType(Double))    
    If Columns.Exists("Instruction") Then .Add("Instruction", GetType(String))    
    If Columns.Exists("OriginalPayment") Then .Add("OriginalPayment", GetType(Decimal))
    If Columns.Exists("OriginalMaturity") Then .Add("OriginalMaturity", GetType(Date)) 
    If Columns.Exists("FirstPayment") Then .Add("FirstPayment", GetType(Date))
    If Columns.Exists("NewPayment") Then .Add("NewPayment", GetType(Decimal))
    If Columns.Exists("NewMaturity") Then .Add("NewMaturity", GetType(Date))    
    If Columns.Exists("Pending") Then .Add("Pending", GetType(Boolean))
    If Columns.Exists("Message") Then .Add("Message", GetType(String))                   
  End With

  ' Add to Summary Table
  For Each Account In accountFloatingInterestRateChange.Accounts
    DataRow = dt.NewRow()
    With Account
      If Columns.Exists("Account") Then DataRow!Account = .AccountId
      If Columns.Exists("Name") Then DataRow!Name = .Name          
      If Columns.Exists("EffectiveDate") Then DataRow!EffectiveDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.DateEffective)
      If Columns.Exists("InterestRate") Then DataRow!InterestRate = .InterestRate
      If Columns.Exists("PremiumRate") Then DataRow!PremiumRate = .InterestRatePremium
      If Columns.Exists("Instruction") Then DataRow!Instruction = .InterestInstruction  
      If Columns.Exists("OriginalPayment") Then DataRow!OriginalPayment = .OriginalPaymentRegular  
      If Columns.Exists("OriginalMaturity") Then DataRow!OriginalMaturity = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.OriginalMaturityDate)  
      If Columns.Exists("FirstPayment") Then DataRow!FirstPayment = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.NewPaymentRegularFirstDate)   
      If Columns.Exists("NewPayment") Then DataRow!NewPayment = .NewPaymentRegular     
      If Columns.Exists("NewMaturity") Then DataRow!NewMaturity = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.NewMaturityDate)  
      If Columns.Exists("Pending") Then DataRow!Pending = .Pending
      If Columns.Exists("Message") Then DataRow!Message = .Message                                    
    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 Floating Interest Rate Change Summary.")
  End If

  Return Success

End Function
  
''' &lt;summary&gt;
'''  Get Account Type Defaults.
''' &lt;/summary&gt;
Private Function GetAccountTypeDefaults(ByRef returnValue As String) As Boolean
  
  Dim AccountTypeId As String
  Dim Data As Object
  Dim DateEarliestNewPayment As Date
  Dim DateEffective As Date
  Dim InterestEffectiveDateOrEarliestPaymentDate As Boolean
  Dim InterestRate As Double
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Parameters
  With mCombinedParameters
    AccountTypeId = .GetString("AccountTypeId")
    DateEffective = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateEffective"))
  End With
  
  ' Get Defaults
  If finBL.AccountTypes.Exists(AccountTypeId) Then
    With finBL.AccountTypes(AccountTypeId)
      InterestRate = .InterestRate
      InterestEffectiveDateOrEarliestPaymentDate = .InterestEffectiveDateOrEarliestPaymentDate
      
      If Len(.InterestEarliestDateDefault) = 0 Then
        DateEarliestNewPayment = Nothing
      Else
        DateEarliestNewPayment = finBL.Utilities.DateCycleGetTermEndDate(.InterestEarliestDateDefault, DateEffective)
      End If
    End With
  End If
  
  ' Build Object
  If Success Then
    Data = New With {
      .InterestRate = InterestRate,
      .InterestEffectiveDateOrEarliestPaymentDate = InterestEffectiveDateOrEarliestPaymentDate,
      .DateEarliestNewPayment = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(DateEarliestNewPayment)
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get Date Earliest New Payment.
''' &lt;/summary&gt;
Private Function GetDateEarliestNewPayment(ByRef returnValue As String) As Boolean
  
  Dim AccountTypeId As String
  Dim Data As Object
  Dim DateEarliestNewPayment As Date
  Dim DateEffective As Date
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Parameters
  With mCombinedParameters
    AccountTypeId = .GetString("AccountTypeId")
    DateEffective = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateEffective"))
  End With
  
  ' Get Defaults
  If finBL.AccountTypes.Exists(AccountTypeId) AndAlso Len(finBL.AccountTypes(AccountTypeId).InterestEarliestDateDefault) &lt;&gt; 0 Then
    DateEarliestNewPayment = finBL.Utilities.DateCycleGetTermEndDate(finBL.AccountTypes(AccountTypeId).InterestEarliestDateDefault, DateEffective)
  End If
  
  ' Build Object
  If Success Then
    Data = New With {
      .DateEarliestNewPayment = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(DateEarliestNewPayment)
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Print Floating Interest Rate Change List.
''' &lt;/summary&gt;
Private Function PrintFloatingInterestRateChangeList(parametersJson As String,
                                                     ByRef returnValue As String) As Boolean

  Dim FileDownloadInfo As finFileDownloadInfo
  Dim FileName As String  
  Dim FloatingInterestRateChange As AccountFloatingInterestRateChange
  Dim obj As Object
  Dim ProcessId As String
  Dim ProcessStatus As finCloudConnectProcessStatus
  Dim Success As Boolean
  
  ' Assume Success
  Success = False
  
  ' Parameters
  With mCombinedParameters
    ProcessId = .GetString("ProcessId")
  End With

  ' Get Process Status
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusObject(ProcessId, ProcessStatus)
  
  ' Get Floating Interest Rate Change Object
  If Success Then
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(ProcessStatus.OtherDetails.GetString("FloatingInterestRateChangeJson"), GetType(AccountFloatingInterestRateChange), obj) Then
      FloatingInterestRateChange = DirectCast(obj, AccountFloatingInterestRateChange)
    Else 
      Success = False
    End If
  End If
  
  ' Get Summary
  If Success Then
    FileName = finBL.Runtime.FileUtilities.GetTemporaryFileName("AccountFloatingInterestRateChangeSummary", "pdf")
    
    If CreateAccountFloatingInterestRateChangeSummaryPdf(FloatingInterestRateChange, FileName) Then
      FileDownloadInfo = finBL.CreateFileDownloadInfo()
      With FileDownloadInfo
        If .LoadFile(FileName) Then
          returnValue = .ToXmlString()
        Else
          Success = False
        End If
      End With
    Else 
      Success = False
    End If
    
    ' Delete temporary file
    finBL.Runtime.FileUtilities.DeleteFile(FileName, True)
  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

  ' Lists
  Public AccountTypeSqlWhere 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

  ' Configuration
  Public PromptOnCommit As Boolean

End Class



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

  Public ProcessId As String

  Public Sub New(processId As String)

    Me.ProcessId = processId

  End Sub

End Class



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

  ' Parameters
  Public AccountTypeId As String
  
  Public DateEffective As Date
  Public DateEffectiveOrEarliestNewPayment As Boolean
  Public InterestRate As Double
  
  Public DateEarliestNewPayment As Date?
  
  Public Reference As String
  
  Public ExecuteReportOnly As Boolean
  
  ' Ranges
  Public RangeAccounts As String
  Public RangeAccountManagers As String  
  Public RangeBranches As String
  Public RangeExternalPartiesBrokers As String
  Public RangeExternalPartiesBrokersIncludeSub As Boolean
  Public RangeClients As String
  Public RangeClientGroups As String
  Public RangeClientTypes As String
  Public RangeExternalPartiesDealers As String
  Public RangeExternalPartiesDealersIncludeSub As Boolean
  Public RangeDepartments As String
  Public RangeEntities As String

  ' Other
  Public ProcessId As String

End Class



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

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

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

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

  End Sub

End Class



''' &lt;summary&gt;
'''  A JSON version of the finAccountFloatingInterestRateChange class to be used in reports.
''' &lt;/summary&gt;
Public Class AccountFloatingInterestRateChange
  
  Public AccountTypeId As String
  
  Public DateEffective As Date
  Public DateEffectiveOrEarliestNewPayment As Boolean
  Public InterestRate As Double
  
  Public DateEarliestNewPayment As Date?
  
  Public Reference As String
  
  Public ExecuteReportOnly As Boolean
  
  Public RangeAccounts As String
  Public RangeAccountManagers As String  
  Public RangeBranches As String
  Public RangeExternalPartiesBrokers As String
  Public RangeExternalPartiesBrokersIncludeSub As Boolean
  Public RangeClients As String
  Public RangeClientGroups As String
  Public RangeClientTypes As String
  Public RangeExternalPartiesDealers As String
  Public RangeExternalPartiesDealersIncludeSub As Boolean
  Public RangeDepartments As String
  Public RangeEntities As String
  
  Public Accounts As New List(Of AccountFloatingRateChangeProcessAccount)
  Public Errors As New List(Of AccountFloatingRateChangeProcessError)
  
  Public Sub New()
  End Sub
  
  Public Sub New(accountFloatingInterestRateChange As finAccountFloatingInterestRateChange)
    
    Dim DataRow As DataRow
    Dim RateChangeError As finAccountFloatingRateChangeProcessError
    
    With accountFloatingInterestRateChange
      ' Properties
      Me.AccountTypeId = .AccountTypeId
      
      Me.DateEffective = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.DateEffective)
      Me.DateEffectiveOrEarliestNewPayment = .DateEffectiveOrEarliestNewPayment
      Me.InterestRate = .InterestRate
      
      Me.DateEarliestNewPayment = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateEarliestNewPayment)
      
      Me.Reference = .Reference
      
      Me.ExecuteReportOnly = .ExecuteReportOnly
      
      ' Ranges
      Me.RangeAccounts = .RangeAccounts
      Me.RangeAccountManagers = .RangeAccountManagers
      Me.RangeBranches = .RangeBranches
      Me.RangeExternalPartiesBrokers = .RangeExternalPartiesBrokers
      Me.RangeExternalPartiesBrokersIncludeSub = .RangeExternalPartiesBrokersIncludeSub
      Me.RangeClients = .RangeClients
      Me.RangeClientGroups = .RangeClientGroups
      Me.RangeClientTypes = .RangeClientTypes
      Me.RangeExternalPartiesDealers = .RangeExternalPartiesDealers
      Me.RangeExternalPartiesDealersIncludeSub = .RangeExternalPartiesDealersIncludeSub
      Me.RangeDepartments = .RangeDepartments
      Me.RangeEntities = .RangeEntities
      
      ' Accounts
      For Each DataRow In .ReportDataTable.Rows
        Me.Accounts.Add(New AccountFloatingRateChangeProcessAccount(DataRow))
      Next 
      
      ' Errors
      For Each RateChangeError In .Errors
        Me.Errors.Add(New AccountFloatingRateChangeProcessError(RateChangeError))
      Next 
    End With    
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Account Floating Rate Change Process Account.
''' &lt;/summary&gt;
Public Class AccountFloatingRateChangeProcessAccount
  
  Public AccountId As String
  Public DateEffective As Date?
  Public InterestInstruction As String
  Public InterestRate As Double
  Public InterestRatePremium As Double
  Public Message As String
  Public Name As String
  Public NewMaturityDate As Date?
  Public NewPaymentRegular As Decimal
  Public NewPaymentRegularFirstDate As Date?
  Public OriginalMaturityDate As Date?
  Public OriginalPaymentRegular As Decimal
  Public Pending As Boolean
  
  Public Sub New()
  End Sub
  
  Public Sub New(row As DataRow)
    
    Me.AccountId = finBLShared.Database.GetFieldString(row!Account)
    Me.DateEffective = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(finBLShared.Database.GetFieldDate(row!DateEffective))
    Me.InterestInstruction = finBLShared.Database.GetFieldString(row!InterestInstructionText)
    Me.InterestRate = finBLShared.Database.GetFieldDouble(row!InterestRate)
    Me.InterestRatePremium = finBLShared.Database.GetFieldDouble(row!InterestRatePremium)
    Me.Message = finBLShared.Database.GetFieldString(row!Message)
    Me.Name = finBLShared.Database.GetFieldString(row!Name)
    Me.NewMaturityDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(finBLShared.Database.GetFieldDate(row!NewMaturityDate))
    Me.NewPaymentRegular = finBLShared.Database.GetFieldDecimal(row!NewPaymentRegular)
    Me.NewPaymentRegularFirstDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(finBLShared.Database.GetFieldDate(row!NewPaymentRegularFirstDate))
    Me.OriginalMaturityDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(finBLShared.Database.GetFieldDate(row!OriginalMaturityDate))
    Me.OriginalPaymentRegular = finBLShared.Database.GetFieldDecimal(row!OriginalPaymentRegular)
    Me.Pending = finBLShared.Database.GetFieldIntegerBoolean(row!Pending)
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Account Floating Rate Change Process Error.
''' &lt;/summary&gt;
Public Class AccountFloatingRateChangeProcessError
  
  Public AccountId As String
  Public AccountName As String
  Public ErrorMessage As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(accountFloatingRateChangeProcessError As finAccountFloatingRateChangeProcessError)
    
    With accountFloatingRateChangeProcessError
      Me.AccountId = .AccountId
      Me.AccountName = .AccountName
      Me.ErrorMessage = .ErrorMessageResolved
    End With
    
  End Sub
  
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

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

  div {
    font-size:11px;

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

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

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

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Floating Interest Rate Changes you have processed."&gt;Recent Floating Interest Rate Change Processing&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="Results" tooltipText="Print report and review and pending changes identified."&gt;Results&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:9em" /&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="lblInterestRate"&gt;Enter the new Interest Rate and date it is applied from&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateEffective"&gt;Effective Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateEffective" /&gt;&amp;nbsp;&amp;nbsp;&lt;input id="chkDateEffectiveOrEarliestNewPayment" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numInterestRate"&gt;Interest Rate:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numInterestRate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblEarliestDate"&gt;Enter the earliest date Payments can be adjusted&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateEarliestNewPayment"&gt;Earliest Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateEarliestNewPayment" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblReference"&gt;Enter a Reference to note against the Interest Rate change&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblProcess"&gt;Do you want to process or preview the Interest Rate change?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="rblProcessType"&gt;&lt;/div&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="txtRangeAccounts"&gt;Accounts:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRangeAccounts" lookupCaption="Accounts" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="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="Client 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="Client 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;!-- Results --&gt;
    &lt;div id="pageResults" style="display:flex; flex-direction:column"&gt;
      &lt;!-- Top Panel --&gt;
      &lt;div&gt;
        &lt;table class="is-form"&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label id="lblReport"&gt;Download the Floating Interest Rate Change report&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;button id="cmdDownloadReport" class="is-button ok"&gt;Download&lt;/button&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;div id="divProcessType" class="is-info-text info" style="display:flex; align-items:center;"&gt;&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;
          
          &lt;tr&gt;
            &lt;th&gt;&lt;label id="lblErrors"&gt;Pending&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      
      &lt;!-- Bottom Panel --&gt;
      &lt;div style="flex-grow:2; display:flex; flex-direction:row; position:relative"&gt;
        &lt;div style="flex-grow:1; position:relative"&gt;
          &lt;div id="gridPending" 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 mAccountFloatingInterestRateChange;

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

  //   General
  lblAccountType: null,
  cboAccountType: null,
  
  lblInterestRate: null,
  dateEffective: null,
  chkDateEffectiveOrEarliestNewPayment: null,
  numInterestRate: null,
  
  lblEarliestDate: null,
  dateEarliestNewPayment: null,
  
  lblReference: null,
  txtReference: null,
  
  lblProcess: null,
  rblProcessType: null,
  
  lblRanges: null,
  txtRangeAccounts: null,
  txtRangeAccountManagers: null,
  txtRangeBranches: null,
  txtRangeExternalPartiesBrokers: null,
  chkRangeExternalPartiesBrokersIncludeSub: null,
  txtRangeClients: null,
  txtRangeClientGroups: null,
  txtRangeClientTypes: null,
  txtRangeExternalPartiesDealers: null,
  chkRangeExternalPartiesDealersIncludeSub: null,
  txtRangeDepartments: null,
  txtRangeEntities: null,

  //   Results
  lblReport: null,
  divProcessType: null,
  lblErrors: null,
  gridPending: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdDownloadReport;
var cmdHistory;
var cmdAdvanced;

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

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

  // Controls
  //   General
  C.lblAccountType = widget.UI.Label("lblAccountType", {});
  C.cboAccountType = widget.UI.DBCombo("cboAccountType", {
    allowBlank: false,
    limitToList: true,
    
    onChange: cboAccountType_Change,
  });
  
  C.lblInterestRate = widget.UI.Label("lblInterestRate", {});
  C.dateEffective = widget.UI.DateBox("dateEffective", {
    allowBlank: false,
    
    onChange: dateEffective_Change,
  });
  C.chkDateEffectiveOrEarliestNewPayment = widget.UI.CheckBox("chkDateEffectiveOrEarliestNewPayment", {
    caption: "Or earliest payment date?",   
    captionWrap: true, 
    
    onChange: chkDateEffectiveOrEarliestNewPayment_Change,
  });
  C.numInterestRate = widget.UI.NumberBox("numInterestRate", {
    allowBlank: false,
    percentage: true,
    decimals: 4,
    minValue: 0,
    maxValue: 10000,
  });
  
  C.lblEarliestDate = widget.UI.Label("lblEarliestDate", {});
  C.dateEarliestNewPayment = widget.UI.DateBox("dateEarliestNewPayment", {});
  
  C.lblReference = widget.UI.Label("lblReference", {});
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20,
  });
  
  C.lblProcess = widget.UI.Label("lblProcess", {});
  C.rblProcessType = widget.UI.RadioButtonList("rblProcessType", {
    allowBlank: false,
    layout: "vertical",
    list: [{ caption: "Process Interest Rate changes", value: "PROCESS" }, { caption: "Preview Interest Rate changes (does not process changes)", value: "PREVIEW" }],
  });

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

  //   Results
  C.lblReport = widget.UI.Label("lblReport", {});
  C.divProcessType = $("#divProcessType");
  C.lblErrors = widget.UI.Label("lblErrors", {});

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

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

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

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

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

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

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

    onAction: gridPending_Action,
    onInitialiseRow: gridPending_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"); });

  cmdDownloadReport = $("#cmdDownloadReport");
  cmdDownloadReport.click(function() { Form_ExecuteAction("DownloadReport"); });

  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
  C.rblProcessType.Value("PREVIEW");

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

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mAccounts = null;
  mAccountFloatingInterestRateChange = 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

      // 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 Interest Rate Change 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 Floating Interest Rate Change.", { heading: "Floating Interest Rate Changes 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);
  }

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

  // Update Controls
  cboAccountType_Change();
  chkDateEffectiveOrEarliestNewPayment_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);
  }

  // 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 (mAccountFloatingInterestRateChange) {
    // Controls
    C.cboAccountType.Text(mAccountFloatingInterestRateChange.AccountTypeId);
    
    C.dateEffective.Value(mAccountFloatingInterestRateChange.DateEffective);
    C.chkDateEffectiveOrEarliestNewPayment.Value(mAccountFloatingInterestRateChange.DateEffectiveOrEarliestNewPayment);
    C.numInterestRate.Value(mAccountFloatingInterestRateChange.InterestRate);
    
    C.dateEarliestNewPayment.Value(mAccountFloatingInterestRateChange.DateEarliestNewPayment);
    
    C.txtReference.Text(mAccountFloatingInterestRateChange.Reference);
    
    if (mAccountFloatingInterestRateChange.ExecuteReportOnly) {
      C.rblProcessType.Value("PREVIEW");
    }
    else {
      C.rblProcessType.Value("PROCESS");
    }

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

    // Advanced
    if (!mAdvancedVisible) {
      var toggle = false;
      
      if (mAccountFloatingInterestRateChange.RangeAccounts &amp;&amp; mAccountFloatingInterestRateChange.RangeAccounts.length != 0 &amp;&amp; mRecord.ShowAccounts.toUpperCase() != "TRUE") toggle = true;
      if (mAccountFloatingInterestRateChange.RangeAccountManagers &amp;&amp; mAccountFloatingInterestRateChange.RangeAccountManagers.length != 0 &amp;&amp; mRecord.ShowAccountManagers.toUpperCase() != "TRUE") toggle = true;                 
      if (mAccountFloatingInterestRateChange.RangeBranches &amp;&amp; mAccountFloatingInterestRateChange.RangeBranches.length != 0 &amp;&amp; mRecord.ShowBranches.toUpperCase() != "TRUE") toggle = true;    
      if (mAccountFloatingInterestRateChange.RangeExternalPartiesBrokers &amp;&amp; mAccountFloatingInterestRateChange.RangeExternalPartiesBrokers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesBrokers.toUpperCase() != "TRUE") toggle = true;    
      if (mAccountFloatingInterestRateChange.RangeClients &amp;&amp; mAccountFloatingInterestRateChange.RangeClients.length != 0 &amp;&amp; mRecord.ShowClients.toUpperCase() != "TRUE") toggle = true;
      if (mAccountFloatingInterestRateChange.RangeClientGroups &amp;&amp; mAccountFloatingInterestRateChange.RangeClientGroups.length != 0 &amp;&amp; mRecord.ShowClientGroups.toUpperCase() != "TRUE") toggle = true;
      if (mAccountFloatingInterestRateChange.RangeClientTypes &amp;&amp; mAccountFloatingInterestRateChange.RangeClientTypes.length != 0 &amp;&amp; mRecord.ShowClientTypes.toUpperCase() != "TRUE") toggle = true;    
      if (mAccountFloatingInterestRateChange.RangeExternalPartiesDealers &amp;&amp; mAccountFloatingInterestRateChange.RangeExternalPartiesDealers.length != 0 &amp;&amp; mRecord.ShowExternalPartiesDealers.toUpperCase() != "TRUE") toggle = true;                 
      if (mAccountFloatingInterestRateChange.RangeDepartments &amp;&amp; mAccountFloatingInterestRateChange.RangeDepartments.length != 0 &amp;&amp; mRecord.ShowDepartments.toUpperCase() != "TRUE") toggle = true;      
      if (mAccountFloatingInterestRateChange.RangeEntities &amp;&amp; mAccountFloatingInterestRateChange.RangeEntities.length != 0 &amp;&amp; mRecord.ShowEntities.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
      mAccountFloatingInterestRateChange = null;
      mLastRefreshParametersJson = null;
      mProcessId = null;
      break;

    case "Results":
      // Refesh Update Items
      pageResults_Refresh();
      break;

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Results":
      if (C.rblProcessType.Value() == "PROCESS") {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Print report and review any pending changes created.");
      }
      else {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Print report and review any pending changes identified.");
      }
      break;
      
    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() {
  var params = {
    processId: mProcessId,

    accountTypeId: C.cboAccountType.Text(),
    
    dateEffective: C.dateEffective.Value(),
    dateEffectiveOrEarliestNewPayment: C.chkDateEffectiveOrEarliestNewPayment.Value(),
    interestRate: C.numInterestRate.Value(),
    
    dateEarliestNewPayment: C.dateEarliestNewPayment.Value(),
    
    reference: C.txtReference.Text(),
    
    rangeAccounts: C.txtRangeAccounts.Text(),
    rangeAccountManagers: C.txtRangeAccountManagers.Text(),
    rangeBranches: C.txtRangeBranches.Text(),
    rangeExternalPartiesBrokers: C.txtRangeExternalPartiesBrokers.Text(),
    rangeExternalPartiesBrokersIncludeSub: C.chkRangeExternalPartiesBrokersIncludeSub.Value(),
    rangeClients: C.txtRangeClients.Text(),
    rangeClientGroups: C.txtRangeClientGroups.Text(),
    rangeClientTypes: C.txtRangeClientTypes.Text(),
    rangeExternalPartiesDealers: C.txtRangeExternalPartiesDealers.Text(),
    rangeExternalPartiesDealersIncludeSub: C.chkRangeExternalPartiesDealersIncludeSub.Value(),
    rangeDepartments: C.txtRangeDepartments.Text(),
    rangeEntities: C.txtRangeEntities.Text(),
  }

  // Preview / Process
  switch (C.rblProcessType.Value()) {
    case "PROCESS":
      params.executeReportOnly = false;
      break;
      
    default:
      params.executeReportOnly = true;
      break;
  }

  return params;
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "DOWNLOADREPORT":
      // Download Report
      PrintFloatingInterestRateChangeList();
      break;
      
    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
      if (C.rblProcessType.Value() == "PROCESS") {
        message += "Are you sure you want to update Interest Rates for Accounts?&lt;/br&gt;&lt;/br&gt;&lt;b style='color:red'&gt;WARNING: Accounts WILL be updated.&lt;/b&gt;&lt;/br&gt;&lt;/br&gt;Are you sure you want to continue?";
      }
      else {
        message += "Floating Interest Rate change report will be created.&lt;/br&gt;&lt;/br&gt;Accounts will &lt;b&gt;NOT&lt;/b&gt; be updated.&lt;/br&gt;&lt;/br&gt;Are you sure you want to continue?"
      }

      // Background Process
      message += "&lt;/br&gt;&lt;/br&gt;NOTE: 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, { messageIsHtml: true }, 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 Interest Rate Change Processing, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();

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

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Floating Interest Rate Change was successfully cancelled.");
          break;

        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":          
          // Complete
          mComplete = true;          
          
          // Update Items
          var process = JSON.parse(mRecord_BackgroundProcessStatus.OtherDetailsJson);
          if (process) mAccountFloatingInterestRateChange = JSON.parse(process.FloatingInterestRateChangeJson);
          
          // Save parameters
          mRecord_BackgroundProcessStatus = null;
          mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters());          
          
          // Update Controls
          if (mFromRecent) Fields_Update_FromBackgroundProcess();
          
          // Set Tab
          tabWizard.SelectedTabId("Results");
          tabWizard_Refresh();
          
          // Update Wizard Buttons
          tabWizard_UpdateButtons();          
          
          // Notify
          widget.UI.MsgBoxInfo("Floating Interest Rate Change is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");     
          break;

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

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

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

// ===============
// pageResults
// ===============
function pageResults_Refresh() {
  // Refresh Grid
  if (mAccountFloatingInterestRateChange) {
    // Update Page
    var html = "";
    if (mAccountFloatingInterestRateChange.ExecuteReportOnly) {
      html = "&lt;span&gt;&lt;img src='" + widget.GetIconUrl("Report") + "'&gt;&lt;/span&gt;&lt;span style='padding-left:8px'&gt;Run as a &lt;b&gt;Preview&lt;/b&gt; (Interest Rates were &lt;b&gt;NOT&lt;/b&gt; updated)&lt;/span&gt;";
    }
    else {
      html = "&lt;span&gt;&lt;img src='" + widget.GetIconUrl("Execute") + "'&gt;&lt;/span&gt;&lt;span style='padding-left:8px'&gt;Run as a &lt;b&gt;Process&lt;/b&gt; (Interest Rates &lt;b&gt;were&lt;/b&gt; updated)&lt;/span&gt;";
    }
    C.divProcessType.html(html);
  
    // Refresh Grid
    gridPending_Refresh();
  }
}

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

    // Actions    
  }

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

  // Icon
  var reportOnly = true;
  var otherDetails;
  var floatingInterestRateChange;  
  
  if (item.OtherDetailsJson) otherDetails = JSON.parse(item.OtherDetailsJson);
  if (otherDetails &amp;&amp; otherDetails.FloatingInterestRateChangeJson &amp;&amp; otherDetails.FloatingInterestRateChangeJson.length != 0) floatingInterestRateChange = JSON.parse(otherDetails.FloatingInterestRateChangeJson);
  if (floatingInterestRateChange) reportOnly = floatingInterestRateChange.ExecuteReportOnly;
  
  if (reportOnly) {
    e.row.cells.ProcessType.value = "Report"; 
  }
  else {
    e.row.cells.ProcessType.value = "Execute"; 
  }

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

// =========
// gridPending
// =========
function gridPending_Refresh() {
  // Add Columns
  C.gridPending.ClearColumns();  
  C.gridPending.AddColumnCode("AccountId", { caption: "Account" });
  C.gridPending.AddColumnString("AccountName", { caption: "Name" });
  C.gridPending.AddColumnString("ErrorMessage", { caption: "Error" });

  // Actions

  // Refresh
  C.gridPending.VirtualDataRefresh(mAccountFloatingInterestRateChange.Errors);

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

function gridPending_Action(actionId) {
  switch (actionId.toUpperCase()) {
    default:
      break;  
  }

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

function gridPending_InitialiseRow(e) {
  var item = mAccountFloatingInterestRateChange.Errors[e.row.listIndex];

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

  // Style
  e.row.cells.ErrorMessage.small = true;

  // 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 Interest Rate Change 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 {
    tabWizard_Cancel_Post();
  }
}

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() == "General") {
    cmdFinish.prop("disabled", false);
    cmdNext.prop("disabled", true);
  }
  else {
    cmdFinish.prop("disabled", true);
  }

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

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

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

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

  // Never allow moving back from Progress or Results page
  switch (tabWizard.SelectedTabId()) {
    case "Progress":
    case "Results":
      cmdBack.prop("disabled", true);
      break;
  }

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

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

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

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":     
        if (Ok) {
          tabWizard_ValidatePost_General(validCallback);
          return; 
        }
        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) {

  // Callback
  validCallback();
}

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

  // Enable form
  frmMain.FormEnable();
}

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

  // General
  AdvancedInitialiseSection("RangesHeading", mRecord.ShowRangesHeading);
  AdvancedInitialiseSection("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()
}

// ===================================
// 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) {
      default:
        mFromRecent = true;
        mMonitoringExisting = true;        

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

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

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

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

// ==============
// 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(),
      dateEffective: C.dateEffective.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
  C.numInterestRate.Value(data.InterestRate);
  C.chkDateEffectiveOrEarliestNewPayment.Value(data.InterestEffectiveDateOrEarliestPaymentDate);
  C.dateEarliestNewPayment.Value(data.DateEarliestNewPayment);

  // Change Events
  chkDateEffectiveOrEarliestNewPayment_Change();

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

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

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

  // Update Controls
  C.dateEarliestNewPayment.Value(data.DateEarliestNewPayment);

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

// ====================================
// chkDateEffectiveOrEarliestNewPayment
// ====================================
function chkDateEffectiveOrEarliestNewPayment_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.dateEarliestNewPayment.AllowBlank(!C.chkDateEffectiveOrEarliestNewPayment.Value());
}

// ========================================
// Print Floating Interest Rate Change List
// ========================================
function PrintFloatingInterestRateChangeList() {
  // Create Parameters
  var params = {
    processId: mProcessId,
  };
  
  // Download File
  widget.DownloadFile("PrintFloatingInterestRateChangeList", params);
}

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

    default:
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>0</TimeoutSeconds>
    <UniqueId>yUFQGePfpEyTBAlyv0kLiw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>InterestRate_Edit</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: Account,Name,EffectiveDate,InterestRate,PremiumRate,Instruction,OriginalPayment,OriginalMaturity,FirstPayment,NewPayment,NewMaturity,Pending,Message</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>