<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-17T23:18:13.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-09-11T03:31:15.2350000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-17T23:14:48.3990000</UpdatedUtcDate>
    <ScriptId>HWCPIDFACC</ScriptId>
    <Description>Create PayID from Account</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountPaymentPayIdCreate
Option Explicit On
Option Strict On

' ####################################################################
' Split/ Zepto Create PayID From Account wizard HTML Widget
'
' Copyright (C) Intersoft Systems Limited 2023
'
' Version: 1.01 (18/09/2024)
'
' Usage: System-supplied HTML Widget
' ####################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  11/09/2023  ISS      J031926   Created
'    1.01  12/09/2024  ISS      J034267   Changed how the Message is handled in GetInitialisationInfo
'          18/09/2024  ISS      J029950   Changed the Workflow Executor to the finBL.HtmlWidgetUtilities.WorkflowItemComplete function
' ####################################################################

' Constants
Private Const FORM_KEY As String = "AccountPaymentPayIdCreate"

' Common Parameters
Private mAccountId As String
Private mWorkflowPk As Integer
Private mWorkflowItemPk 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
    mAccountId = .GetString("AccountId")
    mWorkflowPk = .GetInteger("WorkflowPk")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
  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 "GetEmailDetails"
      ' Get Email Details
      Main = GetEmailDetails(parametersJson, returnValue)

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

    Case "GetServiceReport"
      ' Get Service Report
      Main = GetServiceReport(parametersJson, returnValue)

    Case "PerformCreatePayIdFromAccount"
      ' Perform Create PayID
      Main = PerformCreatePayIdFromAccount(parametersJson, 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 DefaultName As String
  Dim Email As String
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Message As String
  Dim MessagingContacts As finMessagingContacts
  Dim NameListCsv As String
  Dim Success As Boolean

  ' Assume Success
  Success = True
   
  ' Initialise
  DefaultName = ""
  Email = ""
  Message = ""
  MessagingContacts = finBL.CreateMessagingContacts()
  NameListCsv = ""
  
  ' Validate
  If Len(mAccountId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Id details not specified.")
  ElseIf Len(mAccountId) &lt;&gt; 0 AndAlso finBL.CurrentUserInformation.IsAccountFilteredOut(mAccountId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Account.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If

  ' Get Account objects
  If Success Then
    Success = GetAccountWithDetails(Account, NameListCsv, DefaultName, MessagingContacts)
  End If
  
  ' Get Email
  If Success Then
    If Not finBL.BankingInterface.Service_Split.GetDefaultPayIdEmail(Account, Email, "", Message) Then
      Success = False
      If Len(Message) &lt;&gt; 0 Then
        finBL.Error.ErrorBegin(Message)
      End If
    End If
  End If
  
  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()

    ' Other Properties
    With FormInitialisationInfo
      ' General
      If Account IsNot Nothing Then
        .AccountId = Account.AccountId
        .AccountName = Account.Name
      End If
      .WorkflowPk = mWorkflowPk
      .Email = Email
      
      ' Lists
      .NameList = NameListCsv
      .EmailAddresses = MessagingContacts.ToJsonObject()

      ' Defaults
      .DefaultName = DefaultName
      
      ' Configuration
      .TestMode = finBL.SettingsUser.CostCentreTestModeResolved
    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 a finAccount object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function GetAccount(ByRef account As finAccount) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  account = Nothing
  
  ' Initialise
  
  ' Account
  If Len(mAccountId) &lt;&gt; 0 Then
    ' Account
    account = finBL.CreateAccount()
    Success = account.Load(mAccountId)
  Else
    Success = False
  End If
  
  ' Validate
  If Success Then
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get a finAccount object from Web Service properties with Details.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function GetAccountWithDetails(ByRef account As finAccount,
                                       ByRef nameListCsv As String,
                                       ByRef defaultName As String,
                                       ByRef messagingContacts As finMessagingContacts) As Boolean

  Dim AccountClient As finAccountClient                            
  Dim BankingDetails As finBankingDetails
  Dim List As ISList
  Dim PaymentMethod As finPaymentMethodRO
  Dim PaymentTypeCategory As isefinPaymentTypeCategory
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  account = Nothing
  nameListCsv = ""
  defaultName = ""
  messagingContacts = finBL.CreateMessagingContacts()
  
  ' Initialise
  List = New ISList()
  
  ' Account
  If Success Then
    Success = GetAccount(account)
  End If

  ' Account Names
  If Success Then
    If Account.BankingDetails.ExistsBankingDetailsType(isefinAccountBankingDetailsType.Incoming) Then
      PaymentMethod = Account.BankingDetails(isefinAccountBankingDetailsType.Incoming).BankingDetails.PaymentMethod
      If PaymentMethod IsNot Nothing Then
        PaymentTypeCategory = PaymentMethod.PaymentTypeCategory
      End If
  
      ' Get Bank Details, potentially masked
      BankingDetails = Account.BankingDetails(isefinAccountBankingDetailsType.Incoming).BankingDetails.CloneForDisplay()
  
      Select Case PaymentTypeCategory
        Case isefinPaymentTypeCategory.Split
          defaultName = BankingDetails.AccountName
        Case Else
          defaultName = ""
      End Select
    End If    
    
    List.Clear()
    If Len(defaultName) &lt;&gt; 0 Then List.Add(defaultName)
    For Each AccountClient In Account.Clients
      List.Add(AccountClient.Client.GetFullName(True, True, False, False, True))
    Next
    If Len(defaultName) = 0 AndAlso List.Count &lt;&gt; 0 Then defaultName = List(0)
    nameListCsv = List.ToCsvString()      
  End If

  ' Emails
  messagingContacts = finBL.CreateMessagingContacts()
  messagingContacts.LoadAccount_Email(account, True, True, True, True, True, True, True)
  
  ' Validate
  If Success Then
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Email Details.
''' &lt;/summary&gt;
Private Function GetEmailDetails(parametersJson As String,
                                 ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim Email As String
  Dim EmailPrefix As String
  Dim Message As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  Email = ""
  Message = ""
  
  ' Parameters
  With mCombinedParameters
    EmailPrefix = .GetString("EmailPrefix")
  End With

  ' Get Account object
  If Success Then
    Success = GetAccount(Account)
  End If

  ' Email
  If Success Then
    Success = finBL.BankingInterface.Service_Split.GetDefaultPayIdEmail(Account, Email, EmailPrefix, Message)
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New EmailResponseParameters(Email, Message), returnValue)
  End If

  Return Success

End Function

Private Function PerformCreatePayIdFromAccount(parametersJson As String,
                                               ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountLogPk As Integer
  Dim ContactId As String
  Dim Html As String
  Dim obj As Object
  Dim PayIdEmail As String
  Dim ServiceLogPk As Integer             
  Dim Success As Boolean
  Dim strTemp As String
  Dim Warnings As ISValidationItems
  Dim WizardFinishParameters As WizardFinishParameters

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

  ' Create the Account
  If Success Then
    Success = GetAccount(Account)
  End If

  ' Create the PayID
  If Success Then
    Success = finBL.BankingInterface.Service_Split.CreateReceivableContactFromAccount(Account, WizardFinishParameters.Name, WizardFinishParameters.Email, ContactId, WizardFinishParameters.EmailPrefix, PayIdEmail, AccountLogPk, ServiceLogPk, mWorkflowPk, mWorkflowItemPk)
  End If

  ' Get Report
  If Success Then
    Html = GetServiceReportInternal(ServiceLogPk)
  End If

  ' Complete Workflow Item
  If Success Then
    finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, strTemp)
    
    If Len(strTemp) &lt;&gt; 0 Then
      Warnings.Add("The PayID was created successfully, however the Workflow Item could not be actioned due to the following error:" &amp; vbNewLine &amp; vbNewLine &amp; strTemp)
    End If
  End If
    
    ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountLogPk, Html, ServiceLogPk, Warnings.GetSummaryNumbered(False, False, True, , True, True)), returnValue)
  End If

  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get Service Report.
''' &lt;/summary&gt;
Private Function GetServiceReport(parametersJson As String,
                                  ByRef returnValue As String) As Boolean

  Dim Html As String
  Dim ServiceLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    ServiceLogPk = .GetInteger("ServiceLogPk")
  End With

  ' Get Report
  Html = GetServiceReportInternal(ServiceLogPk)

  ' Finalise
  If Success Then
    returnValue = Html
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Internal Get Service Report.
''' &lt;/summary&gt;
Private Function GetServiceReportInternal(serviceLogPk As Integer) As String

  Dim Html As String
  Dim ServiceLogs As ISServiceLogs

  ' Get HTML
  If finBL.Database.GetServiceLogs(serviceLogPk, ServiceLogs) Then
    If Not finBL.Utilities.GetServiceLogSummaryPageHtml(ServiceLogs.ItemByPk(serviceLogPk), Html) Then
      Html = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
    End If
  Else
    Html = finBL.GetHtmlErrorMessage(finBL.Error.Message, finBL.Error.Details)
  End If

  Return Html

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&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 "CreatePayId"
      ' CreatePayID
  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 AccountId As String
  Public AccountName As String

  Public WorkflowPk As Integer

  Public Email As String
  Public EmailWarning As String
  
  ' Lists
  Public NameList As String
  Public EmailAddresses As Object
  
  ' Defaults
  Public DefaultName As String
  
  ' Configuration
  Public TestMode 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 AccountId As String
  Public Name As String
  Public Email As String
  Public EmailPrefix As String
  Public PayIdEmail As String

End Class


''' &lt;summary&gt;
'''  Email Parameters.
''' &lt;/summary&gt;
Public Class EmailResponseParameters

  ' General
  Public Email As String
  Public Message As String

  Public Sub New(email As String,
                message As String)
    
    Me.Email = email
    Me.Message = message
  
  End Sub
End Class


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

  ' General
  Public AccountLogPk As Integer
  Public Html As String
  Public ServiceLogPk As Integer
  Public Warning As String

  Public Sub New(accountLogPk As Integer,
                 html As String,
                 serviceLogPk As Integer,
                 warning As String)

    Me.AccountLogPk = accountLogPk
    Me.Html = html
    Me.ServiceLogPk = serviceLogPk
    Me.Warning = warning

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

Used as a finPOWER Connect Cloud compatible wizard to allow an "Split/ Zepto" Create PayID from Account to be performed.</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="CreatePayID" tooltipText="Enter details to create a new PayID for an Account"&gt;Organisation Enquiry&lt;/li&gt;
        &lt;li tabId="PayID" tooltipText="New PayID detail."&gt;Enquiry Report&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Create PayID --&gt;
    &lt;div id="pageCreatePayID"&gt;
      &lt;table class="is-form"&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 details&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="lblPayIdContact"&gt;PayID Contact details.&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboName" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboEmail"&gt;Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboEmail" /&gt;&lt;/td&gt;
        &lt;/tr&gt;        
        &lt;tr&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;div id="divContactDetails" class="is-info-text info small" style="display:none"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPayIdEmail"&gt;PayID Email details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPayIdEmailPrefix"&gt;Prefix:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPayIdEmailPrefix" /&gt;&lt;/td&gt;
        &lt;/tr&gt;        
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPayIdEmail"&gt;Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPayIdEmail" /&gt;&lt;/td&gt;
        &lt;/tr&gt;          
        &lt;tr&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td colspan="2"&gt;&lt;div id="divPayIdEmailMessage" class="is-info-text info small" style="display:none"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- New PayID --&gt;
    &lt;div id="pagePayID"&gt;
      &lt;div id="wbSummary" class="is-dock-fill"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Finish&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;



&lt;script&gt;
// Properties
var mRecord;
var mRecord_PayIDCreated;
var mRecord_EmailDetails;

// Controls
var C = {
  // Create PayID
  lblAccount: null,
  cboAccount: null,
  
  lblPayIdContact: null,
  cboName: null,
  cboEmail: null,
  divContactDetails: null,
  
  lblPayIdEmail: null,
  txtPayIdEmailPrefix: null,
  txtPayIdEmail: null,
  divPayIdEmailMessage: null,

  // New PayID
  wbSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mLastProduct = "";
var mLastFinishParametersJson = "";

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

  // --------
  // Controls
  // --------
  //   Account
  C.lblAccount = widget.UI.Label("lblAccount", {});
  C.cboAccount = widget.UI.DBCombo("cboAccount", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10
  });
   
  C.lblPayIdContact = widget.UI.Label("lblPayIdContact", {});
  C.cboName = widget.UI.DBCombo("cboName", {
    allowBlank: false,
    autoReadOnly: true,
    readOnly: false,
    showDropdown: true,
    maxLength: 50,
  });
  C.cboEmail = widget.UI.DBCombo("cboEmail", {
    allowBlank: false,
    limitToList: false,
    maxLength: 50,
    showDescription: false
  });  
  C.divContactDetails = $("#divContactDetails");  
          
  C.lblPayIdEmail = widget.UI.Label("lblPayIdEmail", {});
  C.txtPayIdEmailPrefix = widget.UI.TextBox("txtPayIdEmailPrefix", {
    allowBlank: true,
    multiLine: false,
    readOnly: false,
    maxLength: 50,
    onChange: txtPayIdEmailPrefix_Change,
  });  
  C.txtPayIdEmail = widget.UI.TextBox("txtPayIdEmail", {
    allowBlank: false,
    multiLine: false,
    readOnly: true,
    maxLength: 50,
  });  
  C.divPayIdEmailMessage = $("#divPayIdEmailMessage");  

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

  // Grids

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

  // Handle Notifications
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Reset
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_PayIDCreated = null;
  mRecord_EmailDetails - 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);

      // Give Collections ability to lookup by code

      // Load Fields
      Fields_Load();
    },

    // Fail
    function (message) {
      widget.UI.MsgBoxAlert("fail: " + message);
      Fields_Load();
    }
  );
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
      // Account
      C.cboAccount.RefreshUnbound(mRecord.AccountId, mRecord.AccountName);
      
      // Names
      C.cboName.ListFromCsvString(mRecord.NameList);
      C.cboName.Text(mRecord.DefaultName);
      
      // Emails
      C.cboEmail.RefreshFromCollection(mRecord.EmailAddresses, "Value", "SourceNameAndDescription", "Source,Name,Role,Description,Value");
      
      // Email
      C.txtPayIdEmail.Text(mRecord.Email);
      
      // Select first Email Address
      if (!C.cboEmail.Text()) C.cboEmail.ListIndex(0);

      C.divPayIdEmailMessage.hide();
  }

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

