<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-07-28T22:50:43.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2018-05-01T03:52:38.8860000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-07-28T22:49:56.3490000</UpdatedUtcDate>
    <ScriptId>HWAIRC</ScriptId>
    <Description>Account Interest Rate Change</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountInterestRateChange
Option Explicit On
Option Strict On

' #################################################################
' Account Interest Rate Change wizard HTML Widget
'
' Version: 1.11 (10/01/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.06  30/03/2021  ISS                Updated
'    1.07  30/03/2022  ISS      J028493   Added "Print Advice" option
'    1.08  09/08/2022  ISS      J029264   Now supports Commit scripts with Warning message
'    1.09  09/02/2023  ISS      J030152   MaturityOrPaymentAdjustment page added for Floating Rate Loans
'    1.10  11/08/2023  ISS      J031741   Added Workflow support
'          31/08/2023  ISS      J031783   Added Parameter to default the "Download Immediately" checkbox
'    1.11  10/01/2024  ISS      J032722   Updated Permission Keys
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountInterestRateChange"

' Common Parameters
Private mAccountId As String
Private mDefaultDownloadImmediately As Boolean
Private mShowHistory As Boolean

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

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 Common Parameters
  With mCombinedParameters
    mAccountId = .GetString("AccountId")
    mDefaultDownloadImmediately = .GetBoolean("DefaultDownloadImmediately")
    mShowHistory = .GetBoolean("ShowHistory")
  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 "DownloadAdvice"
      ' Download Advice
      Main = DownloadAdvice(returnValue)

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

    Case "Form_DateEffective_Change"
      ' Get updated form information based on Date Effective change
      Main = Form_DateEffective_Change(returnValue)

    Case "GetHistory"
      ' Get History records
      Main = GetHistory(returnValue)

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

    Case "GetSchedule"
      Main = GetSchedule(parametersJson, returnValue)
      
    Case "HistoryItem_Cancel"
      ' Cancel a History Item
      Main = HistoryItem_Cancel(returnValue)

    Case "LoadMaturityOrPaymentAdjustmentData"
      ' Load Maturity Or Payment Adjustment Data
      Main = LoadMaturityOrPaymentAdjustmentData(parametersJson, returnValue)
      
    Case "PaymentArrangementSummaryRefresh"
      ' Payment Arrangement Summary Refresh
      Main = PaymentArrangementSummaryRefresh(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;
'''  Create a finAccountInterestRateChange object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountInterestRateChange(parameters As WizardFinishParameters,                                                 
                                                 ByRef accountInterestRateChange As finAccountInterestRateChange) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountInterestRateChange = finBL.CreateAccountInterestRateChange()

  ' Update
  With accountInterestRateChange
    ' Load Account
    Success = .AccountLoad(mAccountId)

    ' Update
    If Success AndAlso parameters IsNot Nothing Then
      ' General
      If .DateEffectiveSet(finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateEffective)) Then
        Success = .GetInterestRate(.DateEffective)
      Else 
        Success = False
      End If
      
      If Success Then
        .AuthorisedName = parameters.AuthorisedName
        .InterestTypeText = parameters.InterestTypeText
        .InterestRate = parameters.InterestRate
        .InterestRateTableId = parameters.InterestRateTableId
        .InterestRatePremium = parameters.InterestRatePremium
        .InterestInstructionDownText = parameters.InterestInstructionDownText
        .InterestInstructionUpText = parameters.InterestInstructionUpText
        .Notes = parameters.Notes
        .PrintAdvice = parameters.PrintAdvice
        .Reference = parameters.Reference
      End If
      
      If Success AndAlso AccountInterestRateChange.Account.AccountClass = isefinAccountClass.LoanFR Then
        If parameters.RegularPaymentAdjustmentType2 Then
          .RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.HoldRegularPayment
        ElseIf parameters.RegularPaymentAdjustmentType3 Then
          .RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.AdjustRegularPayment
          .RegularPaymentEarliestDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.RegularPaymentEarliestDate)
        ElseIf parameters.RegularPaymentAdjustmentType4 Then
          .RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.OverrideRegularPayment
          .RegularPaymentNew = parameters.RegularPaymentNew
        Else
          .RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.None
        End If
      End If      
    End If
  End With

  Return Success

End Function

''' &lt;summary&gt;
'''  Download Advice Document.
''' &lt;/summary&gt;
Private Function DownloadAdvice(ByRef returnValue As String) As Boolean

  Dim AccountLog As finAccountLog
  Dim FileInfo As finFileDownloadInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  AccountLog = finBL.CreateAccountLog()

  ' Load
  Success = AccountLog.Load(mCombinedParameters.GetInteger("AccountLogPk"))

  ' Create File Info
  If Success Then
    FileInfo = finBL.CreateFileDownloadInfo()

    If FileInfo.LoadFile(AccountLog.DocumentFileNameResolved) Then
      returnValue = FileInfo.ToXmlString()
    Else
      Success = False
    End If
  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;
'''  Finish, i.e., Commit changes.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim AccountInterestRateChange As finAccountInterestRateChange
  Dim AccountLog As finAccountLog
  Dim AccountLogPk As Integer
  Dim Message As String
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters
  Dim WarningWorkflow As String

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Interest Rate Change object
  If Success Then
    Success = CreateAccountInterestRateChange(WizardFinishParameters, AccountInterestRateChange)
  End If

  ' Execute
  If Success Then
    Success = AccountInterestRateChange.ExecuteCommit(Warning)
  End If

  ' Advice generated?
  If Success AndAlso AccountInterestRateChange.PrintAdvice AndAlso AccountInterestRateChange.AdviceDocumentLogs.Count &lt;&gt; 0 Then
    ' Get Account Log
    AccountLog = AccountInterestRateChange.AdviceDocumentLogs(0)

    ' Download Immediately?
    If WizardFinishParameters.PrintAdviceDownload Then
      ' Ensure Advice has been published
      If AccountLog.PublishStatus &lt;&gt; isefinLogPublishStatus.Published Then
        If AccountLog.Publish(isefinLogPublishType.Publish, True) Then
          AccountLogPk = AccountLog.Pk
        Else
          Message = "Advice Document failed to publish and returned the following error:" &amp; vbNewLine &amp; vbNewLine &amp; finBL.Error.Message(True, False, True)
        End If
      Else
        AccountLogPk = AccountLog.Pk
      End If
    Else
      Message = String.Format("Advice Document available to be Published on Account Log '{0}'.", AccountLog.Pk)
    End If
  End If

  ' Workflow Functionality
  If Success Then
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, WarningWorkflow)
  End If
  
  ' Finalise
  If Success Then
    If Len(WarningWorkflow) &lt;&gt; 0 Then
      If Len(Warning) = 0 Then
        Warning = WarningWorkflow
      Else
        Warning &amp;= vbNewLine &amp; vbNewLine &amp; WarningWorkflow
      End If
    End If 
    
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountLogPk, Message, Warning), returnValue)
  End If

  Return Success

End Function

Public Function Form_DateEffective_Change(ByRef response As String) As Boolean

  Dim AccountInterestRateChange As finAccountInterestRateChange
  Dim DateEffective As Date
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    DateEffective = .GetDatabaseDateFromJsonUtcDate("date")
  End With

  ' Create Interest Rate Change object
  If Success Then
    Success = CreateAccountInterestRateChange(Nothing, AccountInterestRateChange)
  End If

  ' Get Interest Rate
  If Success Then
    Success =  AccountInterestRateChange.GetInterestRate(DateEffective)
  End If

  ' Create Response
  If Success Then
    obj = New With {
      .AccountSummaryHtml = finBL.Utilities.GetHtmlFromSummaryTables(finBL.SummaryPageStandardBlocks().Account_Interest2(ScriptInfo, AccountInterestRateChange.Account, AccountInterestRateChange.Account.Calculation,,,,,AccountInterestRateChange.DateEffective, False),,,,iseSummaryPageTarget.WebInternal, "Interest Rate Details - as at " &amp; finBL.FormatDateLong(AccountInterestRateChange.DateEffective)),
      .FutureChange = AccountInterestRateChange.FutureChange,
      .InterestRate = CDec(AccountInterestRateChange.InterestRate),
      .InterestRateBase =  CDec(AccountInterestRateChange.InterestRate - AccountInterestRateChange.InterestRatePremium),
      .InterestRatePremium = CDec(AccountInterestRateChange.InterestRatePremium),
      .InterestRateTableId = AccountInterestRateChange.InterestRateTableId,
      .InterestTypeText = AccountInterestRateChange.InterestTypeText
    }
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, response)
  End If

  ' Return Success
  Return Success

End Function

''' &lt;summary&gt;
'''  Get History records.
''' &lt;/summary&gt;
Public Function GetHistory(ByRef response As String) As Boolean

  Dim AccountHistoryItems As finAccountHistoryItems
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get History Items
  If Success Then
    If finBL.AccountFunctions.GetAccountHistoryItemsByType(mAccountId, isefinAccountHistoryType.InterestRateChange, AccountHistoryItems) Then
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(AccountHistoryItems.ToHtmlWidgetJsonObject(), response)
    Else
      Success = False
    End If
  End If

  Return Success

End Function

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

  Dim AccountInterestRateChange As finAccountInterestRateChange
  Dim CanPrintAdvice As Boolean
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Len(mAccountId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Id not specified.")
  ElseIf finBL.CurrentUserInformation.IsAccountFilteredOut(mAccountId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this record.")
  End If

  ' Create Interest Change object
  If Success Then
    Success = CreateAccountInterestRateChange(Nothing, AccountInterestRateChange)
  End If

  ' Can Print Advice?
  If Success Then
    CanPrintAdvice = (AccountInterestRateChange.Account.AccountType.InterestRateChangeAdvicePk &lt;&gt; 0)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      .RecordId = AccountInterestRateChange.Account.AccountId
      .RecordDescription = AccountInterestRateChange.Account.Name
      .IsFloatingRateLoan = (AccountInterestRateChange.Account.AccountClass = isefinAccountClass.LoanFR)

      ' General
      .DateEffective = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountInterestRateChange.DateEffective)
      .FutureChange = AccountInterestRateChange.FutureChange
      .InterestTypeText = AccountInterestRateChange.InterestTypeText
      .InterestRateTableId = AccountInterestRateChange.InterestRateTableId
      .InterestRate = CDec(AccountInterestRateChange.InterestRate)
      .InterestRateBase =  CDec(AccountInterestRateChange.InterestRate - AccountInterestRateChange.InterestRatePremium)
      .InterestRateBaseStandard = CDec(AccountInterestRateChange.Account.AccountType.InterestRate)
      .InterestRateBaseStandardText = finBL.FormatPercentage(.InterestRateBaseStandard / 100, 4, True)
      .InterestRatePremium = CDec(AccountInterestRateChange.InterestRatePremium)
      .InterestInstructionDownText = AccountInterestRateChange.InterestInstructionDownText
      .InterestInstructionUpText = AccountInterestRateChange.InterestInstructionUpText
      .PrintAdvice = (AccountInterestRateChange.PrintAdvice AndAlso CanPrintAdvice)
      .DefaultDownloadImmediately = (mDefaultDownloadImmediately AndAlso CanPrintAdvice)
      .SupportsNegativeInterestRates = AccountInterestRateChange.Account.SupportsNegativeInterestRates
      
      ' Account Summary
      .AccountSummaryHtml = finBL.Utilities.GetHtmlFromSummaryTables(finBL.SummaryPageStandardBlocks().Account_Interest2(ScriptInfo, AccountInterestRateChange.Account, AccountInterestRateChange.Account.Calculation,,,,,AccountInterestRateChange.DateEffective,False),,,,iseSummaryPageTarget.WebInternal, "Interest Rate Details - as at " &amp; finBL.FormatDateLong(AccountInterestRateChange.DateEffective))

      ' Lists
      .AuthorisedByNameList = finBL.AccountFunctions.GetByWhomList(AccountInterestRateChange.Account, True, False, True).ToCsvString()
      .InterestTypeList = AccountInterestRateChange.GetAvailableInterestTypesCodeDescriptionList.ToJsonObject()
      .InterestInstructionDownList = finBL.Enums.isefinAccountInterestInstruction_GetList.ToCsvString()
      .InterestInstructionUpList = finBL.Enums.isefinAccountInterestInstruction_GetList.ToCsvString()

      ' Configuration
      .CanRevise = Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.InterestRate.Revise")
      .CanViewHistory = finBL.CurrentUser.Permissions.Allow("Account.InterestRate.View")
      .CanChangeInterestInstructions = Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.InterestInstructionRevise")
      .CanPrintAdvice = CanPrintAdvice
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      If .CanRevise Then
        .ShowHistory = mShowHistory
      Else
        .ShowHistory = True
      End If
      .ShowInterestInstructions = (AccountInterestRateChange.Account.AccountType.AccountClass = isefinAccountClass.LoanFR)

      ' Validate
      If Not(.CanRevise OrElse .CanViewHistory) Then
        Success = False
        finBL.Error.ErrorBegin("You do not have permission to either view or change Interest Rate details.")
      End If
    End With
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Cancel a History Item.
''' &lt;/summary&gt;
Public Function HistoryItem_Cancel(ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim Pk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

' Get Parameters
  With mCombinedParameters
    Pk = .GetInteger("pk")
  End With

  ' Load Account
  If Success Then
    Account = finBL.CreateAccount()
    Success = Account.Load(mAccountId)
  End If

  ' Cancel
  If Success Then
    Success = finBL.AccountFunctions.AccountHistoryInterestRateCancel(Account.Pk, Pk)
  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 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
  End Select

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Load Maturity Or Payment Adjustment Data.
''' &lt;/summary&gt;
Private Function LoadMaturityOrPaymentAdjustmentData(parametersJson As String, 
                                                     ByRef returnValue As String) As Boolean

  Dim AccountInterestRateChange As finAccountInterestRateChange                                                      
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim InterestRateNew As Double
  
  ' Assume Success
  Success = True
  
  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)
  
  ' Get Account Interest Change
  If Success Then
    Success = CreateAccountInterestRateChange(WizardFinishParameters, AccountInterestRateChange)
  End If
  
  ' Identify default values
  If Success Then
    If AccountInterestRateChange.GetInterestRateNew(InterestRateNew) Then
      If InterestRateNew &gt; AccountInterestRateChange.OriginalInterestRate Then
        Select Case AccountInterestRateChange.InterestInstructionUp
          Case isefinAccountInterestInstruction.AdjustPayment: AccountInterestRateChange.RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.AdjustRegularPayment
          Case isefinAccountInterestInstruction.HoldPayment: AccountInterestRateChange.RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.HoldRegularPayment
          Case Else: AccountInterestRateChange.RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.None
        End Select
      ElseIf InterestRateNew &lt; AccountInterestRateChange.OriginalInterestRate Then
        Select Case AccountInterestRateChange.InterestInstructionDown
          Case isefinAccountInterestInstruction.AdjustPayment: AccountInterestRateChange.RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.AdjustRegularPayment
          Case isefinAccountInterestInstruction.HoldPayment: AccountInterestRateChange.RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.HoldRegularPayment
          Case Else: AccountInterestRateChange.RegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.None
        End Select
      End If
    Else 
      Success = False
    End If
  End If
  
  ' Get information
  If Success Then
    Data = New With {     
      .RegularPaymentAdjustmentType = AccountInterestRateChange.RegularPaymentAdjustmentType.ToString(),
      .RegularPaymentEarliestDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(AccountInterestRateChange.RegularPaymentEarliestDate),
      .RegularPaymentNew = AccountInterestRateChange.RegularPaymentNew,
      .Summary = GetMaturityOrPaymentAdjustmentSummary(AccountInterestRateChange)
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success

End Function

''' &lt;summary&gt;
'''  Payment Arrangement Summary Refresh.
''' &lt;/summary&gt;
Private Function PaymentArrangementSummaryRefresh(parametersJson As String, 
                                                  ByRef returnValue As String) As Boolean

  Dim AccountInterestRateChange As finAccountInterestRateChange                                                  
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True
  
  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)
  
  ' Get Account Interest Change
  If Success Then
    Success = CreateAccountInterestRateChange(WizardFinishParameters, AccountInterestRateChange)
  End If
  
  ' Get Summary Page
  If Success Then
    returnValue = GetMaturityOrPaymentAdjustmentSummary(AccountInterestRateChange)
  End If
  
  Return Success

End Function

''' &lt;summary&gt;
'''  Get Summary for the MaturityOrPaymentAdjustment page.
''' &lt;/summary&gt;
Private Function GetMaturityOrPaymentAdjustmentSummary(accountInterestRateChange As finAccountInterestRateChange) As String
  
  Return finBL.SummaryPageFunctions.AccountInterestRateChangeSummary(False, accountInterestRateChange, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY, "MaturityOrPaymentAdjustment"))
  
End Function

''' &lt;summary&gt;
'''  Get Account Schedule
''' &lt;/summary&gt;
Private Function GetSchedule(parametersJson As String, 
                             ByRef returnValue As String) As Boolean

  Dim AccountCalc As finAccountCalc                             
  Dim AccountInterestRateChange As finAccountInterestRateChange                             
  Dim AccountInterestRateChangeRegularPaymentAdjustmentType As isefinAccountInterestRateChangeRegularPaymentAdjustmentType                             
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim kvl As ISKeyValueList
  Dim Title As String
  Dim Type As String
  Dim Data As Object
  
  ' Assume Success
  Success = True
  
  ' Initialise
  kvl = finBL.CreateKeyValueList()
  
  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)
  
  ' Get Account Interest Change
  If Success Then
    Success = CreateAccountInterestRateChange(WizardFinishParameters, AccountInterestRateChange)
  End If
  
  ' Populate kvl from Url
  kvl.FromUrlString(WizardFinishParameters.Url)  
  Type = kvl.GetString("type")
  
  Select Case UCase(Type)
    Case "ADJUSTMATURITYDATE"
      AccountInterestRateChangeRegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.HoldRegularPayment
      Title = "Hold current Regular Payment and adjust Maturity Date"
    Case "ADJUSTREGULARPAYMENT"
      AccountInterestRateChangeRegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.AdjustRegularPayment
      Title = "Adjust Regular Payment to maintain current Maturity Date"
    Case "NONE"
      AccountInterestRateChangeRegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.None
      Title = "No action"
    Case "OVERRIDEREGULARPAYMENT"
      AccountInterestRateChangeRegularPaymentAdjustmentType = isefinAccountInterestRateChangeRegularPaymentAdjustmentType.OverrideRegularPayment
      Title = "Override Regular Payment"
    Case Else
      Success = False
      finBL.Error.ErrorBeginFormat("Could not show Account Schedule, type '{0}' is invalid.", Type)
  End Select
  
  ' Get Account Calc
  If Success Then
    Success = AccountInterestRateChange.GetAccountCalc(AccountInterestRateChangeRegularPaymentAdjustmentType, AccountCalc)
  End If
  
  ' Return Value
  If Success Then
    Data = New With {
      .Title = Title,
      .ScheduleJson = AccountCalc.Schedule.ToHtmlWidgetJsonString("Date,ElementId,Reference,Debit,Credit,Balance,Notes")
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
                             
End Function


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

  ' Record
  Public RecordId As String
  Public RecordDescription As String
  Public IsFloatingRateLoan As Boolean

  ' Details
  Public DateEffective As Date
  Public FutureChange As Boolean
  Public InterestInstructionDownText As String
  Public InterestInstructionUpText As String
  Public InterestRate As Decimal
  Public InterestRateBase As Decimal
  Public InterestRateBaseStandard As Decimal
  Public InterestRateBaseStandardText As String
  Public InterestRatePremium As Decimal
  Public InterestRateTableId As String
  Public InterestTypeText As String
  Public PrintAdvice As Boolean
  Public DefaultDownloadImmediately As Boolean
  Public SupportsNegativeInterestRates As Boolean
  
  ' Account Summary
  Public AccountSummaryHtml As String

  ' Lists
  Public AuthorisedByNameList As String
  Public InterestTypeList As Object
  Public InterestInstructionDownList As String
  Public InterestInstructionUpList As String

  ' Configuration
  Public CanChangeInterestInstructions As Boolean
  Public CanRevise As Boolean
  Public CanPrintAdvice As Boolean
  Public CanViewHistory As Boolean
  Public PromptOnCommit As Boolean
  Public ShowHistory As Boolean
  Public ShowInterestInstructions As Boolean

End Class



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

  Public Data As Object
  Public FailedMessage As String
  Public FailedControlId 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;
'''  Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters

  Public AuthorisedName As String
  Public DateEffective As Date?
  Public InterestInstructionDownText As String
  Public InterestInstructionUpText As String
  Public InterestRate As Double
  Public InterestRatePremium As Double
  Public InterestRateTableId As String
  Public InterestTypeText As String
  Public Notes As String
  Public PrintAdvice As Boolean
  Public PrintAdviceDownload As Boolean
  Public Reference As String
  Public RegularPaymentAdjustmentType1 As Boolean
  Public RegularPaymentAdjustmentType2 As Boolean
  Public RegularPaymentAdjustmentType3 As Boolean
  Public RegularPaymentAdjustmentType4 As Boolean
  Public RegularPaymentEarliestDate As Date?
  Public RegularPaymentNew As Decimal 
  Public Url As String

End Class



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

  Public AccountLogPk As Integer
  Public Message As String
  Public Warning As String

  Public Sub New(accountLogPk As Integer,
                 message As String,
                 warning As String)

    Me.AccountLogPk = accountLogPk
    Me.Message = message
    Me.Warning = warning

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "AccountInterestRateChange".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="History" tooltipText=""&gt;Interest Rate Change History&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Specify new Interest Rate details for the Account."&gt;Interest Rate Details&lt;/li&gt;
        &lt;li tabId="MaturityOrPaymentAdjustment" tooltipText="Specify whether to adjust Maturity Date or Regular Payment."&gt;Maturity or Payment Adjustment&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- History --&gt;
    &lt;div id="pageHistory"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="gridHistory" style="height:100%"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

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

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccount"&gt;Account&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRecord"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecord" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblEffective"&gt;Enter the Effective date, Authorisation and Reference for the change&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateEffective"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateEffective"/&gt;&lt;span id="divWarningFutureChanges" class="is-info-text warning small" style="display:none; padding-left:4px;"&gt;WARNING: Future changes exist&lt;/span&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAuthorisedBy"&gt;By Whom:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAuthorisedBy" /&gt;&lt;/td&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&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblNewInterestRateDetails"&gt;Enter the new Interest Rate&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboInterestType"&gt;Interest Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInterestType" /&gt;&lt;/td
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboInterestRateTable"&gt;Rate Table:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInterestRateTable" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numInterestRateBase"&gt;Base Rate:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
              &lt;input id="numInterestRateBase" /&gt;
              &lt;button id="cmdReset" class="is-button icon" icon="Reset"&gt;Reset&lt;/button&gt;
              &lt;span id="divInterestRateBaseStandard" class="is-info-text control" style="display:none; padding-left:4px;"&gt;&lt;/span&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numInterestRatePremium"&gt;Plus Premium:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numInterestRatePremium" /&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="lblInterestInstruction"&gt;Review Interest Rate change instructions&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboInterestInstructionDown"&gt;Rate Decrease:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInterestInstructionDown" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboInterestInstructionUp"&gt;Rate Increase:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboInterestInstructionUp" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOtherOptions"&gt;Other Options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkPrintAdvice" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkDownloadAdvice" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%; padding-top:8px"&gt;&lt;div id="wbAccountSummary" class="is-dock-fill"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Maturity Or Payment Adjustment --&gt;
    &lt;div id="pageMaturityOrPaymentAdjustment"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAdjustOptions"&gt;Adjust Maturity Date or future Regular Payments?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRegularPaymentAdjustmentType1" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRegularPaymentAdjustmentType2" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRegularPaymentAdjustmentType3" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="dateRegularPaymentEarliestDate"&gt;Earliest date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateRegularPaymentEarliestDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRegularPaymentAdjustmentType4" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="numRegularPaymentNew"&gt;Payment:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRegularPaymentNew" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAdjustSummary"&gt;Summary&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbPaymentArrangement" class="is-dock-fill"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&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;History&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;Finish&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;

&lt;script&gt;
// Properties
var mRecord;
var mRecord_History;

// Controls
var C = {
  //   History
  gridHistory: null,

  //   General
  lblAccount: null,
  cboRecord: null,

  lblEffective: null,
  dateEffective: null,
  divWarningFutureChanges: null,
  cboAuthorisedBy: null,
  txtReference: null,
  txtNotes: null,

  lblNewInterestRateDetails: null,
  cboInterestType: null,
  cboInterestRateTable: null,
  numInterestRateBase: null,
  divInterestRateBaseStandard: null,
  numInterestRatePremium: null,
  numInterestRate: null,

  lblInterestInstruction: null,
  cboInterestInstructionDown: null,
  cboInterestInstructionUp: null,

  lblOtherOptions: null,
  chkPrintAdvice: null,
  chkDownloadAdvice: null,

  wbAccountSummary: null,
  
  //   Maturity Or Payment Adjustment
  lblAdjustOptions: null,
  chkRegularPaymentAdjustmentType1: null,
  chkRegularPaymentAdjustmentType2: null,
  chkRegularPaymentAdjustmentType3: null,
  dateRegularPaymentEarliestDate: null,
  chkRegularPaymentAdjustmentType4: null,
  numRegularPaymentNew: null,
  
  lblAdjustSummary: null,
  wbPaymentArrangement: null,
}

// Form
var frmMain;
var tabWizard;

// Other
var mRefreshRequired = false;

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

// ==========
// Initialise
// ==========
$(function () {

  // --------
  // Controls
  // --------
  //   General
  C.lblAccount = widget.UI.Label("lblAccount", {});
  C.cboRecord = widget.UI.DBCombo("cboRecord", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10
  });

  C.lblEffective = widget.UI.Label("lblEffective", {});
  C.dateEffective = widget.UI.DateBox("dateEffective", {
    allowBlank: false,
    onChange: dateEffective_Change,
  });
  C.divWarningFutureChanges = $("#divWarningFutureChanges");
  C.cboAuthorisedBy = widget.UI.ComboBox("cboAuthorisedBy", {
    allowBlank: false,
    maxLength: 50,
  });
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 3,
  });

  C.lblNewInterestRateDetails = widget.UI.Label("lblNewInterestRateDetails", {});
  C.cboInterestType = widget.UI.ComboBox("cboInterestType", {
    allowBlank: false,
    onChange: cboInterestType_Change,
  });
  C.cboInterestRateTable = widget.UI.DBCombo("cboInterestRateTable", {
    allowBlank: true,
    limitToList: true,
    maxLength: 100,
  });
  C.numInterestRateBase = widget.UI.NumberBox("numInterestRateBase", {
    allowBlank: true,
    readOnly: true,
    decimals: 4,
    minValue: 0,
    maxValue: 9999.9999,
    percentage: true,
    width: "8em",
    onChange: numInterestRateBase_Change,
  });
  cmdReset = $("#cmdReset");
  cmdReset.click(function() { cmdReset_Change(); });
  C.divInterestRateBaseStandard = $("#divInterestRateBaseStandard");
  C.numInterestRatePremium = widget.UI.NumberBox("numInterestRatePremium", {
    allowBlank: true,
    decimals: 4,
    minValue: -9999.9999,
    maxValue: 9999.9999,
    percentage: true,
    width: "8em",
    onChange: numInterestRatePremium_Change,
  });
  C.numInterestRate = widget.UI.NumberBox("numInterestRate", {
    allowBlank: false,
    decimals: 4,
    minValue: 0,
    maxValue: 9999.9999,
    percentage: true,
    width: "8em",
    onChange: numInterestRate_Change,
  });

  C.lblInterestInstruction = widget.UI.Label("lblInterestInstruction", {});
  C.cboInterestInstructionDown = widget.UI.ComboBox("cboInterestInstructionDown", {
    allowBlank: false,
  });
  C.cboInterestInstructionUp = widget.UI.ComboBox("cboInterestInstructionUp", {
    allowBlank: false,
  });

  C.lblOtherOptions = widget.UI.Label("lblOtherOptions", {});
  C.chkPrintAdvice = widget.UI.CheckBox("chkPrintAdvice", {
    caption: "Print Advice?",

    onChange: chkPrintAdvice_Change,
  });
  C.chkDownloadAdvice = widget.UI.CheckBox("chkDownloadAdvice", {
    caption: "Download immediately?",
  });

  C.wbAccountSummary = widget.UI.PreviewPane("wbAccountSummary", {});

  //   Maturity Or Payment Adjustment
  C.lblAdjustOptions = widget.UI.Label("lblAdjustOptions", {});
  C.chkRegularPaymentAdjustmentType1 = widget.UI.RadioButton("chkRegularPaymentAdjustmentType1", {
    caption: "1. No action?",
    captionWrap: true,
    
    onChange: RegularPaymentAdjustment_Change,
  });
  C.chkRegularPaymentAdjustmentType2 = widget.UI.RadioButton("chkRegularPaymentAdjustmentType2", {
    caption: "2. Hold current Regular Payment and adjust Maturity Date?",
    captionWrap: true,
    
    onChange: RegularPaymentAdjustment_Change,
  });
  C.chkRegularPaymentAdjustmentType3 = widget.UI.RadioButton("chkRegularPaymentAdjustmentType3", {
    caption: "3. Adjust Regular Payment to maintain current Maturity Date?",
    captionWrap: true,
    
    onChange: RegularPaymentAdjustment_Change,
  });
  C.dateRegularPaymentEarliestDate = widget.UI.DateBox("dateRegularPaymentEarliestDate", {
    onChange: RegularPaymentAdjustment_Change,
  });
  C.chkRegularPaymentAdjustmentType4 = widget.UI.RadioButton("chkRegularPaymentAdjustmentType4", {
    caption: "4. Override Regular Payment?",
    captionWrap: true,
    
    onChange: RegularPaymentAdjustment_Change,
  });
  C.numRegularPaymentNew = widget.UI.NumberBox("numRegularPaymentNew", {
    allowBlank: false,
    minValue: 0,
    maxValue: 999999999999999,
    
    onChange: RegularPaymentAdjustment_Change,
  });

  C.lblAdjustSummary = widget.UI.Label("lblAdjustSummary", {});
  C.wbPaymentArrangement = widget.UI.PreviewPane("wbPaymentArrangement", {
    formActionHandler: Widget_NotificationHandler,
  });

  // Grids
  C.gridHistory = widget.UI.Grid("gridHistory", {
    rowNumbering: false,
    stickyHeader: true,
    onInitialiseRow: gridHistory_InitialiseRow,
    onAfterRowActivate: gridHistory_AfterRowActivate,
    onAction: gridHistory_Action,
  });

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

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

  // Widget Notification Handler
  widget.ActionNotificationHandle(Widget_NotificationHandler)

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

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

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  C.chkRegularPaymentAdjustmentType1.Value(true);
  C.chkRegularPaymentAdjustmentType2.Value(false);
  C.chkRegularPaymentAdjustmentType3.Value(false);
  C.chkRegularPaymentAdjustmentType4.Value(false);

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_History = 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);
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboRecord.RefreshUnbound(mRecord.RecordId, mRecord.RecordDescription);

    C.dateEffective.Value(mRecord.DateEffective);

    C.cboInterestType.Text(mRecord.InterestTypeText);
    C.cboInterestRateTable.Text(mRecord.InterestRateTableId);
    C.numInterestRate.Value(mRecord.InterestRate);
    C.divInterestRateBaseStandard.text("Standard Base Rate " + mRecord.InterestRateBaseStandardText);
    C.numInterestRatePremium.Value(mRecord.InterestRatePremium);
    C.numInterestRateBase.Value(mRecord.InterestRateBase);
    C.cboInterestInstructionDown.Text(mRecord.InterestInstructionDownText);
    C.cboInterestInstructionUp.Text(mRecord.InterestInstructionUpText);

    C.chkPrintAdvice.Value(mRecord.PrintAdvice);
    C.chkDownloadAdvice.Value(mRecord.DefaultDownloadImmediately);

    C.wbAccountSummary.SetContent(mRecord.AccountSummaryHtml, false);    
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Not used by this wizard since there is no concept of updating an object behind the wizard
}

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

  // Lists
  if (mRecord) {
    dateEffective_Change_Done();

    C.cboAuthorisedBy.ListFromCsvString(mRecord.AuthorisedByNameList);
    C.cboInterestType.ListFromCollection(mRecord.InterestTypeList, "Description");
    C.cboInterestRateTable.RefreshFromStandardRange("RateTables");
    C.cboInterestInstructionDown.ListFromCsvString(mRecord.InterestInstructionDownList);
    C.cboInterestInstructionUp.ListFromCsvString(mRecord.InterestInstructionUpList);

    C.lblInterestInstruction.VisibleRow(mRecord.ShowInterestInstructions);
    C.cboInterestInstructionDown.VisibleRow(mRecord.ShowInterestInstructions);
    C.cboInterestInstructionUp.VisibleRow(mRecord.ShowInterestInstructions);

    C.cboInterestInstructionDown.ReadOnly(!mRecord.CanChangeInterestInstructions);
    C.cboInterestInstructionUp.ReadOnly(!mRecord.CanChangeInterestInstructions);
  }

  // Controls
  if (mRecord) {
    if (mRecord.SupportsNegativeInterestRates) C.numInterestRate.MinValue(-9999.9999);

    if (!mRecord.CanPrintAdvice) {
      C.lblOtherOptions.VisibleRow(false);
      C.chkPrintAdvice.VisibleRow(false);
      C.chkDownloadAdvice.VisibleRow(false);
    }  
  }
  cboInterestType_Change();
  chkPrintAdvice_Change();
  numInterestRateBase_Change();
  RegularPaymentAdjustment_Change();

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Show History
  if (mRecord) {
    if (mRecord.CanViewHistory &amp;&amp; mRecord.ShowHistory) {
      Form_ExecuteAction("History");
    }
  }

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

