<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-08-02T02:29:54.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-11-11T02:27:34.3490000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-08-02T02:17:26.3610000</UpdatedUtcDate>
    <ScriptId>HWAPT</ScriptId>
    <Description>Account Payment Transfer</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountPaymentTransfer
Option Explicit On
Option Strict On

' #################################################################
' Account Payment Transfer
'
' Version: 1.04 (02/08/2023)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  13/10/2021  ISS      J027538   Created
'    1.01  04/04/2022  ISS      J028455   Transfer to description tidy up
'    1.02  23/03/2023  ISS      J030758   Removed Date Cleared Warning
'    1.03  20/07/2023  ISS      J031606   Support for Desktop Form Overriding
'    1.04  02/08/2023  ISS      J031714   Add additional validation to prevent cross Entity transfers
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountPaymentTransfer"

' Common Parameters
Private mBankTransactionPk As Integer

' 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
    mBankTransactionPk = .GetInteger("BankTransactionPk")
  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
      Main = Finish(parametersJson)

    Case "GetInitialisationInfo"
      ' Get Initialisation Info
      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 Account As finAccount
  Dim AccountPaymentTransfer As finAccountPaymentTransfer
  Dim DateCleared As Date
  Dim DateToday As Date
  Dim DaysDiff As Integer
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim strTemp As String
  Dim Success As Boolean
  Dim swb As ISSqlWhereBuilder

  ' Assume Success
  Success = True

  ' Initialise
  Account = finBL.CreateAccount()
  swb = finBL.Database.CreateSqlWhereBuilder()

  ' Defaults
  DateToday = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

  ' Validate
  If Not finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY) Then
    Success = False
  ElseIf mBankTransactionPk &lt; 1 Then
    Success = False
    finBL.Error.ErrorBegin("A valid Bank Transaction Pk must be specified.")
  End If

  ' Create Account Transfer object
  If Success Then
    If CreateAccountPaymentTransfer(Nothing, AccountPaymentTransfer) Then
      AccountPaymentTransfer.SetDefaultReferenceAndNotes()
      DateCleared = AccountPaymentTransfer.BankTransactionView.DateCleared
    Else
      Success = False
    End If
  End If

  ' Validate Account
  If Success Then
    Account = AccountPaymentTransfer.BankTransactionView.AccountTransactions(0).Account

    If Account.Status &lt;&gt; isefinAccountStatus.Open Then
      Success = False
      finBL.Error.ErrorBegin("Account Status must be 'Open' to transfer a Bank Transaction to another Account.")
    End If
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      .RecordId = Account.AccountId
      .RecordDescription = Account.Name
      .PaymentDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountPaymentTransfer.BankTransactionView.Date)
      .PaymentValue = (AccountPaymentTransfer.BankTransactionView.Value * -1)

      ' Payment Cleared Date
      If DateCleared &lt;&gt; Nothing Then
        If DateCleared = DateToday Then
          .PaymentClearedDateText = "Payment clears &lt;b&gt;today&lt;/b&gt;."
        ElseIf DateCleared &gt; DateToday Then
          .PaymentNotCleared = True

          strTemp = ""
          DaysDiff = CInt(DateDiff(DateInterval.Day, DateToday, DateCleared))
          If DaysDiff &lt;&gt; 1 Then strTemp = "s"
          .PaymentClearedDateText = String.Format("Payment clears in &lt;b&gt;{0} day{1}&lt;/b&gt; on &lt;b&gt;{2}&lt;/b&gt;", CStr(DaysDiff), strTemp, finBL.HtmlEncode(finBL.FormatDateLongWithTimeZone(DateCleared, finBL.TimeZoneId)))
        Else
          .PaymentClearedDateText = String.Format("Payment cleared &lt;b&gt;{0}&lt;/b&gt;", finBL.HtmlEncode(finBL.FormatDateLongWithTimeZone(DateCleared, finBL.TimeZoneId)))
        End If
      End If

      ' Details
      .FromNotes = AccountPaymentTransfer.FromNotes
      .FromReference = AccountPaymentTransfer.FromReference
      .ToNotes = AccountPaymentTransfer.ToNotes
      .ToReference = AccountPaymentTransfer.ToReference

      ' Summary Page
      .SummaryHtml = finBL.SummaryPageFunctions.BankTransactionSummary(False, False, AccountPaymentTransfer.BankTransactionView, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))

      ' Lists
      swb = finBL.Database.CreateSqlWhereBuilder()
      With swb
        .AppendComparisonInteger("Account.Status", "=", isefinAccountStatus.Open)
        .AppendComparisonInteger("Account.Pk", "&lt;&gt;", Account.Pk)
        If finBL.Settings.AddOns.Branch Then
          strTemp = finBL.Branches.GetBranchPksListFromEntityPk(AccountPaymentTransfer.BankTransactionView.AccountTransactions(0).AccountEntityPk).ToCsvString()
          If Len(strTemp) = 0 Then
            ' No Branches for this Entity so ensure no Accounting Ledgers are returned
            .AppendRange("Account.BranchPk", "0", iseRangeDataType.Integer)
          Else
            .AppendRange("Account.BranchPk", strTemp, iseRangeDataType.Integer)
          End If
        End If        
      End With
      .AccountSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(swb.SqlWhere)

      ' Configuration
      .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;
