<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-07-26T03:21:27.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2018-05-18T00:46:59.9610000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2022-07-26T03:20:03.0810000</UpdatedUtcDate>
    <ScriptId>HWACQ</ScriptId>
    <Description>Account Close Quotation</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_AccountCloseQuotation
Option Explicit On
Option Strict On

' #################################################################
' Account Close Quotation wizard (OBSOLETE)
'
' Version: 1.07 (26/07/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.07  26/07/2022  ISS      J028620   Obsoleted
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountCloseSummary"

' 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 = Replace(ScriptInfo.TemplateText, "&lt;%[RecordId]%&gt;", mAccountId)

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

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

    Case "WizardValidate"
      ' Validate wizard page
      Main = WizardValidate(parametersJson, returnValue)

    Case "Form_AccountSummary_Refresh"
      ' Get updated form information based on values changing, namely Date and Futute Payments show
      Main = Form_AccountSummary_Refresh(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 AccountClose As finAccountClose
  Dim Client As finClient
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Create Account Close object
  If Success Then
    Success = CreateAccountClose(mAccountId, Nothing, AccountClose)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Read Only
      .ReadOnly = finBL.Database.IsReadOnly

      ' Record
      .RecordId = AccountClose.Account.AccountId
      .RecordDescription = AccountClose.Account.Name

      ' General
      .CloseDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountClose.CloseDate)
      .FuturePaymentsShow = AccountClose.FuturePaymentsShow

      ' Account Summary
      .AccountSummaryHtml = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "General", 0, CreateScriptContextData())

      ' Permissions
      If .ReadOnly Then
        .CanAddLog = False
        .CanCreateDocument = False
        .CanSendEmail = False

        .DocumentWarning = "Database is Read-Only."
      Else
        ' Default Permissions
        .CanAddLog = True
        .CanCreateDocument = True
        .CanSendEmail = True

        ' Can Document be generated?
        If AccountClose.Account.AccountType.ClosingSummaryDocumentPk = 0 Then
          .CanCreateDocument = False
          .DocumentWarning = "Document not defined."
        Else
          ' Document Warning
          With finBL.Documents(AccountClose.Account.AccountType.ClosingSummaryDocumentId)
            If Not .Active Then
              FormInitialisationInfo.CanCreateDocument = False
              FormInitialisationInfo.DocumentWarning = "Document is not active."
            ElseIf Not .HasPermissionToExecute() Then
              FormInitialisationInfo.CanCreateDocument = False
              FormInitialisationInfo.DocumentWarning = "You do not have permission to execute this Document."
            Else
              Select Case .FileType
                Case iseDocumentFileType.WordDocument
                Case Else
                  FormInitialisationInfo.CanCreateDocument = False
                  FormInitialisationInfo.DocumentWarning = "Document File Type is not supported for printing through this interface."
              End Select
            End If
          End With
        End If

        ' Can Email be Sent?
        .CanSendEmail = finBL.CurrentUserInformation.CanSendAccountEmailUnattended AndAlso .CanCreateDocument
        If .CanSendEmail Then
          ' Main Client
          If mCombinedParameters.GetBoolean("EmailAllowMainClient") AndAlso AccountClose.Account.Clients.Count &lt;&gt; 0 Then
            .EmailMainClient = AccountClose.Account.Clients(0).Client.ContactMethods.GetCurrentEmail().Value
          End If

          ' Broker
          If mCombinedParameters.GetBoolean("EmailAllowBroker") AndAlso finBL.Settings.AddOns.ExternalPartyBrokers AndAlso AccountClose.Account.BrokerExternalParty IsNot Nothing Then
            AccountClose.Account.BrokerExternalParty.GetClient(Client)
            If Client IsNot Nothing Then .EmailBroker = Client.ContactMethods.GetCurrentEmail().Value
          End If

          ' Dealer
          If mCombinedParameters.GetBoolean("EmailAllowDealer") AndAlso finBL.Settings.AddOns.ExternalPartyDealers AndAlso AccountClose.Account.DealerExternalParty IsNot Nothing Then
            AccountClose.Account.DealerExternalParty.GetClient(Client)
            If Client IsNot Nothing Then .EmailDealer = Client.ContactMethods.GetCurrentEmail().Value
          End If
        End If
      End If

      ' Lists

      ' Configuration
      ' NOTE: Not used by this Widget
      .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;