function tabWizard_UpdateButtons() {
  var VisibleTabCount = tabWizard.TabCount();
  if (mRecord) {
    if (!mRecord.CanViewHistory) VisibleTabCount -= 1;
    if (!mRecord.CanRevise) VisibleTabCount -= 1;
    if (!mRecord.IsFloatingRateLoan) VisibleTabCount -= 1;
  }

  // History Button
  var tabIndex = tabWizard.SelectedTabIndex();
  if (tabIndex == 0 || (mRecord &amp;&amp; !mRecord.CanViewHistory)) {
    cmdHistory.hide();
  }
  else {
    cmdHistory.show();
  }

  // Back and Next Buttons?
  if (VisibleTabCount == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    cmdBack.prop("disabled", tabIndex &lt;= 0);
    cmdNext.prop("disabled", tabIndex &gt;= VisibleTabCount - 1);
  }

  // Finish Button
  if (mRecord &amp;&amp; !mRecord.CanRevise) {
    cmdCancel.hide();
    cmdFinish.text("Close");
  }
  else {
    if (VisibleTabCount != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
  }
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "History":
      break;

    case "General":
      C.txtReference.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent();
      C.wbAccountSummary.ResizeFromParent();
      break;

    default:
      break;
  }
}

// ===========
// Wizard Move
// ===========
function tabWizard_Move(direction) {
  var Ok;

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        case "MaturityOrPaymentAdjustment":
          found = mRecord.IsFloatingRateLoan;
          break;
          
        default:
          found = true;
          break;
      }

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

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

