<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-01-24T02:30:55.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2018-07-15T20:57:35.8320000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-01-24T02:28:19.4430000</UpdatedUtcDate>
    <ScriptId>HWAIPT</ScriptId>
    <Description>Account Interest Payment Type Change</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountInterestPaymentTypeChange
Option Explicit On
Option Strict On

' #################################################################
' Account Interest Payment Type Change wizard HTML Widget
'
' Version: 1.07 (24/01/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.05  23/04/2021  ISS                Updated
'    1.06  24/03/2022  ISS      J026428   Final message no longer hidden behind block
'    1.07  24/01/2024  ISS      J032783   Updated Permission Keys
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountInterestPaymentTypeChange"

' Common Parameters
Private mAccountId As String
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")
    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 "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

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

    Case "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(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 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.InterestPaymentTypeChange, 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 AccountInterestPaymentTypeChange As finAccountInterestPaymentTypeChange
  Dim CodeDescriptionList As ISCodeDescriptionList
  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 Account Payment object
  If Success Then
    Success = CreateAccountInterestPaymentTypeChange(Nothing, AccountInterestPaymentTypeChange)
  End If

  ' Get Related Accounts
  If Success Then
    CodeDescriptionList = finBL.AccountFunctions.GetRelatedAccountsCodeDescriptionList(AccountInterestPaymentTypeChange.Account)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      .RecordId = AccountInterestPaymentTypeChange.Account.AccountId
      .RecordDescription = AccountInterestPaymentTypeChange.Account.Name

      ' General
      .BalanceInterest = AccountInterestPaymentTypeChange.BalanceInterest
      .BankingDetailsJson = AccountInterestPaymentTypeChange.BankingDetails.ToHtmlWidgetJsonString()
      .CapitaliseInterest = AccountInterestPaymentTypeChange.CapitaliseInterest
      .InterestPaymentType = AccountInterestPaymentTypeChange.InterestPaymentType.ToString()
      .InterestPaymentTypeText = AccountInterestPaymentTypeChange.InterestPaymentTypeText
      .InterestTransferToAccountId = AccountInterestPaymentTypeChange.InterestTransferToAccountId

      ' Account Summary
      .AccountSummaryHtml = finBL.Utilities.GetHtmlFromSummaryTables(finBL.SummaryPageStandardBlocks().Account_Interest2(ScriptInfo, AccountInterestPaymentTypeChange.Account, AccountInterestPaymentTypeChange.Account.Calculation,,,,,,False),,,,iseSummaryPageTarget.WebInternal, "Current Interest Payment Type details")

      ' Lists
      .AuthorisedByNameList = finBL.AccountFunctions.GetByWhomList(AccountInterestPaymentTypeChange.Account, True, False, True).ToCsvString()
      .InterestPaymentTypesList = finBL.Enums.isefinAccountInterestPaymentType_ToCodeDescriptionList(AccountInterestPaymentTypeChange.Account.AccountType.InterestPaymentAvailableTypes).ToJsonObject()
      If AccountInterestPaymentTypeChange.Account.AccountType.TransferCommonClient Then
        .InterestTransferCommonClient = True
        .InterestTransferToCodeDescriptionList = finBL.AccountFunctions.GetRelatedAccountsCodeDescriptionList(AccountInterestPaymentTypeChange.Account).ToJsonObject(False)
      Else
        .InterestTransferCommonClient = False
      End If

      ' Configuration
      .CanRevise = Not finBL.Database.IsReadOnly AndAlso finBL.CurrentUser.Permissions.Allow("Account.InterestPayType.Revise")
      .CanViewHistory = finBL.CurrentUser.Permissions.Allow("Account.InterestPayType.View")
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      If .CanRevise Then
        .ShowHistory = mShowHistory
      Else
        .ShowHistory = True
      End If

      ' Validate
      If Not(.CanRevise OrElse .CanViewHistory) Then
        Success = False
        finBL.Error.ErrorBegin("You do not have permission to either view or change an Account's Interest Payment Type 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;
'''  Create a finAccountPayment object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountInterestPaymentTypeChange(parameters As WizardFinishParameters,
                                                        ByRef accountInterestPaymentTypeChange As finAccountInterestPaymentTypeChange) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountInterestPaymentTypeChange = finBL.CreateAccountInterestPaymentTypeChange()

  ' Update
  If Success Then
    With accountInterestPaymentTypeChange
      ' Load Account
      Success = .AccountLoad(mAccountId)

      ' Update
      If Success AndAlso parameters IsNot Nothing Then
        ' General
        .AuthorisedName = parameters.AuthorisedName
        .AuthorisedReason = parameters.AuthorisedReason
        .Reference = parameters.Reference

        .InterestPaymentTypeText = parameters.InterestPaymentTypeText
        .InterestTransferToAccountId = parameters.InterestTransferToAccountId
        .CapitaliseInterest = parameters.CapitaliseInterest

        ' Banking Details
        Success = .BankingDetails.FromHtmlWidgetJsonString(parameters.BankingDetailsJson)
      End If
    End With
  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 AccountInterestPaymentTypeChange As finAccountInterestPaymentTypeChange
  Dim obj As Object
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Account Payment object
  If Success Then
    Success = CreateAccountInterestPaymentTypeChange(WizardFinishParameters, AccountInterestPaymentTypeChange)
  End If

  ' Validation
  If Success Then
    Select Case AccountInterestPaymentTypeChange.InterestPaymentType
      Case isefinAccountInterestPaymentType.Cheque
        If finBL.PaymentMethods.ItemByPk(AccountInterestPaymentTypeChange.BankingDetails.PaymentMethodPk).PaymentTypeCategory &lt;&gt; isefinPaymentTypeCategory.Cheque Then
          Success = False
          finBL.Error.ErrorBeginFormat("Invalid '{0}' Payment Method.", finBL.CurrentCountry.Terminology(isefinCountryTerminology.Cheque, False))
        End If
      Case isefinAccountInterestPaymentType.DirectCredit
        If Not finBL.PaymentMethods.ItemByPk(AccountInterestPaymentTypeChange.BankingDetails.PaymentMethodPk).IsDirectCredit Then
          Success = False
          finBL.Error.ErrorBegin("Invalid 'Direct Credit' Payment Method.")
        End If
    End Select
  End If

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

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(Warning), returnValue)
  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 New 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"
      ' General
      If WizardValidate_General(parametersJson, ConfirmList) Then
        Data = ConfirmList
      Else
        Success = False
      End If
  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 WizardValidate_General(parametersJson As String,
                                        ByRef confirmList As List(Of String)) As Boolean

  Dim AccountInterestPaymentTypeChange As finAccountInterestPaymentTypeChange
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise ByRef
  confirmList = New List(Of String)()

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

  ' Create Account Interest Payment Type Change object
  If Success Then
    Success = CreateAccountInterestPaymentTypeChange(WizardFinishParameters, AccountInterestPaymentTypeChange)
  End If

  ' Banking Information
  If Success Then
    Select AccountInterestPaymentTypeChange.InterestPaymentType
      Case isefinAccountInterestPaymentType.DirectCredit
        If AccountInterestPaymentTypeChange.BankingDetails.HasValue AndAlso Not AccountInterestPaymentTypeChange.BankingDetails.IsValid(False, False) Then
          confirmList.Add("Invalid Banking Details. " &amp; finBL.Error.Message())
        End If
    End Select
  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

  ' Details
  Public BalanceInterest As Decimal
  Public BankingDetailsJson As String
  Public CapitaliseInterest As Boolean
  Public InterestPaymentType As String
  Public InterestPaymentTypeText As String
  Public InterestTransferToAccountId As String

  ' Account Summary
  Public AccountSummaryHtml As String

  ' Lists
  Public AuthorisedByNameList As String
  Public InterestPaymentTypesList As Object
  Public InterestTransferCommonClient As Boolean
  Public InterestTransferToCodeDescriptionList As Object

  ' Configuration
  Public CanRevise As Boolean
  Public CanViewHistory As Boolean
  Public PromptOnCommit As Boolean
  Public ShowHistory 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 AuthorisedReason As String
  Public Reference As String

  Public InterestPaymentTypeText As String
  Public BankingDetailsJson As String
  Public InterestTransferToAccountId As String
  Public CapitaliseInterest As Boolean

End Class


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

  ' General
  Public Warning As String

  Public Sub New(warning As String)

    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 "AccountInterestPaymentTypeChange".</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 Payment Type Change History&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter details of the Interest Payment Type Change being made."&gt;Interest Payment Type Change&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;tr&gt;&lt;td&gt;
          &lt;!-- Chrome sizing issue (May-2018) requires use of a sub-table --&gt;
          &lt;table class="is-form"&gt;
            &lt;colgroup&gt;
              &lt;col style="width:11em" /&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="lblAuthorisationDetails"&gt;Authorisation details&lt;/label&gt;&lt;/th&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="txtReason"&gt;Reason:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtReason"/&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblNew"&gt;Interest Payment Type details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboInterestPaymentType"&gt;Pay Type:&lt;/label&gt;&lt;/th&gt;
              &lt;td colspan="2"&gt;&lt;input id="cboInterestPaymentType"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboInterestTransferToAccount"&gt;Transfer To:&lt;/label&gt;&lt;/th&gt;
              &lt;td colspan="2"&gt;&lt;input id="cboInterestTransferToAccount"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tbody id="apdPaymentDetailsOutgoing"&gt;&lt;/tbody&gt;

            &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblCapitaliseInterest"&gt;Capitalise Interest&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkCapitaliseInterest" type="checkbox"/&gt;&lt;/th&gt;
            &lt;tr&gt;
              &lt;th class="indent1"&gt;&lt;label for="numBalanceInterest"&gt;Interest Balance:&lt;/label&gt;&lt;/th&gt;
              &lt;td colspan="2" class="indent1"&gt;&lt;input id="numBalanceInterest"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/td&gt;&lt;/tr&gt;

        &lt;tr style="height:100%"&gt;
          &lt;td colspan="2" style="height:100%; padding-top:8px"&gt;&lt;div id="wbAccountSummary" class="is-dock-fill"&gt;&lt;/div&gt;&lt;/td&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,

  lblAuthorisationDetails: null,
  cboAuthorisedBy: null,
  txtReference: null,
  txtReason: null,

  lblNew: null,
  cboInterestPaymentType: null,
  apdPaymentDetailsOutgoing: null,
  cboInterestTransferToAccount: null,

  lblCapitaliseInterest: null,
  chkCapitaliseInterest: null,
  numBalanceInterest: null,

  wbAccountSummary: null,
}

// Form
var frmMain;
var tabWizard;

// Other
var mValueData;

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

// ==========
// Initialise
// ==========
$(function () {
  // Mobile optimisations
  var currencyWidth = "20em";
  $(window).resize(Form_Resize);

  // --------
  // 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.lblAuthorisationDetails = widget.UI.Label("lblAuthorisationDetails", {});
  C.cboAuthorisedBy = widget.UI.ComboBox("cboAuthorisedBy", {
    allowBlank: false,
    maxLength: 50,
  });
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20
  });
  C.txtReason = widget.UI.TextBox("txtReason", {
    multiLine: true,
    rows: 3,
    maxLength: 1024,
  });

  C.lblNew = widget.UI.Label("lblNew", {});
  C.cboInterestPaymentType = widget.UI.ComboBox("cboInterestPaymentType", {
    allowBlank: false,
    onChange: cboInterestPaymentType_Change,
  });
  C.apdPaymentDetailsOutgoing = widget.UI.AccountOutgoingPaymentDetails("apdPaymentDetailsOutgoing", {
  });
  C.cboInterestTransferToAccount = widget.UI.DBCombo("cboInterestTransferToAccount", {
    allowBlank: false,
    limitToList: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblCapitaliseInterest = widget.UI.Label("lblCapitaliseInterest", {
    tooltipText: "If unchecked, the Interest Balance will be included with the next Interest Pay Out/ Transfer"
  });
  C.chkCapitaliseInterest = widget.UI.CheckBox("chkCapitaliseInterest", {
    caption: "Capitalise Interest?",
  });
  C.numBalanceInterest = widget.UI.NumberBox("numBalanceInterest", {
    blankIfZero: false,
    readOnly: true,
  });

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

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

  // 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

  // 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.cboInterestPaymentType.Text(mRecord.InterestPaymentTypeText);
    C.apdPaymentDetailsOutgoing.Initialise(mRecord.RecordId);
    C.apdPaymentDetailsOutgoing.FromBankingDetailsJson(mRecord.BankingDetailsJson);
    C.cboInterestTransferToAccount.Text(mRecord.InterestTransferToAccountId);

    C.chkCapitaliseInterest.Value(mRecord.CapitaliseInterest);
    C.numBalanceInterest.Value(-mRecord.BalanceInterest);

    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) {
    C.cboAuthorisedBy.ListFromCsvString(mRecord.AuthorisedByNameList);
    C.cboInterestPaymentType.ListFromCollection(mRecord.InterestPaymentTypesList, "Description");
    if (mRecord.InterestTransferCommonClient) {
      C.cboInterestTransferToAccount.LimitToList(true);
      C.cboInterestTransferToAccount.RefreshFromCollection(mRecord.InterestTransferToCodeDescriptionList, "Code", "Description");
    }
    else {
      C.cboInterestTransferToAccount.RefreshFromStandardRange("Accounts");
    }
  }

  // Controls
  if (mRecord) {
    cboInterestPaymentType_Change();
  }

  // Check for Advanced options
  if (mRecord) {
  }

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

  // 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.cboAuthorisedBy.WidthResizeFromParent();
      C.txtReference.WidthResizeFromParent();
      C.txtReason.ResizeFromParent();
      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)) {
        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)) {
      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
  tabWizard_Refresh_UpdateHeading();

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

  // Resize Wizard
  tabWizard_Resize();

  // Focus
  switch (tabWizard.SelectedTabId()) {
    case "History":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Interest Payment Type change history for Account '" + mRecord.RecordId + "', " + mRecord.RecordDescription + ".");
      break;

    default:
      tabWizard.FocusFirst();
      break;
  }
}

function tabWizard_Refresh_UpdateHeading() {
  switch (tabWizard.SelectedTabId()) {
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Server side validation required
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        params = CreateFinishParameters();
        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 () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // 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 Payment Type Details";
      var message = "Are you sure you want to update the Interest Payment Type 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);

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

      // Finalise
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Account Interest Payment Type was successfully updated but the following warning was given:\n\n" + data.Warning, {}, Form_ExecuteAction_FinishPost_Finalise);
      }
      else {
        Form_ExecuteAction_FinishPost_Finalise();
      }
    },

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

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

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

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

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

  // Grid Actions

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

// ======================
// cboInterestPaymentType
// ======================
function cboInterestPaymentType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Initialise
  var InterestPaymentType = C.cboInterestPaymentType.ListIndex() == -1 ? "" : mRecord.InterestPaymentTypesList[C.cboInterestPaymentType.ListIndex()].Code;

  switch (InterestPaymentType) {
    case "Capitalise":
      C.apdPaymentDetailsOutgoing.Visible(false);
      C.cboInterestTransferToAccount.VisibleRow(false);
      break;

    case "Cheque":
      C.apdPaymentDetailsOutgoing.Visible(true);
      C.cboInterestTransferToAccount.VisibleRow(false);

      C.apdPaymentDetailsOutgoing.PaymentTypeCategoryFilter("Cheque");
      break;

    case "Compound":
      C.apdPaymentDetailsOutgoing.Visible(false);
      C.cboInterestTransferToAccount.VisibleRow(false);
      break;

    case "DirectCredit":
      C.apdPaymentDetailsOutgoing.Visible(true);
      C.cboInterestTransferToAccount.VisibleRow(false);

      C.apdPaymentDetailsOutgoing.PaymentTypeCategoryFilter("DirectCredit");
      break;

    case "Transfer":
      C.apdPaymentDetailsOutgoing.Visible(false);
      C.cboInterestTransferToAccount.VisibleRow(true);
      break;
  }

  if (mRecord.InterestPaymentType == "Compound" &amp;&amp; InterestPaymentType != "Compound" &amp;&amp; mRecord.BalanceInterest &lt; 0) {
    C.lblCapitaliseInterest.VisibleRow(true);
    C.chkCapitaliseInterest.VisibleRow(true);
    C.numBalanceInterest.VisibleRow(true);
  }
  else {
    C.chkCapitaliseInterest.Value(false);

    C.lblCapitaliseInterest.VisibleRow(false);
    C.chkCapitaliseInterest.VisibleRow(false);
    C.numBalanceInterest.VisibleRow(false);
  }
}

function CreateFinishParameters() {

  var params = {
    // General
    AuthorisedName: C.cboAuthorisedBy.Text(),
    Reference: C.txtReference.Text(),
    AuthorisedReason: C.txtReason.Text(),
    InterestPaymentTypeText: mRecord.InterestPaymentTypesList[C.cboInterestPaymentType.ListIndex()].Description,
    BankingDetailsJson: C.apdPaymentDetailsOutgoing.ToBankingDetailsJson(),
    InterestTransferToAccountId: C.cboInterestTransferToAccount.Text(),
    CapitaliseInterest: C.chkCapitaliseInterest.Value(),
  };

  return params;
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>pHUaqXKIBkuhREBPNBsIiQ</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>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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>