// ===================
// txtPayIdEmailPrefix
// ===================
function txtPayIdEmailPrefix_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Get Email and any Messages
  widget.GetString("GetEmailDetails", { EmailPrefix: C.txtPayIdEmailPrefix.Text() },
    // Success
    function(data) {
      mRecord_EmailDetails = JSON.parse(data);

      if(mRecord_EmailDetails) {
        C.txtPayIdEmail.Text(mRecord_EmailDetails.Email);
        if(mRecord_EmailDetails.Message) {
          C.divPayIdEmailMessage.html(mRecord_EmailDetails.Message);
          C.divPayIdEmailMessage.show();
        } else {
          C.divPayIdEmailMessage.hide();
        }
      }
    },

    // Failure
    function(errorMessage) {
      widget.UI.Unblock();
    }
  );
} 
  
// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  widget.SetHeading("Create PayID for Account");

  // Information Lists

  // Lists
  if (mRecord) {
  }

  // Controls
  if (mRecord) {
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  widget.Close();
}

function tabWizard_UpdateButtons() {
  // Back and Next Buttons?
  if (tabWizard.TabCount() == 1) {
    cmdBack.hide();
    cmdNext.hide();
  }
  else {
    var tabIndex = tabWizard.SelectedTabIndex();
    if(!mRecord_PayIDCreated) {
      cmdBack.prop("disabled", tabIndex &lt;= 0);
    } else {
    // Can't go backwards if the Create has already run
    cmdBack.prop("disabled", true);
    }
    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 "CreatePayID":
      C.cboAccount.WidthResizeFromParent();
      C.cboName.WidthResizeFromParent();
      C.cboEmail.WidthResizeFromParent();
      C.txtPayIdEmail.WidthResizeFromParent();
      C.txtPayIdEmailPrefix.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);

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "CreatePayID":
      frmMain.RefreshHeading("Create PayID", tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;

    case "PayID":
      frmMain.RefreshHeading("PayID", tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      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 "CreatePayID":
        // If parameters have changed so allow performing another Enquiry
        if (mRecord_PayIDCreated &amp;&amp; mLastFinishParametersJson != JSON.stringify(CreateFinishParameters())) {
          mRecord_PayIDCreated = null;
        }

        // Perform Create PayID
        PerformCreatePayID_Pre(validCallback);
        return;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "CreatePayID":
        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 "Options":
        mRecord_CompanySelection = o.Data;

        // Refresh Grid
        C.gridCompanySelection.VirtualDataRefresh(mRecord_CompanySelection);
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ====================
// Perform Create PayID
// ====================
function PerformCreatePayID(successCallback) {
  // Block UI
  widget.UI.Block("Performing Create PayID, please wait...");

  // Save parameters
  mLastFinishParametersJson = JSON.stringify(CreateFinishParameters());

  // Perform Enquiry
  widget.GetString("PerformCreatePayIdFromAccount", CreateFinishParameters(), function (data) { PerformCreatePayID_Success(data, successCallback); }, PerformCreatePayID_Fail);
}

function PerformCreatePayID_Success(data, successCallback) {
  // Parse
  mRecord_PayIDCreated = JSON.parse(data);

  // Show Enquiry Details
  C.wbSummary.SetContent(mRecord_PayIDCreated.Html, false);

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

  // Callback
  successCallback();

  // Show warning
  if (mRecord_PayIDCreated.Warning) widget.UI.MsgBoxAlert(mRecord_PayIDCreated.Warning);

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

function PerformCreatePayID_Fail(error) {
  // Unblock UI
  widget.UI.Unblock();

  widget.UI.MsgBoxAlert(error);
}

function PerformCreatePayID_Pre(validCallback) {
  // Confirm
  if (mRecord_PayIDCreated) {
    validCallback();
  }
  else {
    PerformCreatePayID(validCallback);
  }
}

// =================
// 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() {
  widget.Close();
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var params = {
    name: C.cboName.Text(),
    email: C.cboEmail.Text(),
    emailPrefix: C.txtPayIdEmailPrefix.Text(),
    payIdEmail: C.txtPayIdEmail.Text(),
  };

  return params;
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId) {
    case "AccountRefresh":
      // Refresh report
      wbSummary_Refresh();
      break;
  }
}

// =========
// wbSummary
// =========
function wbSummary_Refresh() {
  widget.GetString("GetServiceReport", { serviceLogPk: mRecord_PayIDCreated.ServiceLogPk },
    function (data) {
      C.wbSummary.SetContent(data, false);
    },

    function (error) {
      widget.UI.MsgBoxAlert(error);
    }
  );
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>l3Gwe+O8hUuzbDINEwskyg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>800</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>Logo_Zepto</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="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AccountId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="WorkflowPk" 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>
          <Parameter name="WorkflowItemPk" 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>