'''  Create Context Data for Scripts.
''' &lt;/summary&gt;
Private Function CreateScriptContextData() As ISKeyValueList

  CreateScriptContextData = finBL.CreateKeyValueList()
  With CreateScriptContextData
    .SetObject("Target", ScriptInfo.Target)
    .SetBoolean("HighDpi", finBL.HighDpi)
    .SetString("FormKey", FORM_KEY)
    .SetString("FormRecordMode", iseFormRecordMode.Loaded.ToString())
  End With

End Function

''' &lt;summary&gt;
'''  Create a finAccountClose object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountClose(accountId As String,
                                    parameters As WizardFinishParameters,
                                    ByRef accountClose As finAccountClose) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountClose = finBL.CreateAccountClose()

  ' Update
  If Success Then
    With accountClose
      ' Load Account
      Success = .AccountLoad(AccountId)

      ' Update
      If Success AndAlso parameters IsNot Nothing Then
        ' General
        .CloseDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.CloseDate)
        .FuturePaymentsShow = parameters.FuturePaymentsShow

        ' Calculate
        .Calculate()
      End If
    End With
  End If

  Return Success

End Function

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

  Dim AccountClose As finAccountClose
  Dim AccountLog As finAccountLog
  Dim Client As finClient
  Dim Document As finDocumentRO
  Dim EmailAddress As String
  Dim ExternalParty As finExternalPartyRO
  Dim Message As String
  Dim Parameters As ISKeyValueList
  Dim obj As Object
  Dim Subject As String
  Dim Success As Boolean
  Dim Warning As String
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Account Close object
  If Success Then
    Success = CreateAccountClose(mAccountId, WizardFinishParameters, AccountClose)
  End If

  ' Validate
  If Success Then
    If Not AccountClose.CanCommitConsumerRegulationType(Message) Then
      Success = False
      finBL.Error.ErrorBegin(Message)
    End If
  End If

  ' Create Log
  If Success Then
    If AccountClose.ExecuteCreateLog(AccountLog) Then
      ' Save
      Success = AccountLog.Save()
    Else
      Success = False
    End If
  End If

  ' Email
  If Success Then
    Select Case WizardFinishParameters.Action
      Case "EMAIL_MAINCLIENT"
          ' Main Client
          Client = AccountClose.Account.Clients(0).Client
          EmailAddress = Client.ContactMethods.GetCurrentEmail().Value

      Case "EMAIL_BROKER"
          ' Broker
          ExternalParty = AccountClose.Account.BrokerExternalParty
          ExternalParty.GetClient(Client)
          If Client IsNot Nothing Then EmailAddress = Client.ContactMethods.GetCurrentEmail().Value

      Case "EMAIL_DEALER"
          ' Dealer
          ExternalParty = AccountClose.Account.DealerExternalParty
          ExternalParty.GetClient(Client)
          If Client IsNot Nothing Then EmailAddress = Client.ContactMethods.GetCurrentEmail().Value

      Case Else
        If WizardFinishParameters.Action.StartsWith("EMAIL_") Then
          Warning = String.Format("Unsupported Email action '{0}'.", WizardFinishParameters.Action)
        End If
    End Select
  End If

  ' Create PDF Document
  ' NOTE: Only necessary if emailing since the document printing is done client-side via an Application Shortcut
  If Success AndAlso Len(EmailAddress) &lt;&gt; 0 Then
    ' Get Document
    Document = finBL.Documents(AccountClose.Account.AccountType.ClosingSummaryDocumentId)

    ' Generate Subject and Message
    Subject = finBL.DocumentFunctions.ResolveTaggedMessageFromObjects(Document.TemplateSubject, finBL.TimeZoneFunctions.GetCurrentDatabaseDate(), AccountClose.Account, Client, ExternalParty, finBL.Users(finBL.CurrentUserInformation.UserId))
    Message = finBL.DocumentFunctions.ResolveTaggedMessageFromObjects(Document.TemplateMessage, finBL.TimeZoneFunctions.GetCurrentDatabaseDate(), AccountClose.Account, Client, ExternalParty, finBL.Users(finBL.CurrentUserInformation.UserId))
    If Len(Subject) = 0 Then Subject = "Account Close Quotation"
    If Len(Message) = 0 Then Message = "Your Account Close quotation is attached."

    ' Create Parameters
    Parameters = finBL.CreateKeyValueList()
    With Parameters
      .SetInteger("logPk", AccountLog.Pk)
    End With

    ' Email Subject and Body

    ' Execute and Email Document
    ' NOTE: HTML format, includes Signature and Entity-based Signature
    If Not finBL.DocumentFunctions.SendEmailFromDocumentExecute(Document.DocumentId, parameters, Subject, Message, EmailAddress,,,,,True, True, AccountClose.Account.EntityPk) Then
      Warning = finBL.Error.Message(True, True)
    End If
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountLog.Pk, AccountClose.Account.AccountType.ClosingSummaryDocumentId, Warning), returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
  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;
