<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-08-21T04:44:45.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-08-25T00:06:29.3370000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-08-21T04:44:18.2970000</UpdatedUtcDate>
    <ScriptId>DDSTOP</ScriptId>
    <Description>Account Direct Debit Stop</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountDirectDebitStop
Option Explicit On
Option Strict On

' #################################################################
' Account Direct Debit Stop wizard HTML Widget
'
' Version: 1.09 (21/08/2023)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.06  23/04/2021  ISS
'    1.07  28/10/2021  ISS      J027650   Updated Tooltip
'    1.08  01/11/2021  ISS      J027675   Add "Apply to Minimum Payments only?" option
'          02/11/2021  ISS      J027675   Added Callback to recalculate on Stop Date change
'    1.09  21/08/2023  ISS      J031770   'Stop' Grid Checkbox re-implemented
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountDirectDebitStop"

' Common Parameters
Private mAccountId As String
Private Shared mHideNotes As Boolean
Private Shared mHidePayValue 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")
    mHideNotes = .GetBoolean("HideNotes")
    mHidePayValue = .GetBoolean("HidePayValue")
  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 "Form_PageGeneral_Refresh"
      ' Get updated General page information
      Main = Form_PageGeneral_Refresh(parametersJson, 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 Initialisation Information required for this wizard.
''' &lt;/summary&gt;
Public Function GetInitialisationInfo(ByRef response As String) As Boolean

  Dim AccountDirectDebitStop As finAccountDirectDebitStop
  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 Account.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("Account.DirectDebitStop") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to stop Direct Debits.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If

  ' Create Account Direct Debit Stop object
  If Success Then
    Success = CreateAccountDirectDebitStop(Nothing, AccountDirectDebitStop)
  End If

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

      ' General
      .DateAuthorised = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountDirectDebitStop.AuthorisedDate)
      .DirectDebitBalloonPayment = AccountDirectDebitStop.DirectDebitBalloonPayment
      .DirectDebitStopMinimumPaymentsOnly = AccountDirectDebitStop.DirectDebitStopMinimumPaymentsOnly
      .DirectDebitStopToDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(AccountDirectDebitStop.DirectDebitStopToDate)
      .DirectDebitItems = Me.GetDirectDebitItems(AccountDirectDebitStop)

      ' Lists
      .AuthorisedByNameList = finBL.AccountFunctions.GetByWhomList(AccountDirectDebitStop.Account, True, False, True).ToCsvString()

      ' Configuration
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      Select Case AccountDirectDebitStop.Account.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT
          .ShowDirectApplyToMinimumPaymentOnly = False
          .ShowDirectDebitBalloonPayment = (AccountDirectDebitStop.Calculation.PaymentBalloon &lt;&gt; 0)
        Case isefinAccountClass.LoanRC
          .ShowDirectApplyToMinimumPaymentOnly = True
          .ShowDirectDebitBalloonPayment = False
        Case isefinAccountClass.LoanRC
          .ShowDirectApplyToMinimumPaymentOnly = False
          .ShowDirectDebitBalloonPayment = False
        End Select
      .ShowNotes = (Not mHideNotes)
      .ShowPayValue = (Not mHidePayValue)
    End With
  End If

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

  Return Success

End Function

Private Function GetDirectDebitItems(accountDirectDebitStop As finAccountDirectDebitStop) As List(Of DirectDebitItem)

  Dim AccountFutureDirectDebit As finAccountFutureDirectDebit
  Dim DirectDebitItems As List(Of DirectDebitItem)

  ' Initialise
  DirectDebitItems = New List(Of DirectDebitItem)

  ' Get Items
  For Each AccountFutureDirectDebit In accountDirectDebitStop.FutureDirectDebits
    DirectDebitItems.Add(New DirectDebitItem(finBL, AccountFutureDirectDebit))
  Next

  Return DirectDebitItems

End Function

''' &lt;summary&gt;
'''  Create a CreateAccountDirectDebitStop object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountDirectDebitStop(parameters As WizardFinishParameters,
                                              ByRef accountDirectDebitStop As finAccountDirectDebitStop) As Boolean

  Dim StopItemPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountDirectDebitStop = finBL.CreateAccountDirectDebitStop()

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

    ' Update
    If Success AndAlso parameters IsNot Nothing Then
      ' General
      .AuthorisedDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DateAuthorised)
      .AuthorisedName = parameters.AuthorisedName
      .AuthorisedReason = parameters.AuthorisedReason
      .DirectDebitBalloonPayment = parameters.DirectDebitBalloonPayment
      .DirectDebitStopMinimumPaymentsOnly = parameters.DirectDebitStopMinimumPaymentsOnly
      .DirectDebitStopToDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.DirectDebitStopToDate)

      ' Calculate
      If .Calculate() Then
        If parameters.UpdateExistingTransactions Then
          .UpdateExistingTransactions(.DirectDebitStopToDate)
        End If        
      Else 
        Success = False
      End If

      ' Keep any items were manually flagged in the grid by the User
      If Success Then
        For Each StopItemPk In parameters.StoppedItems          
          .FutureDirectDebits.ItemByTransactionPk(StopItemPk).DirectDebitStop = True
        Next
      End If
    End If
  End With

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Update.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishDetails object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim AccountDirectDebitStop As finAccountDirectDebitStop
  Dim obj As Object
  Dim Success As Boolean
  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 Direct Debit Stop object
  If Success Then
    Success = CreateAccountDirectDebitStop(WizardFinishParameters, AccountDirectDebitStop)
  End If

  ' Execute
  If Success Then
    Success = AccountDirectDebitStop.ExecuteCommit()
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get updated form information.
''' &lt;/summary&gt;
Private Function Form_PageGeneral_Refresh(parametersJson As String,
                                          ByRef response As String) As Boolean

  Dim AccountDirectDebitStop As finAccountDirectDebitStop
  Dim obj As Object
  Dim Success As Boolean
  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 Direct Debit Stop object
  If Success Then
    Success = CreateAccountDirectDebitStop(WizardFinishParameters, AccountDirectDebitStop)
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Me.GetDirectDebitItems(AccountDirectDebitStop), response)
  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;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' Record
  Public RecordId As String
  Public RecordDescription As String

  ' General
  Public DateAuthorised As Date
  Public DirectDebitBalloonPayment As Boolean
  Public DirectDebitStopMinimumPaymentsOnly As Boolean
  Public DirectDebitStopToDate As Date?
  Public DirectDebitItems As List(Of DirectDebitItem)

  ' Lists
  Public AuthorisedByNameList As String

  ' Configuration
  Public PromptOnCommit As Boolean
  Public ShowDirectApplyToMinimumPaymentOnly As Boolean
  Public ShowDirectDebitBalloonPayment As Boolean
  Public ShowNotes As Boolean
  Public ShowPayValue As Boolean

