<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-01-10T02:42:25.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2018-05-08T04:48:28.3540000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-01-10T02:42:10.8180000</UpdatedUtcDate>
    <ScriptId>HWAPW</ScriptId>
    <Description>Account Pending Withdrawal</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountPendingWithdrawal
Option Explicit On
Option Strict On

' #################################################################
' Account Pending Withdrawal wizard HTML Widget
' 
' Version: 1.05 (10/01/2024)
' 
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.04  20/01/2021  ISS
'    1.05  10/01/2024  ISS      J032719   Updated Permission Keys
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountPendingWithdrawal"

' Common Parameters
Private mAccountId As String

' 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")
  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_DatePending_Change"
      ' Get updated form information based on Date Pending change
      Main = Form_DatePending_Change(returnValue)

    Case "Form_PendingValue_Change"
      ' Get updated form information based on Value change
      Main = Form_PendingValue_Change(returnValue)

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

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

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

    Case "HistoryItem_Complete"
      ' Complete a History Item
      Main = HistoryItem_Action("Complete", returnValue)

    Case "HistoryItem_Reverse"
      ' Reverse a History Item
      Main = HistoryItem_Action("Reverse", 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 finAccountPendingWithdrawalAdd object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountPendingWithdrawalAdd(accountId As String,
                                                   parameters As WizardFinishParameters,
                                                   ByRef accountPendingWithdrawalAdd As finAccountPendingWithdrawalAdd) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountPendingWithdrawalAdd = finBL.CreateAccountPendingWithdrawalAdd()

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

    ' Update
    If Success AndAlso parameters IsNot Nothing Then
      .Dated = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.Dated)
      .Notes = parameters.Notes
      .Reference = parameters.Reference
      .ReviewDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.ReviewDate)
      .Value = parameters.Value
    End If
  End With

  Return Success

End Function

Private Function CreditLimitSummaryPageChange(ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountSummaryHtml As String
  Dim Dated As Date
  Dim obj As Object
  Dim PendingValue As Decimal
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    Dated = .GetDatabaseDateFromJsonUtcDate("dated")
    PendingValue = .GetDecimal("pendingValue")
  End With

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

  If Success Then
    AccountSummaryHtml = finBL.Utilities.GetHtmlFromSummaryTables(finBL.SummaryPageStandardBlocks().Account_CreditLimits_ForTransaction(ScriptInfo, Account, Dated,,,"New Pending Withdrawal", PendingValue,,,False,),,,"",iseSummaryPageTarget.WebInternal, "Credit Limits")
  End If

  ' Create Response
  If Success Then
    obj = New With {
      .AccountSummaryHtml = AccountSummaryHtml
    }
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, response)
  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 AccountPendingWithdrawalAdd As finAccountPendingWithdrawalAdd
  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 Account Pending Withdrawal Add object
  If Success Then
    Success = CreateAccountPendingWithdrawalAdd(mAccountId, WizardFinishParameters, AccountPendingWithdrawalAdd)
  End If

  ' Execute
  If Success Then
    Success = AccountPendingWithdrawalAdd.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 based on Date Pending change.