'''  Get updated form information based on value changes.
''' &lt;/summary&gt;
Public Function Form_AccountSummary_Refresh(ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim AccountSummaryHtml As String
  Dim FuturePaymentsShow As Boolean
  Dim CloseDate As Date
  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    CloseDate = .GetDatabaseDateFromJsonUtcDate("CloseDate")
    FuturePaymentsShow = .GetBoolean("FuturePaymentsShow")
  End With

  ' Create Account Close object
  If Success Then
    Success = CreateAccountClose(mAccountId, Nothing, AccountClose)
  End If

  ' Update
  If Success Then
    With AccountClose
      .CloseDate = CloseDate
      .FuturePaymentsShow = FuturePaymentsShow
      .Calculate()
    End With
  End If

  ' Get Summary
  If Success Then
    AccountSummaryHtml = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "General", 0, CreateScriptContextData())
  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;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' Record
  Public RecordId As String
  Public RecordDescription As String

  ' Details
  Public CloseDate As Date
  Public FuturePaymentsShow As Boolean

  ' Account Summary
  Public AccountSummaryHtml As String

  ' Other
  Public DocumentWarning As String
  Public EmailMainClient As String
  Public EmailBroker As String
  Public EmailDealer As String

  ' Configuration
  Public CanAddLog As Boolean
  Public CanCreateDocument As Boolean
  Public CanSendEmail As Boolean
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean

End Class


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

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

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

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

  End Sub

End Class


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

  ' General
  Public CloseDate As Date
  Public FuturePaymentsShow As Boolean
  Public Action As String

End Class


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

  ' General
  Public AccountLogPk As Integer
  Public DocumentId As String
  Public Warning As String

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

    Me.AccountLogPk = accountLogPk
    Me.DocumentId = documentId
    Me.Warning = warning

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>OBSOLETE: This wizard has been superseded by the Account Close wizard.

System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "AccountClose" but only used to produce a Quotation.

NOTE: Uses template Email and Message defined on the Account Settlement Summary Document for the Account Type.</Notes>
    <PermissionKeyExecute />
    <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="General" tooltipText="Enter details to produce a Close Quotation for this Account."&gt;Account Close Quotation&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"&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="lblOptions"&gt;Enter the expected close date and other options&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateClose"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateClose" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFuturePaymentsShow" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccountSummary"&gt;Account Summary&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbAccountSummary"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;span class="is-info-text wizard-footer" style="display:none"&gt;Startup Tooltip&lt;/span&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;
// Server-side information
var mRecordId = "&lt;%[RecordId]%&gt;";

// Properties
var mRecord;

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

  lblOptions: null,
  dateClose: null,
  chkFuturePaymentsShow: null,

  lblAccountSummary: null,
  wbAccountSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