'''  Get Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  Return Success

End Function

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

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountPaymentTransfer = finBL.CreateAccountPaymentTransfer()

  ' Set the From Account
  If Success Then
    Success = accountPaymentTransfer.BankTransactionLoad(mBankTransactionPk)
  End If

  ' Update
  If Success AndAlso parameters IsNot Nothing Then
    With accountPaymentTransfer
      .FromNotes = parameters.FromNotes
      .FromReference = parameters.FromReference
      .ToAccountId = parameters.ToAccountId
      .ToNotes = parameters.ToNotes
      .ToReference = parameters.ToReference
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish Action.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String) As Boolean

  Dim AccountPaymentTransfer As finAccountPaymentTransfer
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Get Wizard Finish Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Create Object
  If Success Then
    Success = CreateAccountPaymentTransfer(WizardFinishParameters, AccountPaymentTransfer)
  End If

  ' Execute
  If Success Then
    Success = AccountPaymentTransfer.ExecuteCommit()
  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 AccountPaymentTransfer As finAccountPaymentTransfer
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' 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
      Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

      ' Create Account Payment Transfer
      If Success Then
        Success = CreateAccountPaymentTransfer(WizardFinishParameters, AccountPaymentTransfer)
      End If

      ' Validate
      If Success Then
        If Not AccountPaymentTransfer.ValidateToAccount() Then
          FailedMessage = finBL.Error.Message(True, False, True)
        End If
      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

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

  ' Record
  Public PaymentClearedDateText As String
  Public PaymentDate As Date
  Public PaymentNotCleared As Boolean
  Public PaymentValue As Decimal
  Public RecordDescription As String
  Public RecordId As String

  ' Details
  Public FromNotes As String
  Public FromReference As String
  Public ToNotes As String
  Public ToReference As String

  ' Summary Page
  Public SummaryHtml As String

  ' Configuration
  Public PromptOnCommit As Boolean

  ' Lists
  Public AccountSqlWhere As String

End Class



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

  Public FromNotes As String
  Public FromReference As String
  Public ToAccountId As String
  Public ToNotes As String
  Public ToReference As String

End Class



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

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

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

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

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountPaymentTransfer".</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="Summary" tooltipText="Transaction."&gt;Original Payment Details&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter Transfer details."&gt;Transfer 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;!-- Summary --&gt;
    &lt;div id="pageSummary"&gt;
      &lt;div id="wbSummary" class="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;

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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPaymentDetails"&gt;Original Payment Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboFromAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboFromAccount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="datePaymentDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="datePaymentDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numPaymentValue"&gt;Value:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numPaymentValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trClearedDate"&gt;
          &lt;th colspan="2"&gt;&lt;div id="divClearedDate" class="is-info-text info small"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblFromDetails"&gt;Payment Transfer from Transaction Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFromReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFromReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFromNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFromNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblToAccount"&gt;Enter the Account the Payment is being transferred to&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblToDetails"&gt;Payment Transfer to Transaction Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtToReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtToReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtToNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtToNotes" /&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="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;

// Controls
var C = {
  //   Summary
  wbSummary: null,

  //   General
  lblPaymentDetails: null,
  cboFromAccount: null,
  datePaymentDate: null,
  numPaymentValue: null,
  trClearedDate: null,
  divClearedDate: null,

  lblFromDetails: null,
  txtFromReference: null,
  txtFromNotes: null,

  lblToAccount: null,
  cboAccount: null,

  lblToDetails: null,
  txtToReference: null,
  txtToNotes: null,
}

// Form
var frmMain;
var tabWizard;

// Other
var mValueData;
var mTransactionTypeChanging;

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

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

  // --------
  // Controls
  // --------
  //   Summary
  C.wbSummary = widget.UI.PreviewPane("wbSummary", {});

  //   General
  C.lblPaymentDetails = widget.UI.Label("lblPaymentDetails", {});
  C.cboFromAccount = widget.UI.DBCombo("cboFromAccount", {
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.datePaymentDate = widget.UI.DateBox("datePaymentDate", {
    readOnly: true,
  });
  C.numPaymentValue = widget.UI.NumberBox("numPaymentValue", {
    readOnly: true,
  });
  C.trClearedDate = $("#trClearedDate");
  C.divClearedDate = $("#divClearedDate");

  C.lblFromDetails = widget.UI.Label("lblFromDetails", {});
  C.txtFromReference = widget.UI.TextBox("txtFromReference", {
    maxLength: 20,
  });
  C.txtFromNotes = widget.UI.TextBox("txtFromNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });

  C.lblToAccount = widget.UI.Label("lblToAccount", {});
  C.cboAccount = widget.UI.DBCombo("cboAccount", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblToDetails = widget.UI.Label("lblToDetails", {});
  C.txtToReference = widget.UI.TextBox("txtToReference", {
    maxLength: 20,
  });
  C.txtToNotes = widget.UI.TextBox("txtToNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });

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

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

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

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = 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) {
      // Unblock
      widget.UI.Unblock();
      
      // Special case - close HTML Widget if an error has occurred
      widget.UI.MsgBoxAlert("fail: " + message, {}, tabWizard_Cancel);
    }
  );
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    //   Summary
    C.wbSummary.SetContent(mRecord.SummaryHtml, false);

    //   General
    C.cboFromAccount.RefreshUnbound(mRecord.RecordId, mRecord.RecordDescription);
    C.datePaymentDate.Value(mRecord.PaymentDate);
    C.numPaymentValue.Value(mRecord.PaymentValue);
    C.divClearedDate.html(mRecord.PaymentClearedDateText);

    C.txtFromReference.Text(mRecord.FromReference);
    C.txtFromNotes.Text(mRecord.FromNotes);
    C.txtToReference.Text(mRecord.ToReference);
    C.txtToNotes.Text(mRecord.ToNotes);
  }

  // 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.cboAccount.RefreshFromStandardRange("Accounts", mRecord.AccountSqlWhere);
  }

  // Controls
  if (mRecord) {
    if (mRecord.PaymentClearedDateText) {
      if (mRecord.PaymentNotCleared) C.divClearedDate.addClass("warning");
    }
    else {
      C.trClearedDate.hide();
    }

    C.txtFromNotes.TagsListDefine([{ caption: "To Account Id", value: "[AccountIdTo]" }, { caption: "Bank Transaction Pk", value: "[BankTransactionPk]" }]);
    C.txtToNotes.TagsListDefine([{ caption: "From Account Id", value: "[AccountIdFrom]" }, { caption: "Bank Transaction Pk", value: "[BankTransactionPk]" }]);
  }

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

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Show History
  if (mRecord) {
  }

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Summary":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Transaction for " + 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 "Summary":
        break;

      case "General":
        // Has server-side validation
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        params = CreateFinishParameters();
        break;

      default:
        break;
    }

    if (params) {
      // Disable Form
      frmMain.FormDisable("Validating");

      // Extend parameters
      params.pageId = tabWizard.SelectedTabId();

      // Call WizardValidate method in Script
      widget.GetString("WizardValidate",
                       params,
                       function (data) { tabWizard_ValidatePost(validCallback, data); },
                       tabWizard_ValidateFail);
    }
    else {
      // No server-side validation
      validCallback();
    }
  }
}

function tabWizard_ValidatePost(validCallback, data) {
  // Enable form
  frmMain.FormEnable();

  // Parse Data
  var o = {};
  if (data) o = JSON.parse(data);

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    fromNotes: C.txtFromNotes.Text(),
    fromReference: C.txtFromReference.Text(),
    toAccountId: C.cboAccount.Text(),
    toNotes: C.txtToNotes.Text(),
    toReference: C.txtToReference.Text(),
  }

  return params;
}

// =================
// 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
      var toAccount = "&lt;b&gt;" + widget.UI.HtmlEncode(C.cboAccount.Text()) + "&lt;/b&gt;";
      if (C.cboAccount.GetDescription()) {
        toAccount += ", &lt;i&gt;'" + C.cboAccount.GetDescription() + "'&lt;/i&gt;";
      }
      else {
        // DBCombo is asynchronous so probably hasn't fetched the description yet!
      }
      var message = "&lt;p&gt;Are you sure you want to transfer the Payment from Account:&lt;/p&gt;&lt;p&gt;&lt;b&gt;" + widget.UI.HtmlEncode(mRecord.RecordId) + "&lt;/b&gt;, &lt;i&gt;'" + widget.UI.HtmlEncode(mRecord.RecordDescription) + "'&lt;/i&gt;&lt;/p&gt;&lt;p&gt;to Account:&lt;/p&gt;&lt;p&gt;" + toAccount + "&lt;/p&gt;";
      var options = {
        heading: "Transfer Account Payment",
        messageIsHtml: true,
      }

      widget.UI.MsgBoxConfirm(message,
                              options,
                              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) {
      // 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 Form_ExecuteAction_FinishPost_Finalise() {
  // Close Form
  widget.Close();

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

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>qo9NWG7AU0+QcowfUXcCbA</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="BankTransactionPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>