// ===========
// Refresh Tab
// ===========
function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "General":
        // Refresh (e.g., history item cancelled)
        if (mRefreshRequired) {
          dateEffective_Change();
        }
        break;

      case "MaturityOrPaymentAdjustment":
        pageMaturityOrPaymentAdjustment_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "History":
      // Load History (we move back to this page, not forward!)
      if (!mRecord_History) {
        gridHistory_Refresh();
      }
      else {
        // Refresh (e.g., to show hidden rows)
        C.gridHistory.VirtualDataRefresh(mRecord_History);

        // Activate Last Row
        C.gridHistory.ActivateLastDataRow();
      }
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "History":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Interest Rate change history for Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      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;
  }

}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      default:
        // No validation
        validCallback();
        return;
    }
  }

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

    switch (tabWizard.SelectedTabId()) {
    }

    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()) {
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

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

    case "HISTORY":
      // Show History page
      tabWizard_Refresh(0);
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    if (mRecord.PromptOnCommit) {
      // Confirm
      var heading = "Update Interest Rate Details";
      var message = "Are you sure you want to update Interest Rate Details for this Account?";

      widget.UI.MsgBoxConfirm(message,
                              {heading: heading},
                              Form_ExecuteAction_FinishPost,
                              null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost() {

  // Disable Form
  widget.UI.Block("Committing, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();

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

      // Unblock
      widget.UI.Unblock();

      // Warning
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Interest Rate was successfully updated but the following warning was given:\n\n" + data.Warning, {}, function(){Form_ExecuteAction_FinishPostAdvice(data)});
      }  
      else {
        Form_ExecuteAction_FinishPostAdvice(data);
      }
    },

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

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

function Form_ExecuteAction_FinishPostAdvice(data) {

  // Advice Generated?
  if (data.AccountLogPk) {
    Form_ExecuteAction_FinishPost_PrintAdvice(data.AccountLogPk);
  }
  else if (data.Message) {
    widget.UI.MsgBoxInfo(data.Message, {}, Form_ExecuteAction_FinishPost_Done);
  }
  else {
    Form_ExecuteAction_FinishPost_Done();
  }
}

function Form_ExecuteAction_FinishPost_PrintAdvice(accountLogPk) {
  // Block UI
  widget.UI.Block("Downloading Advice Document, please wait...");

  // Params
  var params = {
    accountLogPk: accountLogPk,
  };

  // Download
  widget.DownloadFile("DownloadAdvice", params);

  // Close
  Form_ExecuteAction_FinishPost_Done();
}

function Form_ExecuteAction_FinishPost_Done() {
  // Close Form
  widget.Close();

  // Refresh Parent (to show updated details)
  widget.RefreshParent();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    AuthorisedName: C.cboAuthorisedBy.Text(),
    DateEffective: C.dateEffective.Value(),
    InterestTypeText: C.cboInterestType.Text(),
    InterestRate: C.numInterestRate.Value(),
    InterestRateTableId: C.cboInterestRateTable.Text(),
    InterestRatePremium: C.numInterestRatePremium.Value(),
    InterestInstructionDownText: C.cboInterestInstructionDown.Text(),
    InterestInstructionUpText: C.cboInterestInstructionUp.Text(),
    Notes: C.txtNotes.Text(),
    PrintAdvice: C.chkPrintAdvice.Value(),
    PrintAdviceDownload: (C.chkPrintAdvice.Value() &amp;&amp; C.chkDownloadAdvice.Value()),
    Reference: C.txtReference.Text(),
    RegularPaymentAdjustmentType1: C.chkRegularPaymentAdjustmentType1.Value(),
    RegularPaymentAdjustmentType2: C.chkRegularPaymentAdjustmentType2.Value(),
    RegularPaymentAdjustmentType3: C.chkRegularPaymentAdjustmentType3.Value(),
    RegularPaymentAdjustmentType4: C.chkRegularPaymentAdjustmentType4.Value(),
    RegularPaymentEarliestDate: C.dateRegularPaymentEarliestDate.Value(),
    RegularPaymentNew: C.numRegularPaymentNew.Value(),
  };

  return params;
}

// ===========
// gridHistory
// ===========
function gridHistory_Refresh() {
  // Add Columns
  C.gridHistory.ClearColumns();
  C.gridHistory.AddColumnDate("Date", { caption: "Date"});
  C.gridHistory.AddColumnCode("CreatedUserId", { caption: "User", width: "10em"});
  C.gridHistory.AddColumnString("Reference", { caption: "Reference", width: "10em"});
  C.gridHistory.AddColumnString("Description", { caption: "Description"});
  C.gridHistory.AddColumnString("Notes", { caption: "Notes"});

  // Grid Actions
  C.gridHistory.Actions().Define([{ actionId: "Cancel", tooltipText: "Cancel Interest Rate change", icon: "Trash" },
                                ]);

  // Fetch data
  widget.GetString("GetHistory", {},
  function (data) {
    // Parse Data
    mRecord_History = JSON.parse(data);

    // Refresh Grid
    C.gridHistory.VirtualDataRefresh(mRecord_History);

    // Activate Last Row
    C.gridHistory.ActivateLastDataRow();
  },

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

function gridHistory_InitialiseRow(e) {
  var item = mRecord_History[e.row.listIndex];

  // Automatic data binding
  e.row.AutoBind(item);

  // Strikethrough Cancelled items
  if (item.Cancelled) {
    e.row.inactive = true;
    e.row.strike = true;
  }

  // Hide?
  if (e.row.inactive) e.row.hidden = true;
}

function gridHistory_Action(actionId) {
  var item = mRecord_History[C.gridHistory.ActiveDataRowListIndex()];

  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      widget.UI.MsgBoxConfirm("Are you sure you want to CANCEL the selected item dated " + widget.FormatDate(item.Date) + "?", {}, function() { gridHistory_Action_Cancel(item); });
      break;

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

function gridHistory_Action_Cancel(item) {
  // Block UI
  widget.UI.Block("Cancelling, please wait...");

  // Cancel
  var params = { pk: item.Pk };
  widget.GetString("HistoryItem_Cancel", params,
    // Success
    function (data) {
      // Unblock UI
      widget.UI.Unblock();

      // Refresh grid
      item.CanCancel = false;
      item.Cancelled = true;
      C.gridHistory.RefreshRow(C.gridHistory.ActiveDataRowListIndex());
      gridHistory_RefreshButtons();

      // Flag as needing to reload details
     mRefreshRequired = true;

      // Refresh Parent (to show updated details)
      widget.RefreshParent();
    },

    // Fail
    function (message) {
      widget.UI.MsgBoxAlert(message);

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

function gridHistory_AfterRowActivate(e) {
  // Refresh Buttons
  gridHistory_RefreshButtons();
}

function gridHistory_RefreshButtons() {
  if (C.gridHistory.ActiveDataRowListIndex() == -1) {
    C.gridHistory.Actions().SetEnabled("Cancel", false);
  }
  else {
   var item = mRecord_History[C.gridHistory.ActiveDataRowListIndex()];
    C.gridHistory.Actions().SetEnabled("Cancel", !item.Cancelled &amp;&amp; item.CanCancel);
  }

  C.gridHistory.RefreshButtons();
}

// ===============
// cboInterestType
// ===============
function cboInterestType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Initialise
  var InterestType = C.cboInterestType.ListIndex() == -1 ? "" : mRecord.InterestTypeList[C.cboInterestType.ListIndex()].Code;

  if (C.cboInterestType.Text()) {
    switch(InterestType.toUpperCase()) {
      case "FIXEDRATE":
        C.cboInterestRateTable.VisibleRow(false);
        C.numInterestRateBase.VisibleRow(false);
        C.numInterestRatePremium.VisibleRow(false);
        C.numInterestRate.VisibleRow(true);
        break;

      case "FLOATINGRATE":
        C.cboInterestRateTable.VisibleRow(false);
        C.numInterestRateBase.VisibleRow(true);
        C.numInterestRatePremium.VisibleRow(true);
        C.numInterestRate.VisibleRow(true);
        break;

      case "INTERESTFREE":
        C.cboInterestRateTable.VisibleRow(false);
        C.numInterestRateBase.VisibleRow(false);
        C.numInterestRatePremium.VisibleRow(false);
        C.numInterestRate.VisibleRow(false);
        break;

      case "RATETABLE":
        C.cboInterestRateTable.VisibleRow(true);
        C.numInterestRateBase.VisibleRow(false);
        C.numInterestRatePremium.VisibleRow(true);
        C.numInterestRate.VisibleRow(false);
        break;

      default: // NOT APPLICABLE or Blank
        C.cboInterestRateTable.VisibleRow(false);
        C.numInterestRateBase.VisibleRow(false);
        C.numInterestRatePremium.VisibleRow(false);
        C.numInterestRate.VisibleRow(false);
        break;
    }
  }
}

// ==============
// chkPrintAdvice
// ==============
function chkPrintAdvice_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Download Checkbox
  C.chkDownloadAdvice.VisibleRow(C.chkPrintAdvice.Value());
}

// ==================================
// Regular Payment Adjustment Options
// ==================================
function RegularPaymentAdjustment_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  if (sender) {
    if (sender == C.chkRegularPaymentAdjustmentType1 || sender == C.chkRegularPaymentAdjustmentType2 || sender == C.chkRegularPaymentAdjustmentType3 || sender == C.chkRegularPaymentAdjustmentType4) {
      C.chkRegularPaymentAdjustmentType1.Value(sender == C.chkRegularPaymentAdjustmentType1);
      C.chkRegularPaymentAdjustmentType2.Value(sender == C.chkRegularPaymentAdjustmentType2);
      C.chkRegularPaymentAdjustmentType3.Value(sender == C.chkRegularPaymentAdjustmentType3);
      C.chkRegularPaymentAdjustmentType4.Value(sender == C.chkRegularPaymentAdjustmentType4);
    }    
  }  
  
  // Other Controls
  C.dateRegularPaymentEarliestDate.VisibleRow(C.chkRegularPaymentAdjustmentType3.Value());
  C.numRegularPaymentNew.VisibleRow(C.chkRegularPaymentAdjustmentType4.Value());
  
  // Update Summary
  if (e) PaymentArrangementSummaryRefresh();
}

// ===================
// numInterestRateBase
// ===================
function numInterestRateBase_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (C.numInterestRateBase.Value() != mRecord.InterestRateBaseStandard) {
    cmdReset.show();
    C.divInterestRateBaseStandard.show();
  }
  else {
    cmdReset.hide();
    C.divInterestRateBaseStandard.hide();
  }
}

// ========
// cmdReset
// ========
function cmdReset_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  C.numInterestRateBase.Value(mRecord.InterestRateBaseStandard);
  C.numInterestRate.Value(mRecord.InterestRateBaseStandard + C.numInterestRatePremium.Value());

  numInterestRateBase_Change();
}

// ======================
// numInterestRatePremium
// ======================
function numInterestRatePremium_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (C.numInterestRatePremium.Value()) {
    C.numInterestRate.Value(C.numInterestRateBase.Value() + C.numInterestRatePremium.Value());
  }
}

// ===============
// numInterestRate
// ===============
function numInterestRate_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (C.numInterestRate.Value()) {
    C.numInterestRatePremium.Value(C.numInterestRate.Value() - C.numInterestRateBase.Value());
  }
}

// =============
// dateEffective
// =============
function dateEffective_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  if (C.dateEffective.Value()) {
    widget.GetString("Form_DateEffective_Change", { date: C.dateEffective.Value() }, dateEffective_Change_Done, dateEffective_Change_Fail);
  }
}

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

    // Update Record
    mRecord.AccountSummaryHtml = o.AccountSummaryHtml
    mRecord.FutureChange = o.FutureChange;
    mRecord.InterestRate = o.InterestRate;
    mRecord.InterestRateBase = o.InterestRateBase;
    mRecord.InterestRatePremium = o.InterestRatePremium;
    mRecord.InterestRateTableId = o.InterestRateTableId;
    mRecord.InterestTypeText = o.InterestTypeText;
  }

  // Load Fields
  C.cboInterestType.Text(mRecord.InterestTypeText);
  C.cboInterestRateTable.Text(mRecord.InterestRateTableId);
  C.numInterestRate.Value(mRecord.InterestRate);
  C.numInterestRatePremium.Value(mRecord.InterestRatePremium);
  C.numInterestRateBase.Value(mRecord.InterestRateBase);
  C.wbAccountSummary.SetContent(mRecord.AccountSummaryHtml, false);

  // Update Controls
  if (mRecord.FutureChange) C.divWarningFutureChanges.show(); else C.divWarningFutureChanges.hide();
  cboInterestType_Change();
  numInterestRateBase_Change();

  // Finalise
  mRefreshRequired = false;
}