// ==========
// 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.lblOptions = widget.UI.Label("lblOptions", {});
  C.dateClose= widget.UI.DateBox("dateClose", {
    allowBlank: false,
    onChange: dateClose_Change,
  });
  C.chkFuturePaymentsShow = widget.UI.CheckBox("chkFuturePaymentsShow", {
    caption: "Include Future Payments?",
    onChange: chkFuturePaymentsShow_Change,
  });

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

  // Grids

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

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

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  var params = {recordId: mRecordId};
  widget.GetString("GetInitialisationInfo", params,
    // 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.dateClose.Value(mRecord.CloseDate);
    C.chkFuturePaymentsShow.Value(mRecord.FuturePaymentsShow);

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

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

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

  // Lists
  if (mRecord) {
  }

  // Controls

  // Startup tooltip
  if (mRecord) {
    if (mRecord.CanAddLog || mRecord.CanCreateDocument || mRecord.CanSendEmail) {
      s = "You will be prompted to save this summary";
      if (mRecord.CanCreateDocument || mRecord.CanSendEmail) s += " or create a document ";
      s += " upon finishing.";

      var e = $(".is-info-text.wizard-footer");
      e.text(s);
      e.show();
    }
  }

  // Update Buttons
  tabWizard_UpdateButtons();

  // Read-Only?
  //if (mRecord &amp;&amp; mRecord.ReadOnly) frmMain.FormReadOnly(C, true);

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

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      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()) {
  }

  // 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()) {
      case "General":
        // General
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        var params = {
          //InvestmentValue: C.numInvestmentValue.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 (mRecord.ReadOnly) {
        tabWizard_Cancel();
      }
      else {
        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.CanAddLog || mRecord.CanCreateDocument || mRecord.CanSendEmail) {
      // Prompt
      var list = [];
      if (mRecord.CanAddLog) list.push({ key: "ADD", caption: "Add Log", icon: "Log|Add", details: "Record Close Quotation details to a Log." });
      if (mRecord.CanCreateDocument) list.push({ key: "DOCUMENT", caption: "Print", icon: "DocumentType_PDF", details: "Download a Close Quotation PDF." });
      if (mRecord.CanSendEmail) {
        if (mRecord.EmailMainClient) list.push({ key: "EMAIL_MAINCLIENT", caption: "Email Main Client", icon: "Client|Mail", details: "Email a Close Quotation PDF to:\n" + mRecord.EmailMainClient });
        if (mRecord.EmailBroker) list.push({ key: "EMAIL_BROKER", caption: "Email Broker", icon: "ExternalParty|Mail", details: "Email a Close Quotation PDF to:\n" + mRecord.EmailBroker });
        if (mRecord.EmailDealer) list.push({ key: "EMAIL_Dealer", caption: "Email Dealer", icon: "ExternalParty|Mail", details: "Email a Close Quotation PDF to:\n" + mRecord.EmailDealer });
      }

      widget.UI.MsgBoxList("", list, { closeOnEscape: true, title: "Account Close Quotation", showClose: true }, Form_ExecuteAction_FinishProcessSelection);
    }
    else {
      // Can't do anything so just close!
      Form_ExecuteAction_FinishPost_Finalise();
    }
  });
}

function Form_ExecuteAction_FinishProcessSelection(key) {
  switch(key) {
    case "CANCEL":
      break;
    default:
      Form_ExecuteAction_FinishPost(key);
      break;
  }
}

function Form_ExecuteAction_FinishPost(action) {
  // Disable Form
  widget.UI.Block("Committing, please wait...");

  // Create Parameters
  var params = {
    // General
    CloseDate: C.dateClose.Value(),
    FuturePaymentsShow: C.chkFuturePaymentsShow.Value(),
    Action: action,
  };

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

      // Finalise
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Close Quotation was successfully produced but the following warning was given:\n\n" + data.Warning, {}, function () { Form_ExecuteAction_FinishPost_Finalise(data, action); });
      }
      else {
        Form_ExecuteAction_FinishPost_Finalise(data, action);
      }
    },

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

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

function Form_ExecuteAction_FinishPost_Finalise(data, action) {
  // Download Document?
  switch (action) {
    case "DOCUMENT":
      // Use an Application Shortcut to download the document
      widget.ExecuteApplicationShortcutUrl("app://Document?id=" + encodeURI(data.DocumentId) + "&amp;logPk=" + data.AccountLogPk);
      break;
  }

  // Close Form
  widget.Close();

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

// =========
// dateClose
// =========
function dateClose_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Preview
  wbAccountSummary_Refresh();
}

// =====================
// chkFuturePaymentsShow
// =====================
function chkFuturePaymentsShow_Change(source, e) {
  // Update Preview
  wbAccountSummary_Refresh();
}

// ================
// wbAccountSummary
// ================
function wbAccountSummary_Refresh() {
  widget.GetString("Form_AccountSummary_Refresh", { CloseDate: C.dateClose.Value(), FuturePaymentsShow: C.chkFuturePaymentsShow.Value() }, wbAccountSummary_Refresh_Done, wbAccountSummary_Refresh_Fail);
}

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

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

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

  // Finalise
  mRefreshRequired = false;
}

function wbAccountSummary_Refresh_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>WVLDbaRpx02-ZZ7LQn3Ojg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <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>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EmailAllowMainClient" type="Boolean">
            <BlankTip />
            <Caption>Allow Emailing to Main Account Client?</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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EmailAllowBroker" type="Boolean">
            <BlankTip />
            <Caption>Allow Emailing to Broker?</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>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="EmailAllowDealer" type="Boolean">
            <BlankTip />
            <Caption>Allow Emailing to Dealer?</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>True</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>