End Class


''' &lt;summary&gt;
'''  Direct Debit item.
''' &lt;/summary&gt;
Public Class DirectDebitItem

  Public [Date] As Date
  Public Notes As String
  Public PayValue As Decimal
  Public Pk As Integer
  Public Reference As String
  Public StatusText As String
  Public [Stop] As Boolean
  Public Value As Decimal

  Public Sub New (finBL As ISfinSupport,
                  accountFutureDirectDebit As finAccountFutureDirectDebit)

    With accountFutureDirectDebit
      Me.Date = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.Date)
      If Not mHideNotes Then Me.Notes = .Notes
      If Not mHidePayValue Then Me.PayValue = .Value
      Me.Pk = .TransactionPk
      Me.Reference = .Reference
      If .TransactionPk = 0 Then
        Select Case .DirectDebitStatus
          Case isefinTransactionDirectDebitStatus.NotApplicable
            Me.StatusText = "Future Manual"
          Case Else
            Me.StatusText = "Future Direct Debit"
        End Select
      Else
        Me.StatusText = .DirectDebitStatusText
      End If
      Me.[Stop]= .DirectDebitStop
      Select Case .DirectDebitStatus
        Case isefinTransactionDirectDebitStatus.NotApplicable
          Me.Value = 0
        Case Else
          Me.Value = .DirectDebitValue
      End Select
    End With

  End Sub

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

  ' General
  Public AuthorisedName As String
  Public AuthorisedReason As String
  Public DateAuthorised As Date?
  Public DirectDebitBalloonPayment As Boolean
  Public DirectDebitStopMinimumPaymentsOnly As Boolean
  Public DirectDebitStopToDate As Date?
  Public StoppedItems As List(Of Integer)
  Public UpdateExistingTransactions As Boolean

End Class


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

  Public Sub New()
  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountDirectDebitStop".</Notes>
    <PermissionKeyExecute />
    <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="General" tooltipText="Specify new Direct Debit Stop details for the Account."&gt;Direct Debit Stop&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- General --&gt;
    &lt;div id="pageGeneral" class="flex-panels"&gt;
      &lt;div class="panel-fixed"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="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="lblAuthorised"&gt;Authorisation details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateAuthorised"&gt;Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateAuthorised"/&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="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="lblOptions"&gt;Direct Debit options&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkDirectDebitBalloonPayment" type="checkbox"/&gt;&lt;/th&gt;
          &lt;/tr&gt;

          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblStopToDate"&gt;Enter the Direct Debit Stop date or check the items to Stop&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateStopToDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;
              &lt;input id="dateStopToDate"/&gt;
              &lt;button id="cmdClear" class="is-button small icon" icon="Clear"&gt;Clear&lt;/button&gt;
            &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkDirectDebitStopMinimumPaymentsOnly" type="checkbox"/&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;

      &lt;div class="panel-flex gap-top" style="min-height:200px"&gt;
        &lt;div id="gridDirectDebitItems" class="is-dock-fill border"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&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_DirectDebits;

// Controls
var C = {
  //   General
  lblAccount: null,
  cboRecord: null,

  lblAuthorised:null,
  dateAuthorised: null,
  cboAuthorisedBy: null,
  txtReason: null,

  lblOptions: null,
  chkDirectDebitBalloonPayment: null,

  lblStopToDate:null,
  dateStopToDate: null,
  chkDirectDebitStopMinimumPaymentsOnly: null,
  gridDirectDebitItems: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdClear;

// Other
var mRefreshTimer;

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

  C.lblOptions = widget.UI.Label("lblOptions", {});
  C.chkDirectDebitBalloonPayment = widget.UI.CheckBox("chkDirectDebitBalloonPayment", {
    caption: "Direct Debit Balloon Payment?",

    onChange: chkDirectDebitBalloonPayment_OnChange,
  });

  C.lblStopToDate = widget.UI.Label("lblStopToDate", {
    tooltipText: "Click the calendar icon to update the 'Stop To' date and stop all Direct Debits up to and including that date.",
  });
  C.dateStopToDate = widget.UI.DateBox("dateStopToDate", {
    onChange: dateStopToDate_Change,
  });
  C.chkDirectDebitStopMinimumPaymentsOnly = widget.UI.CheckBox("chkDirectDebitStopMinimumPaymentsOnly", {
    caption: "Apply to Minimum Payments only?",

    onChange: chkDirectDebitStopMinimumPaymentsOnly_OnChange,
  });

  // Grids
  C.gridDirectDebitItems = widget.UI.Grid("gridDirectDebitItems", {
    stickyHeader: true,
    rowNumbering: true,
    onInitialiseRow: gridDirectDebitItems_InitialiseRow,
    onBeforeCellUpdate: gridDirectDebitItems_BeforeCellUpdate,
    onRowDrilldown: gridDirectDebitItems_RowDrilldown,
  });

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

  cmdClear = $("#cmdClear");
  cmdClear.click(ClearDate);

  // 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_DirectDebits = null;

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);      
      mRecord_DirectDebits = mRecord.DirectDebitItems;
      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.dateAuthorised.Value(mRecord.DateAuthorised);
    C.chkDirectDebitBalloonPayment.Value(mRecord.DirectDebitBalloonPayment);
    C.dateStopToDate.Value(mRecord.DirectDebitStopToDate);
    C.chkDirectDebitStopMinimumPaymentsOnly.Value(mRecord.DirectDebitStopMinimumPaymentsOnly);

    gridDirectDebitItems_Refresh();
  }

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

  // Controls
  if (mRecord) {
    C.lblOptions.VisibleRow(mRecord.ShowDirectDebitBalloonPayment);
    C.chkDirectDebitBalloonPayment.VisibleRow(mRecord.ShowDirectDebitBalloonPayment);
    C.chkDirectDebitStopMinimumPaymentsOnly.VisibleRow(mRecord.ShowDirectApplyToMinimumPaymentOnly);
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // 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() {
  // Back and Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();
    cmdBack.prop("disabled", tabIndex &lt;= 0);
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
  }

  // Finish Button
  if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.cboAuthorisedBy.WidthResizeFromParent();
      C.txtReason.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)) {
      case "General":
        break;

      default:
        break;
    }
  }

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

  // Tweak fields

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

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

  // Resize Wizard
  tabWizard_Resize();

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

// ===============
// 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
      Form_ExecuteAction_Finish();
      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
      widget.UI.MsgBoxConfirm("Are you sure you want to update Direct Debits for Account " + mRecord.RecordId + ", '" + mRecord.RecordDescription + "'?", { heading: "Update Direct Debits" }, function () { 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);

      // Close Form
      widget.Close();

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

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

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

function GetStopItems() {
  var StoppedItems = [];

  // Add non-future payments
  for(var i = 0; i &lt; mRecord_DirectDebits.length; i++) {
    var item = mRecord_DirectDebits[i];

    if (item.Pk == 0) {
      // Done
      break;
    }
    else if (item.Stop) {
      StoppedItems.push(mRecord_DirectDebits[i].Pk)
    }
  }

  return StoppedItems;
}

// ====================
// gridDirectDebitItems
// ====================
function gridDirectDebitItems_Refresh() {
  var showDrilldown = false;
  var showNotes = false;
  var showPayValue = false;
  var showStop = false;

  // Hide Columns
  if (mRecord) {
    for (var i = 0; i &lt; mRecord_DirectDebits.length; i++) {
      var item = mRecord_DirectDebits[i];

      if (item.StatusText != "Future Manual") showDrilldown = true;
      if (item.Notes) showNotes = mRecord.ShowNotes;
      if (item.StatusText == "Future Manual") showPayValue = mRecord.ShowPayValue;
      if (item.Pk != 0) showStop = true;
    }
  }

  // Add Columns
  C.gridDirectDebitItems.ClearColumns();
  C.gridDirectDebitItems.AddColumnDrilldown("DrillDown", { caption: "", icon: "Calendar", drilldownHideIfBlank: true, visible: showDrilldown });
  C.gridDirectDebitItems.AddColumnBoolean("Stop", { caption: "Stop", allowEdit: true, visible: showStop });
  C.gridDirectDebitItems.AddColumnDate("Date", { caption: "Date" });
  C.gridDirectDebitItems.AddColumnString("Reference", { caption: "Reference" });
  C.gridDirectDebitItems.AddColumnString("StatusText", { caption: "DD Status" });
  C.gridDirectDebitItems.AddColumnCurrency("Value", { caption: "DD Value", blankIfZero: true });
  C.gridDirectDebitItems.AddColumnCurrency("PayValue", { caption: "Pay Value", blankIfZero: true, visible: showPayValue });
  C.gridDirectDebitItems.AddColumnString("Notes", { caption: "Notes", visible: showNotes });

  // Refresh
  C.gridDirectDebitItems.VirtualDataRefresh(mRecord_DirectDebits);
}

function gridDirectDebitItems_InitialiseRow(e) {
  var item = mRecord_DirectDebits[e.row.listIndex];

  // Auto-populate cell values from object
  e.row.AutoBind(item);

  // Color
  if (item.Pk &gt; 0 &amp;&amp; !item.Stop) {
    e.row.colour = "red";
  } else {
    e.row.colour = "";
  }

  // Drilldown
  e.row.cells.DrillDown.value = true;

  // No checkboxes for future payments
  e.row.cells.Stop.readOnly = (item.Pk == 0);
  if (item.Pk == 0) e.row.cells.Stop.value = null;

  // Stop
  if (item.Pk == 0) {
    if ((C.dateStopToDate.Value) &amp;&amp; widget.CompareDates(item.Date, C.dateStopToDate.Value()) &lt;= 0 &amp;&amp; item.Value == 0) {
      e.row.strike = true;
      e.row.inactive = true;
    }
    else {
      e.row.strike = false;
      e.row.inactive = false;
    }
  }
  else {
    e.row.strike = item.Stop;
    e.row.inactive = item.Stop;
  }
}

function gridDirectDebitItems_RowDrilldown(e) {
  var item = mRecord_DirectDebits[e.row.listIndex];
  C.gridDirectDebitItems.ActiveDataRowListIndex(e.row.listIndex);
  C.dateStopToDate.Value(item.Date);
  dateStopToDate_Change();
}

function gridDirectDebitItems_BeforeCellUpdate(e) {
  var item = mRecord_DirectDebits[e.row.listIndex];
  switch(e.columnKey) {
    case "Stop":
      item.Stop = e.newValue;
      break;
  }

  // Refresh row to update styles
  e.refreshRow = true;
}

function CreateFinishParameters() {
  var params = {
    // General
    AuthorisedName: C.cboAuthorisedBy.Text(),
    AuthorisedReason: C.txtReason.Text(),
    DateAuthorised: C.dateAuthorised.Value(),
    DirectDebitBalloonPayment: C.chkDirectDebitBalloonPayment.Value(),
    DirectDebitStopToDate: C.dateStopToDate.Value(),
    DirectDebitStopMinimumPaymentsOnly: C.chkDirectDebitStopMinimumPaymentsOnly.Value(),

    StoppedItems: GetStopItems(),
  };

  return params;
}

// ==========================
// Refresh Direct Debits grid
// ==========================
function RefreshGrid(updateExistingTransactions) {
  // Delayed refresh
  if (mRefreshTimer) {
    window.clearTimeout(mRefreshTimer);
    mRefreshTimer = null;
  }

  // Refresh after 500ms
  mRefreshTimer = window.setTimeout(function () {
    // Block UI
    widget.UI.Block("Updating Direct Debits, please wait...");

    // Parameters
    var params = CreateFinishParameters();
    params.UpdateExistingTransactions = updateExistingTransactions;

    // Get Direct Debits
    widget.GetString("Form_PageGeneral_Refresh", params, RefreshGrid_Done, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();

      // Error Message
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }, 500);
}

function RefreshGrid_Done(data) {
  // Clear Timer
  mRefreshTimer = null;

  // Parse
  if (data) mRecord_DirectDebits = JSON.parse(data);
  
  // Refresh Grid
  gridDirectDebitItems_Refresh();
  
  // Unblock UI
  widget.UI.Unblock();
}

// ==============
// dateStopToDate
// ==============
function dateStopToDate_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update defaults  
  for(var i = 0; i &lt; mRecord_DirectDebits.length; i++) {
    var item = mRecord_DirectDebits[i];

    if (C.dateStopToDate.Value() &amp;&amp; widget.CompareDates(C.dateStopToDate.Value(), item.Date) &gt;= 0) {
      item.Stop = true;
    }
    else {
      item.Stop = false;
    }
  }
  
  // Refresh Grid
  RefreshGrid(true);
}

// ============================
// chkDirectDebitBalloonPayment
// ============================
function chkDirectDebitBalloonPayment_OnChange(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh Grid
  RefreshGrid(false);
}

// =====================================
// chkDirectDebitStopMinimumPaymentsOnly
// =====================================
function chkDirectDebitStopMinimumPaymentsOnly_OnChange(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh Grid
  RefreshGrid(false);
}

// =========
// ClearDate
// =========
function ClearDate() {
  if (C.dateStopToDate.Value()) {
    C.dateStopToDate.Value(null);
    dateStopToDate_Change();
  }  
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>TPux0XrUV0yc8jL+WonTcQ</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>
    <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="HideNotes" type="Boolean">
            <BlankTip />
            <Caption>Hide 'Notes' column?</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="HidePayValue" type="Boolean">
            <BlankTip />
            <Caption>Hide 'Pay Value' column?</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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>