function dateEffective_Change_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}

// ===============================
// pageMaturityOrPaymentAdjustment
// ===============================
function pageMaturityOrPaymentAdjustment_Refresh() {
  // Hide content
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Initialising, please wait...");
  
  // Params
  var params = CreateFinishParameters();
  
  // Get Data
  widget.GetString("LoadMaturityOrPaymentAdjustmentData", params, pageMaturityOrPaymentAdjustment_Refresh_Done, function(errorMessage) {
    // Go back to General page
    tabWizard_Move(-1);
  
    // Show content
    frmMain.Visible(true);
  
    // Unblock
    widget.UI.Unblock();
    
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function pageMaturityOrPaymentAdjustment_Refresh_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Update
  C.chkRegularPaymentAdjustmentType1.Value(data.RegularPaymentAdjustmentType == "None");
  C.chkRegularPaymentAdjustmentType2.Value(data.RegularPaymentAdjustmentType == "HoldRegularPayment");
  C.chkRegularPaymentAdjustmentType3.Value(data.RegularPaymentAdjustmentType == "AdjustRegularPayment");
  C.chkRegularPaymentAdjustmentType4.Value(data.RegularPaymentAdjustmentType == "OverrideRegularPayment"); 
  
  if (data.RegularPaymentEarliestDate) C.dateRegularPaymentEarliestDate.Value(data.RegularPaymentEarliestDate);
  if (data.RegularPaymentNew) C.numRegularPaymentNew.Value(data.RegularPaymentNew);
  if (data.Summary) PaymentArrangementSummaryRefresh_Done(data.Summary);
  
  // Update Controls
  RegularPaymentAdjustment_Change();
  
  // Show content
  frmMain.Visible(true);
  
  // Unblock
  widget.UI.Unblock();
}

// ===================================
// Payment Arrangement Summary Refresh
// ===================================
function PaymentArrangementSummaryRefresh() {
  tabWizard_Validate(function() {
    // Block
    widget.UI.Block("Calculating, please wait...");
  
    // Clear
    C.wbPaymentArrangement.SetContent("", false);
  
    // Params
    var params = CreateFinishParameters();
    
    // Get Summary
    widget.GetString("PaymentArrangementSummaryRefresh", params, PaymentArrangementSummaryRefresh_Done,    
      function(errorMessage) {
        // Unblock
        widget.UI.Unblock();
      
        // Error
        widget.UI.MsgBoxAlert(errorMessage);
    });
  });  
}

function PaymentArrangementSummaryRefresh_Done(data) {
  // Update Data
  C.wbPaymentArrangement.SetContent(data, false);
  
  // Unblock
  widget.UI.Unblock();
}

// =============
// Show Schedule
// =============
function ShowSchedule(url) {
  // Block UI
  widget.UI.Block("Calculating Schedule, please wait...");

  // Create Parameters
  var params = CreateFinishParameters();
  params.Url = url;

  // Get Schedule
  widget.GetString("GetSchedule", params,
    function(data) {
      // Parse
      if (data) data = JSON.parse(data);
    
      // Params
      var params = {
        scheduleJson: data.ScheduleJson, 
        headingSummary: data.Title,
        gotoDate: C.dateEffective.Value(),
      };
    
      // Unblock
      widget.UI.Unblock();
    
      // Show Schedule
      widget.UI.Forms.ShowAccountSchedule(params);
    },

    function(data) {
      // Unblock
      widget.UI.Unblock();
      
      // Error
      widget.UI.MsgBoxAlert(data);
    }
  );
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId) {
    case "ShowSchedule":
      ShowSchedule(data);
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>DjfMoXvdZkO3YQzb9HtfKg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="DefaultDownloadImmediately" 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>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AccountId" 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 />
            <Visible>true</Visible>
            <List>RANGE.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowHistory" 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>
          <Parameter name="WorkflowPk" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="WorkflowItemPk" type="Number">
            <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>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>