''' &lt;/summary&gt;
Public Function Form_DatePending_Change(ByRef response As String) As Boolean

  Return CreditLimitSummaryPageChange(response)

End Function

''' &lt;summary&gt;
'''  Get updated form information based on Value change.
''' &lt;/summary&gt;
Public Function Form_PendingValue_Change(ByRef response As String) As Boolean

  Return CreditLimitSummaryPageChange(response)

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.PendingWithdrawal, 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 Account As finAccount
  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.PendingWithdrawal.View") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view Account Pending Withdrawals.")
  End If

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

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

      ' Set Dated to current database date
      .Dated = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())

      ' Account Summary
      .AccountSummaryHtml = finBL.Utilities.GetHtmlFromSummaryTables(finBL.SummaryPageStandardBlocks().Account_CreditLimits_ForTransaction(ScriptInfo, Account, .Dated,,,"New Pending Withdrawal", 0,,,False,),,,"",iseSummaryPageTarget.WebInternal, "Credit Limits")

      ' Configuration
      .CanAdd = finBL.CurrentUser.Permissions.Allow("Account.PendingWithdrawal.Add")
      .CanCancel = finBL.CurrentUser.Permissions.Allow("Account.PendingWithdrawal.Cancel")
      .CanComplete = finBL.CurrentUser.Permissions.Allow("Account.PendingWithdrawal.Complete")
      .CanReverse = finBL.CurrentUser.Permissions.Allow("Account.PendingWithdrawal.Reverse")
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    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/ Complete/ Reverse a Pending Withdrawal Item.
''' &lt;/summary&gt;
Public Function HistoryItem_Action(action As String,
                                   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

  ' Action
  If Success Then
    Select Case UCase(action)
      Case "CANCEL": Success = finBL.AccountFunctions.AccountHistoryPendingWithdrawalCancel(Account.Pk, Pk)
      Case "COMPLETE": Success = finBL.AccountFunctions.AccountHistoryPendingWithdrawalComplete(Account.Pk, Pk)
      Case "REVERSE": Success = finBL.AccountFunctions.AccountHistoryPendingWithdrawalReverse(Account.Pk, Pk)
    End Select
  End If

  ' Return updated History Items
  If Success Then
    ' Refresh History Items
    Account.HistoryItemsRefresh()

    ' Response
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Account.HistoryItems.GetItemsByHistoryType(isefinAccountHistoryType.PendingWithdrawal).ToHtmlWidgetJsonObject(), 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 Dated As Date
  Public Notes As String
  Public Reference As String
  Public ReviewDate As Date?
  Public Value As Decimal

  ' Account Summary
  Public AccountSummaryHtml As String

  ' Configuration
  Public CanAdd As Boolean
  Public CanCancel As Boolean
  Public CanComplete As Boolean
  Public CanReverse As Boolean
  Public PromptOnCommit As Boolean

End Class



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

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

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

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

  End Sub

End Class

''' &lt;summary&gt;
'''  Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters
  Public Dated As Date?
  Public Notes As String
  Public Reference As String
  Public ReviewDate As Date?
  Public Value As Decimal
End Class

''' &lt;summary&gt;
'''  Finish details.
''' &lt;/summary&gt;
Public Class WizardFinishDetails
End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "AccountPendingWithdrawal".</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content"&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"&gt;Account Pending Withdrawal History&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Specify new Pending Withdrawal details for the Account."&gt;Pending Withdrawal Details&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:6em" /&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="lblPending"&gt;Enter the Date, Reference and Pending Withdrawal Value&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePendingDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePendingDate"/&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="numPendingValue"&gt;Value:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numPendingValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblReview"&gt;Enter a Review Date and Notes for the Pending Withdrawal&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateReview"&gt;Review:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateReview"/&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 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,

  lblPending: null,
  datePendingDate: null,
  txtReference: null,
  numPendingValue: null,

  lblReview: null,
  dateReview: null,
  txtNotes: 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 () {

  // --------
  // 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.lblPending = widget.UI.Label("lblPending", {});
  C.datePendingDate = widget.UI.DateBox("datePendingDate", {
    allowBlank: false,
    onChange: datePendingDate_Change,
  });
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20,
  });
  C.numPendingValue = widget.UI.NumberBox("numPendingValue", {
    allowBlank: true,
    decimals: -1,
    minValue: 0,
    maxValue: 99999999999,
    onChange: numPendingValue_Change,
  });

  C.lblReview = widget.UI.Label("lblReview", {});
  C.dateReview = widget.UI.DateBox("dateReview", {
    allowBlank: true,
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 3,
  });

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

  // Grids
  C.gridHistory = widget.UI.Grid("gridHistory", {
    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
  C.txtReference.Text("");
  C.numPendingValue.Value(0);

  C.dateReview.Value(null);
  C.txtNotes.Text("");

  // 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.datePendingDate.Value(mRecord.Dated);
    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

  // Controls

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Show History
  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 tabIndex = tabWizard.SelectedTabIndex();

  // Back and Next Buttons?
  cmdBack.hide();
  cmdNext.hide();

  // Finish Button
  if (tabIndex == 0) {
    cmdCancel.hide();
    cmdFinish.text("Close");
  }
  else {
    cmdCancel.show();
    cmdFinish.text("Add");
  }

  // History Button
  if (tabIndex == 0) {
    cmdHistory.hide();
  }
  else {
    cmdHistory.show();
  }
}

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

    case "General":
      C.txtNotes.WidthResizeFromParent();
      C.txtReference.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)) {
        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();
        gridHistory_RefreshButtons();
      }
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "History":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Pending Withdrawal 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()) {
      case "General":
        // General
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        params = {
          Dated: C.datePendingDate.Value(),
        };
        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 (tabWizard.SelectedTabIndex() == 0) {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      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 = "Add Pending Withdrawal";
      var message = "Are you sure you want to add a Pending Withdrawal 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 = {
    Dated: C.datePendingDate.Value(),
    Notes: C.txtNotes.Text(),
    Reference: C.txtReference.Text(),
    ReviewDate: C.dateReview.Value(),
    Value: C.numPendingValue.Value(),
  };

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

      // Finalise
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Pending Withdrawal 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();

  // Reset Form
  Form_Reset();

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

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

  widget.GetString("Form_PendingValue_Change", { Dated: C.datePendingDate.Value() , PendingValue: C.numPendingValue.Value() }, numPendingValue_Change_Done, numPendingValue_Change_Fail);
}

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

    // Update Record
    mRecord.AccountSummaryHtml = o.AccountSummaryHtml;

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

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

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

  widget.GetString("Form_DatePending_Change", { Dated: C.datePendingDate.Value() , PendingValue: C.numPendingValue.Value() }, datePendingDate_Change_Done, datePendingDate_Change_Fail);
}

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

    // Update Record
    mRecord.AccountSummaryHtml = o.AccountSummaryHtml;

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

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

// ===========
// gridHistory
// ===========
function gridHistory_Refresh() {
  // Add Columns
  C.gridHistory.ClearColumns();
  C.gridHistory.AddColumnString("Status", { caption: "Status", width: "10em"});
  C.gridHistory.AddColumnDate("Date", { caption: "Date"});
  C.gridHistory.AddColumnString("Reference", { caption: "Reference", width: "10em"});
  C.gridHistory.AddColumnCurrency("Value", { caption: "Value"});
  C.gridHistory.AddColumnDate("DateReview", { caption: "Review"});
  C.gridHistory.AddColumnString("Notes", { caption: "Notes"});

  // Grid Actions
  var actions = [];
  if (mRecord &amp;&amp; mRecord.CanAdd) actions.push({ actionId: "Add", tooltipText: "Add Pending Withdrawal", icon: "Add" });
  if (mRecord &amp;&amp; mRecord.CanComplete) actions.push({ actionId: "Complete", tooltipText: "Complete Pending Withdrawal", icon: "Check" });
  if (mRecord &amp;&amp; mRecord.CanReverse) actions.push({ actionId: "Reverse", tooltipText: "Reverse completed Pending Withdrawal", icon: "Reverse" });
  if (mRecord &amp;&amp; mRecord.CanCancel) actions.push({ actionId: "Cancel", tooltipText: "Cancel Pending Withdrawal", icon: "Trash" });
  C.gridHistory.Actions().Define(actions);

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

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

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

  // Pending items
  e.row.bold = item.Pending;
  e.row.colour = (item.Pending &amp;&amp; item.DateReviewPast) ? "red" : "";

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

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

  switch (actionId.toUpperCase()) {
    case "ADD":
      // Add
      cmdNext.click();
      break;

    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;

    case "COMPLETE":
      // Complete
      widget.UI.MsgBoxConfirm("Are you sure you want to COMPLETE the selected item dated " + widget.FormatDate(item.Date) + "?", {}, function() { gridHistory_Action_Complete(item); });
      break;

    case "REVERSE":
      // Reverse
      widget.UI.MsgBoxConfirm("Are you sure you want to REVERSE the selected item dated " + widget.FormatDate(item.Date) + "?", {}, function() { gridHistory_Action_Reverse(item); });
      break;

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

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

  // Cancel
  widget.GetString("HistoryItem_Cancel",
                   { pk: item.Pk },
                   gridHistory_Action_Done,
                   gridHistory_Action_Fail);
}

function gridHistory_Action_Complete(item) {
  // Block UI
  widget.UI.Block("Completing, please wait...");

  // Complete
  widget.GetString("HistoryItem_Complete",
                   { pk: item.Pk },
                   gridHistory_Action_Done,
                   gridHistory_Action_Fail);
}

function gridHistory_Action_Reverse(item) {
  // Block UI
  widget.UI.Block("Reversing, please wait...");

  // Reverse
  widget.GetString("HistoryItem_Reverse",
                   { pk: item.Pk },
                   gridHistory_Action_Done,
                   gridHistory_Action_Fail);
}

function gridHistory_Action_Done(data) {
  // Unblock UI
  widget.UI.Unblock();

  // Parse Data
  mRecord_History = JSON.parse(data);

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

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

function gridHistory_Action_Fail(message) {
  // Show Message
  widget.UI.MsgBoxAlert(message);

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

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

function gridHistory_RefreshButtons() {
  C.gridHistory.Actions().SetEnabled("Add", mRecord &amp;&amp; mRecord.CanAdd);

  if (C.gridHistory.ActiveDataRowListIndex() == -1) {
    C.gridHistory.Actions().SetEnabled("Complete", false);
    C.gridHistory.Actions().SetEnabled("Reverse", false);
    C.gridHistory.Actions().SetEnabled("Cancel", false);
  }
  else {
   var item = mRecord_History[C.gridHistory.ActiveDataRowListIndex()];
    C.gridHistory.Actions().SetEnabled("Complete", item.CanComplete);
    C.gridHistory.Actions().SetEnabled("Reverse", item.CanReverse);
    C.gridHistory.Actions().SetEnabled("Cancel", item.CanCancel);
  }

  C.gridHistory.RefreshButtons();
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>gU2VONiZzk662hU0z12WXw</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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>