<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-09-29T02:05:33.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2021-08-16T03:33:54.5430000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-09-29T02:04:38.1770000</UpdatedUtcDate>
    <ScriptId>SECALLOC</ScriptId>
    <Description>Securitisation Allocation</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_SecuritisationAllocation
Option Explicit On
Option Strict On

' #################################################################
' Securitisation Allocation
'
' Version: 1.04 (29/09/2022)
'
' Usage: System-defined HTML Widget
'
' NOTE: Uses Web Services Background Processes
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  17/08/2021  ISS      J027225   Created Stub
'    1.01  22/11/2021  ISS      J020367   Implemented HTML Widget
'    1.02  08/12/2021  ISS      J027840   Spelling Correction
'    1.03  07/06/2022  ISS      J028452   User Defined fields not retaining indexes
'    1.04  29/09/2022  ISS      J029737   Implemented widget.UI.BuildBackgroundProcessProgress
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountSecuritisationAllocation"
Private Const BATCH_SIZE As Integer = 25

' Objects
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

' Other
Private mAutoCommit As Boolean
Private mProcessId As String

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 Parameters
  With mCombinedParameters
    mAutoCommit = .GetBoolean("AutoCommit")
    mProcessId = .GetString("ProcessId")
  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 "CancelBackgroundProcess"
      ' Cancel a Process
      Main = CancelBackgroundProcess(returnValue)

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

    Case "GetBackgroundProcessStatus"
      ' Get Background Process Status
      Main = GetBackgroundProcessStatus(returnValue)

    Case "GetCurrentProcesses"
      ' Get Current Processes
      Main = GetCurrentProcesses(returnValue)

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

    Case "GetUpdateItemPreview"
      ' Get the HTML Summary Page for the active row on the grid
      Main = GetUpdateItemPreview(returnValue)

    Case "Refresh"
      ' Refresh (and Execute Commit, if in Auto Commit mode)
      Main = Refresh(parametersJson, returnValue)

    Case "UpdateRefreshData"
      ' Update Refresh Data
      Main = UpdateRefreshData(parametersJson)

    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;
Private Function GetInitialisationInfo(ByRef returnValue As String) As Boolean

  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Validate
  Success = finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY)

  ' Validate Process Id
  If Success AndAlso Len(mProcessId) &lt;&gt; 0 Then
    Success = finBL.HtmlWidgetUtilities.BackgroundProcessStatusIsValid(mProcessId, isefinCloudConnectProcessType.AccountSecuritisationAllocations)
  End If

  ' Get Form Initialisation Info
  If Success Then
    With FormInitialisationInfo
      ' Record
      .DefaultDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
      .ProcessId = mProcessId
      If finBL.Settings.AccountSecuritisationSaleParameterSetPk &lt;&gt; 0 Then .SaleParameters = finBL.CreateWsParameters(finBL.ParameterSets(finBL.Settings.AccountSecuritisationSaleParameterSetId).CreateParameters())
      If finBL.Settings.AccountSecuritisationBuybackParameterSetPk &lt;&gt; 0 Then .BuybackParameters = finBL.CreateWsParameters(finBL.ParameterSets(finBL.Settings.AccountSecuritisationBuybackParameterSetId).CreateParameters())
      If finBL.Settings.AccountSecuritisationTransferParameterSetPk &lt;&gt; 0 Then .TransferParameters = finBL.CreateWsParameters(finBL.ParameterSets(finBL.Settings.AccountSecuritisationTransferParameterSetId).CreateParameters())

      ' Advanced
      .ShowMaxValue = mCombinedParameters.GetString("ShowMaxValue") : If Len(.ShowMaxValue) = 0 Then .ShowMaxValue = "Advanced"
      .ShowSecuritisationType = mCombinedParameters.GetString("ShowSecuritisationType") : If Len(.ShowSecuritisationType) = 0 Then .ShowSecuritisationType = "Advanced"
      .PageGeneralHasAdvanced = (.ShowMaxValue = "Advanced" OrElse .ShowSecuritisationType = "Advanced")

      ' Permissions
      .PermissionTransferToSameBulkFunder = finBL.CurrentUser.Permissions.Allow("Account.Securitisations.TransferToSameBulkFunder")
      .PermissionAllocateBuyback = finBL.CurrentUser.Permissions.Allow("Account.Securitisations.AllocateBuyback")
      .PermissionAllocateSale = finBL.CurrentUser.Permissions.Allow("Account.Securitisations.AllocateSale")
      .PermissionAllocateTransfer = finBL.CurrentUser.Permissions.Allow("Account.Securitisations.AllocateTransfer")

      ' Configuration
      .AutoCommit = mAutoCommit
      .CustomDisplayColumnHeading1 = finBL.Settings.AccountSecuritisationCustomDisplayColumn1HeadingResolved
      .CustomDisplayColumnHeading2 = finBL.Settings.AccountSecuritisationCustomDisplayColumn2HeadingResolved
      .CustomDisplayColumnHeading3 = finBL.Settings.AccountSecuritisationCustomDisplayColumn3HeadingResolved
      .CustomDisplayColumnHeading4 = finBL.Settings.AccountSecuritisationCustomDisplayColumn4HeadingResolved
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    End With

    ' Get current and recent Background Processes for this User
    If Success Then
      If finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_AccountSecuritisationAllocations(True, ProcessStatuses) Then
        FormInitialisationInfo.CurrentProcesses = ProcessStatuses
      Else
        Success = False
      End If
    End If

    ' Serialise
    If Success Then
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, returnValue)
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get the HTML Summary Page for the active row on the grid.
''' &lt;/summary&gt;
Private Function GetUpdateItemPreview(ByRef returnValue As String) As Boolean

  Dim AccountId As String
  Dim AccountSecuritisationAllocations As finAccountSecuritisationAllocations
  Dim Found As Boolean
  Dim i As Integer
  Dim ProcessId As String
  Dim RefreshData As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  AccountSecuritisationAllocations = finBL.CreateAccountSecuritisationAllocations()

  ' Get Parameters
  With mCombinedParameters
    AccountId = .GetString("AccountId")
    ProcessId = .GetString("ProcessId")
  End With

  If Len(AccountId) &lt;&gt; 0 Then
    ' Restrict Results to this Account
    Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessRefreshData(ProcessId, RefreshData)

    ' Build Object from Json
    If Success Then
      Success = AccountSecuritisationAllocations.FromHtmlWidgetJsonString(RefreshData)
    End If

    ' Get Index of item
    If Success Then
      For i = 0 To AccountSecuritisationAllocations.Count - 1
        If StrComp(AccountSecuritisationAllocations(i).AccountId, AccountId, CompareMethod.Text) = 0 Then
          Found = True
          Exit For
        End If
      Next
    End If

    ' Get Summary
    If Success Then
      If Found Then
        returnValue = finBL.SummaryPageFunctions.AccountSecuritisationAllocationsSummary(False, AccountSecuritisationAllocations, i, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
      Else
        Success = False
        finBL.Error.ErrorBeginFormat("Could not find Account '{0}'", AccountId)
      End If
    End If
  End If

  ' Error
  If Not Success Then
    returnValue = finBL.GetHtmlErrorMessage(finBL.Error.Message(True, False, True))
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Request that a Background Process is Cancelled.
''' &lt;/summary&gt;
Private Function CancelBackgroundProcess(ByRef returnValue As String) As Boolean

  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ProcessId = mCombinedParameters.GetString("ProcessId")

  ' Request Cancel
  Success = finBL.HtmlWidgetUtilities.CancelBackgroundProcess(processId)

  Return Success

End Function

''' &lt;summary&gt;
'''  Gets Account Securitisation Allocations.
''' &lt;/summary&gt;
Private Function CreateAccountSecuritisationAllocations(parameters As WizardFinishParameters,
                                                        ByRef accountSecuritisationAllocations As finAccountSecuritisationAllocations) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountSecuritisationAllocations = finBL.CreateAccountSecuritisationAllocations()

  ' Update Parameters
  If Success AndAlso parameters IsNot Nothing Then
    With accountSecuritisationAllocations
      .FromExternalPartyId = parameters.FromExternalPartyId
      .ToExternalPartyId = parameters.ToExternalPartyId
      .SecuritisationType = parameters.SecuritisationType
      .Date = parameters.Date
      .Value = parameters.Value

      ' Parameters
      If Len(parameters.CustomParametersJson) &lt;&gt; 0 Then
        .ScriptProperties.FromHtmlWidgetParametersJsonString(parameters.CustomParametersJson)
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Refresh, i.e., Queue Background Process.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Refresh(parametersJson As String,
                         ByRef returnValue As String) As Boolean

  Dim AccountSecuritisationAllocations As finAccountSecuritisationAllocations
  Dim ProcessId As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Validate

  ' Parse Parameters
  Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

  ' Get finAccountSecuritisationAllocations Object
  If Success Then
    Success = CreateAccountSecuritisationAllocations(WizardFinishParameters, AccountSecuritisationAllocations)
  End If

  ' Queue Background Process
  If Success Then
    Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_AccountSecuritisationAllocations_Refresh(AccountSecuritisationAllocations, mAutoCommit, ProcessId)
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Queue Background Process.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        ByRef returnValue As String) As Boolean

  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Queue Background Process
  If mAutoCommit Then
    ' Queue "Refresh" - Execute Commit will occur automatically
    Success = Me.Refresh(parametersJson, returnValue)
  Else
    ' Get Wizard Finish Parameters
    Success = GetWizardFinishParameters(parametersJson, WizardFinishParameters)

    ' Queue Background Process
    If Success Then
      Success = finBL.HtmlWidgetUtilities.QueueBackgroundProcess_AccountSecuritisationAllocations_ExecuteCommit(WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData)
    End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Background Process Status.
''' &lt;/summary&gt;
Private Function GetBackgroundProcessStatus(ByRef returnValue As String) As Boolean

  Dim LastEventId As String
  Dim ProcessId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    LastEventId = .GetString("LastEventId")
    ProcessId = .GetString("ProcessId")
  End With

  ' Get Background Processes Status including Events
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessStatusIncludingEventsJson(processId, lastEventId, returnValue)

  Return Success

End Function

''' &lt;summary&gt;
'''  Get current and recent Background Processes that for this User (these  are also returned in GetInitialisationInfo).
''' &lt;/summary&gt;
Private Function GetCurrentProcesses(ByRef returnValue As String) As Boolean

  Dim ProcessStatuses As List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get current and recent Background Processes that for this User
  Success = finBL.HtmlWidgetUtilities.GetBackgroundProcessesJson_AccountSecuritisationAllocations(True, ProcessStatuses)

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ProcessStatuses, returnValue)
  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;
'''  Update Refresh Data.
''' &lt;/summary&gt;
Private Function UpdateRefreshData(parametersJson As String) As Boolean

  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Update Process
  If Success Then
    Success = finBL.HtmlWidgetUtilities.UpdateBackgroundProcessRefreshData(WizardFinishParameters.ProcessId, WizardFinishParameters.RefreshData)
  End If

  Return Success

End Function



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

  ' Current Processes
  Public CurrentProcesses As New List(Of finHtmlWidgetUtilities.JsonProcessStatusInformation)

  ' Record
  Public BuybackParameters As ISWsParameters
  Public DefaultDate As Date
  Public ProcessId As String
  Public SaleParameters As ISWsParameters
  Public TransferParameters As ISWsParameters

  ' Advanced
  Public PageGeneralHasAdvanced As Boolean
  Public ShowMaxValue As String
  Public ShowSecuritisationType As String

  ' Permissions
  Public PermissionTransferToSameBulkFunder As Boolean
  Public PermissionAllocateBuyback As Boolean
  Public PermissionAllocateSale As Boolean
  Public PermissionAllocateTransfer As Boolean

  ' Configuration
  Public AutoCommit As Boolean
  Public CustomDisplayColumnHeading1 As String
  Public CustomDisplayColumnHeading2 As String
  Public CustomDisplayColumnHeading3 As String
  Public CustomDisplayColumnHeading4 As String
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean

End Class



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

  Public ProcessId As String

  Public Sub New(processId As String)

    Me.ProcessId = processId

  End Sub

End Class



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

  Public [Date] As Date
  Public CustomParametersJson As String
  Public FromExternalPartyId As String
  Public ProcessId As String
  Public RefreshData As String
  Public SecuritisationType As String
  Public ToExternalPartyId As String
  Public Value As Decimal

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountSecuritisationAllocation".</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
/* Total Summary when a total value has been specified */
.value-summary {
  display:flex;
  flex-direction:row;

  div {
    font-size:11px;

    &gt; b {
      font-size:14px;
    }
  }

  div:nth-child(2),
  div:nth-child(3) {
    padding-left:12px;

    .variance-red {
      color: red;
    }

    .variance-blue {
      color: blue;
    }

    .variance-green {
      color: green;
    }
  }
}

/* Small device portrait */
@media screen and (max-width:640px) {
  .value-summary {
    flex-direction:column;
    font-size:12px;

    div:nth-child(2),
    div:nth-child(3) {
      padding-left:0px;
    }
  }
}
&lt;/style&gt;

&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="CurrentProcesses" tooltipText="Drilldown to view the status of current and recent Securitisation Allocations you have processed."&gt;Recent Securitisation Allocations&lt;/li&gt;
        &lt;li tabId="General" tooltipText="Enter Allocation Options."&gt;Securitisation Allocation options&lt;/li&gt;
        &lt;li tabId="Parameters" tooltipText="Enter additional Parameters."&gt;Parameters&lt;/li&gt;
        &lt;li tabId="UpdateItems" tooltipText="Select Accounts to Allocate."&gt;Allocation Items&lt;/li&gt;
        &lt;li tabId="Progress" tooltipText="Processing progress."&gt;Progress&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- Current Processes --&gt;
    &lt;div id="pageCurrentProcesses"&gt;
      &lt;div id="gridCurrentProcesses"&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="lblAllocationType"&gt;Select the type of Allocation to perform&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="rblAllocationType"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr id="trPermissionWarning"&gt;
          &lt;th colspan="2"&gt;&lt;div id="divPermissionWarning" class="is-info-text info small"&gt;The Allocation Types are limited due to your Permissions.&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSelectedlblAllocationType"&gt;&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateAllocationDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateAllocationDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboFromBulkFunder"&gt;From Funder:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboFromBulkFunder" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboToBulkFunder"&gt;To Funder:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboToBulkFunder" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="SecuritisationType"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSecuritisationType"&gt;Securitisation Type&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="SecuritisationType"&gt;
          &lt;th&gt;&lt;label for="cboSecuritisationType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSecuritisationType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr advancedId="MaxValue"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblMaxValue"&gt;Optionally, specify a maximum value&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr advancedId="MaxValue"&gt;
          &lt;th&gt;&lt;label for="numMaxValue"&gt;Value:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numMaxValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Parameters --&gt;
    &lt;div id="pageParameters"&gt;
      &lt;div id="phParameters"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Update Items --&gt;
    &lt;div id="pageUpdateItems"&gt;
      &lt;div class="is-dock-fill is-split-container split5050"&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridUpdateItems"&gt;&lt;/div&gt;
          &lt;div id="divAllocationsSummary" class="is-info-text info" style="position:absolute; bottom:2px; right:2px; line-height:19px; font-size:15px; margin:0"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div id="wbUpdateItemSummary" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Progress --&gt;
    &lt;div id="pageProgress" style="display:flex"&gt;
      &lt;div id="divProgress" class="progress-events"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdHistory" class="is-button" style="float:left"&gt;Recent&lt;/button&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;&amp;lt; Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next &amp;gt;&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Commit&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;

&lt;script&gt;
// Properties
var mRecord;
var mRecord_BackgroundProcessStatus;
var mRecord_CurrentProcesses;

var mAccountSecuritisationAllocations;

// Controls
var C = {
  //   Current Processes
  gridCurrentProcesses: null,

  //   General
  lblAllocationType: null,
  rblAllocationType: null,
  trPermissionWarning: null,

  lblSelectedlblAllocationType: null,
  dateAllocationDate: null,
  cboFromBulkFunder: null,
  cboToBulkFunder: null,

  lblSecuritisationType: null,
  cboSecuritisationType: null,

  lblMaxValue: null,
  numMaxValue: null,

  //   Parameters
  phParameters: null,

  //   Allocation Items
  gridUpdateItems: null,
  divAllocationsSummary: null,
  wbUpdateItemSummary: null,

  //   Progress
  divProgress: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdHistory;
var cmdAdvanced;

// Other
var mAccounts;
var mAdvancedVisible = false;
var mComplete = false;
var mFromRecent = false;
var mLastRefreshParametersJson = "";
var mMonitoringExisting = false;
var mProcessId;

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

  // Controls
  //   General
  C.lblAllocationType = widget.UI.Label("lblAllocationType", {});
  C.rblAllocationType = widget.UI.RadioButtonList("rblAllocationType", {
    allowBlank: false,
    layout: "vertical",

    onChange: rblAllocationType_Change,
  });
  C.trPermissionWarning = $("#trPermissionWarning");

  C.lblSelectedlblAllocationType = widget.UI.Label("lblSelectedlblAllocationType", {});
  C.cboFromBulkFunder = widget.UI.DBCombo("cboFromBulkFunder", {
    allowBlank: false,
    limitToList: true,
  });
  C.cboToBulkFunder = widget.UI.DBCombo("cboToBulkFunder", {
    allowBlank: false,
    limitToList: true,
  });
  C.dateAllocationDate = widget.UI.DateBox("dateAllocationDate", {
    allowBlank: false,
  });

  C.lblSecuritisationType = widget.UI.Label("lblSecuritisationType", {});
  C.cboSecuritisationType = widget.UI.InformationListComboBox("cboSecuritisationType", {});

  C.lblMaxValue = widget.UI.Label("lblMaxValue", {});
  C.numMaxValue = widget.UI.NumberBox("numMaxValue", {
    blankIfZero: true,
    minValue: 0,
  });

  //   Parameters
  C.phParameters = widget.UI.ParametersHost("phParameters", {});

  //   Update Items
  C.divAllocationsSummary = $("#divAllocationsSummary");
  C.wbUpdateItemSummary = widget.UI.PreviewPane("wbUpdateItemSummary", {});

  //   Progress
  C.divProgress = $("#divProgress");

  // Grids
  C.gridCurrentProcesses = widget.UI.Grid("gridCurrentProcesses", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridCurrentProcesses_Action,
    onAfterRowActivate: gridCurrentProcesses_AfterRowActivate,
    onInitialiseRow: gridCurrentProcesses_InitialiseRow,
    onRowDrilldown: gridCurrentProcesses_RowDrilldown,
  });

  C.gridUpdateItems = widget.UI.Grid("gridUpdateItems", {
    allowCellSelect: false,
    allowMultiRowSelect: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,
    rowNumbering: true,

    onAction: gridUpdateItems_Action,
    onAfterRowActivate: gridUpdateItems_AfterRowActivate,
    onBeforeCellUpdate: gridUpdateItems_BeforeCellUpdate,
    onInitialiseRow: gridUpdateItems_InitialiseRow,
  });

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

  cmdHistory = $("#cmdHistory");
  cmdHistory.click(function() { Form_ExecuteAction("Recent"); });

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(AdvancedToggle);

  // Handle Notifications
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler);

  // Reset
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Record Load
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_BackgroundProcessStatus = null;
  mRecord_CurrentProcesses = null;
  mAccounts = null;
  mAccountSecuritisationAllocations = null;

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_CurrentProcesses = mRecord.CurrentProcesses;

      // Load Fields
      Fields_Load();

      // Notify if there are Current Processes
      var countCurrent = 0;
      var processIndex = -1;
      for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
        var item = mRecord_CurrentProcesses[i];

        // Process
        if (mRecord.ProcessId &amp;&amp; mRecord.ProcessId == item.ProcessId) {
          processIndex = i;
        }

        // Status
        switch (item.Status) {
          case "Pending":
          case "PendingCommit":
          case "InProgress":
          case "InProgressRefreshComplete":
          case "InProgressCancelRequested":
            countCurrent += 1;
            break;
        }
      }
      if (processIndex != -1) {
        ViewExistingProcess(processIndex);
      }
      else if (countCurrent != 0) {
        tabWizard_Move(-1);
        widget.UI.MsgBoxInfo("There are existing incomplete Securitisation Allocations that you have started and are not yet complete.\n\nYou can review these or use the 'Next &gt;' button to begin a new instance of Securitisation Allocations.", { heading: "Securitisation Allocations still Running", icon: "MonitorCategory"} );
      }
    },

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    var allocationTypeList = rblAllocationType_GetList();

    // Current Processes
    // NOTE: Bind here since this is the first page
    gridCurrentProcesses_Refresh();

    // General
    C.rblAllocationType.ListFromArray(allocationTypeList);
    for (var i = 0; i &lt; allocationTypeList.length; i++) {
      var item = allocationTypeList[i];

      if (item.enabled) {
        C.rblAllocationType.Value(item.value);
        break;
      }
    }
    C.dateAllocationDate.Value(mRecord.DefaultDate);
  }

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

  // Update Controls
  UpdateAllocationTypeControls();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

  // Lists
  C.cboFromBulkFunder.RefreshFromStandardRange("ExternalPartiesBulkFunders");
  C.cboToBulkFunder.RefreshFromStandardRange("ExternalPartiesBulkFunders");
  C.cboSecuritisationType.SetComboFromInformationList("SecuritisationTypes");

  // Controls
  if(mRecord) {
    if (mRecord.PermissionAllocateBuyback &amp;&amp; mRecord.PermissionAllocateSale &amp;&amp; mRecord.PermissionAllocateTransfer) {
      C.trPermissionWarning.hide();
    }
    else {
      C.trPermissionWarning.show();
    }

    // Initialise Advanced
    AdvancedInitialise();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize
  tabWizard_Resize();
}

// ======================================
// Updates Fields from Background Process
// ======================================
function Fields_Update_FromBackgroundProcess() {
  if (mAccountSecuritisationAllocations) {
    C.dateAllocationDate.Value(mAccountSecuritisationAllocations.Date);
    C.cboSecuritisationType.Text(mAccountSecuritisationAllocations.SecuritisationType);
    C.numMaxValue.Value(mAccountSecuritisationAllocations.Value);
    C.cboFromBulkFunder.Text(mAccountSecuritisationAllocations.FromExternalPartyId);
    C.cboToBulkFunder.Text(mAccountSecuritisationAllocations.ToExternalPartyId);

    // Allocation Type
    if (mAccountSecuritisationAllocations.IsSale) {
      C.rblAllocationType.Value("SALE");
    }
    else if (mAccountSecuritisationAllocations.IsBuyback) {
      C.rblAllocationType.Value("BUYBACK");
    }
    else {
      C.rblAllocationType.Value("TRANSFER");
    }

    // Update
    UpdateAllocationTypeControls();

    // Update Parameters
    if (mAccountSecuritisationAllocations.ScriptProperties) {
      C.phParameters.UpdateParameterValues(JSON.parse(mAccountSecuritisationAllocations.ScriptProperties));
    }
  }
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      default:
        break;
    }
  }

  // Always Refresh Current Processes, even when moving back
  if (newTab == 0) {
    if (!mRecord_CurrentProcesses) pageCurrentProcesses_Refresh();
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "CurrentProcesses":
      // Reset from recent flag
      mFromRecent = false;

      // Reset Objects
      mAccountDirectDebits = null;
      mLastRefreshParametersJson = null;
      mProcessId = null;
      break;

    case "UpdateItems":
      // Refesh Update Items
      pageUpdateItems_Refresh();
      break;

    default:
      break;
  }

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Parameters":
      if (C.rblAllocationType.Value() == "SALE") {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter additional Parameters for this Sale.");
        break;
      }
      else if (C.rblAllocationType.Value() == "TRANSFER") {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter additional Parameters for this Transfer.");
        break;
      }
      else if (C.rblAllocationType.Value() == "BUYBACK") {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Enter additional Parameters for this Buyback.");
        break;
      }
      break;

    case "UpdateItems":
      if (mAccountSecuritisationAllocations) {
        if (mAccountSecuritisationAllocations.IsSale) {
          frmMain.RefreshHeading("Securitise Accounts", "Select the Accounts to Securitise to '" + mAccountSecuritisationAllocations.ToExternalPartyId + "' on " + widget.FormatDate(mAccountSecuritisationAllocations.Date));
        }
        else if (mAccountSecuritisationAllocations.IsBuyback) {
          frmMain.RefreshHeading("Buyback Securitised Accounts", "Select the Securitised Accounts for this Buyback from '" + mAccountSecuritisationAllocations.FromExternalPartyId + "' on " + widget.FormatDate(mAccountSecuritisationAllocations.Date));
        }
        else {
          frmMain.RefreshHeading("Transfer Securitised Accounts", "Select the Securitised Accounts to Transfer from '" + mAccountSecuritisationAllocations.FromExternalPartyId + "' to '" + mAccountSecuritisationAllocations.ToExternalPartyId + "' on " + widget.FormatDate(mAccountSecuritisationAllocations.Date));
        }
      }
      else {
        frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), 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;
  }
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters(includeRefreshData) {
  var params = {
    securitisationType: C.cboSecuritisationType.Text(),
    date: C.dateAllocationDate.Value(),
    value: C.numMaxValue.Value(),
    processId: mProcessId,
  }

  // Custom Parameters
  switch (C.rblAllocationType.Value()) {
    case "SALE":
      params.toExternalPartyId = C.cboToBulkFunder.Text();
      if (mRecord.SaleParameters) {
        params.customParametersJson = JSON.stringify(C.phParameters.GetParameterValuesWithTypes());
      }
      break;

    case "TRANSFER":
      params.fromExternalPartyId = C.cboFromBulkFunder.Text();
      params.toExternalPartyId = C.cboToBulkFunder.Text();
      if (mRecord.TransferParameters) {
        params.customParametersJson = JSON.stringify(C.phParameters.GetParameterValuesWithTypes());
      }
      break;

    case "BUYBACK":
      params.fromExternalPartyId = C.cboFromBulkFunder.Text();
      if (mRecord.BuybackParameters) {
        params.customParametersJson = JSON.stringify(C.phParameters.GetParameterValuesWithTypes());
      }
      break;
  }

  // Selected Accounts
  if (includeRefreshData &amp;&amp; mAccountSecuritisationAllocations) {
    params.RefreshData = JSON.stringify(mAccountSecuritisationAllocations);
  }

  return params;
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      if (mComplete) {
        widget.Close();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;

    case "RECENT":
      // Recent
      tabWizard_Refresh(tabWizard.GetTabIndexById("CurrentProcesses"));
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  if (cmdFinish.text() == "Stop") {
    // Stop Process?
    widget.UI.MsgBoxConfirm("Are you sure you want to stop this process?\n\nNOTE: This may not take effect immediately.", {}, function () { Form_ExecuteAction_FinishStop(); }, null);
  }
  else {
    // Validate
    tabWizard_Validate(function () {
      // Confirmation Message
      var message = "";

      // Build Message
      message += "Are you sure you want to run Securitisation Allocations?";

      // Background Process
      message += "\n\nNOTE: This may take some time. You can close this form at any time and open it again to monitor progress.";

      // Confirm
      widget.UI.MsgBoxConfirm(message, {}, function () { Form_ExecuteAction_FinishPost(); }, null);
    });
  }
}

function Form_ExecuteAction_FinishPost() {
  // Running new process
  mMonitoringExisting = false;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Securitisation Allocations, please wait...");

  // Create Parameters
  var params = CreateFinishParameters(true);

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

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },

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

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

function Form_ExecuteAction_FinishStop() {
  // Continue
  widget.GetString("CancelBackgroundProcess", { processId: mProcessId },
    function (data) {
      widget.UI.MsgBoxInfo("The process has been requested to stop.");
    },

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

function Form_ExecuteAction_GetBackgroundProcessStatus() {
  var InProgressRefreshComplete = false;

  // Just in case!
  if (!mProcessId) return;

  // Continue
  widget.GetString("GetBackgroundProcessStatus", { processId: mProcessId, lastEventId: mLastEventId },
    function (data) {
      data = JSON.parse(data);

      // Update Status
      mRecord_BackgroundProcessStatus = data;

      // Refresh Progress
      pageProgress_Refresh();

      // Status
      var Status = mRecord_BackgroundProcessStatus.Status;

      // Override Status
      if (Status == "InProgressRefreshComplete" &amp;&amp; mFromRecent) {
        InProgressRefreshComplete = true;
        Status = "Complete";
      }
      if (Status == "InProgressRefreshComplete" &amp;&amp; mRecord.AutoCommit) {
        Status = "Pending";
      }

      // Handle Status
      switch(Status) {
        case "Cancelled":
          // Cancelled
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxInfo("Securitisation Allocations were successfully cancelled.");
          break;

        case "InProgressRefreshComplete":
          // Update Items
          mAccountSecuritisationAllocations = JSON.parse(mRecord_BackgroundProcessStatus.RefreshData);

          // Save parameters
          mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters(false));

          // Refresh Complete
          mRecord_BackgroundProcessStatus = null;

          // Set Tab
          tabWizard.SelectedTabId("UpdateItems");
          tabWizard_Refresh();
          break;

        case "Complete":
        case "CompleteWithErrors":
        case "CompleteWithWarnings":
          // Complete
          mComplete = true;
          mRecord_BackgroundProcessStatus = null;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          if (InProgressRefreshComplete) {
            widget.UI.MsgBoxInfo("Securitisation Allocations Refresh is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          else {
            widget.UI.MsgBoxInfo("Securitisation Allocations is " + widget.SplitWordsAtCapitals(Status, true, true) + ".");
          }
          break;

        case "Failed":
          // Failed
          mRecord_BackgroundProcessStatus = null;

          // Ensure if phase 2 has failed we are not prompted to Save and Close
          if (mAccountSecuritisationAllocations) mComplete = true;

          // Update Wizard Buttons
          tabWizard_UpdateButtons();

          // Notify
          widget.UI.MsgBoxAlert("Securitisation Allocations failed to complete.");
          break;

        default:
          // Continue Polling
          window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 2500);

          // Prevent finPOWER Connect Cloud UI signing the User out
          widget.NotifyBusy();
      }
    },

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

      // Abort Execution
      mRecord_BackgroundProcessStatus = null;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();
    }
  );
}

// ====================
// pageCurrentProcesses
// ====================
function pageCurrentProcesses_Refresh() {
  // Reset flags
  mComplete = false;

  // Block UI
  widget.UI.Block("Refreshing Recent Securitisation Allocations, please wait...");

  // Fetch
  widget.GetString("GetCurrentProcesses", {},
    function (data) {
      // Parse
      mRecord_CurrentProcesses = JSON.parse(data);

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

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

      // Refresh Grid
      gridCurrentProcesses_Refresh();
    },

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

      // Show Error
      widget.UI.MsgBoxAlert(error);
    }
  );
}

// ============
// pageProgress
// ============
function pageProgress_Refresh(clear) {
  if (clear) {    
    mLastProcessStatus = "";
    mLastEventId = "";
    mRecord_BackgroundProcessStatus = null;
    mRecord_CurrentProcesses = null;
  }
  else if (mRecord_BackgroundProcessStatus) {
    // Retrieve Last Process Status
    mLastProcessStatus = mRecord_BackgroundProcessStatus.StatusText;
  }

  // Build Progress
  mLastEventId = widget.UI.BuildBackgroundProcessProgress(C.divProgress, clear, mRecord_BackgroundProcessStatus);

  // Stop button valid?
  tabWizard_UpdateButtons()

  // Update Heading
  if (tabWizard.SelectedTabId() == "Progress") {
    if (mLastProcessStatus &amp;&amp; mLastProcessStatus.length != 0) {
      frmMain.RefreshHeading(mLastProcessStatus, "Processing progress.");
    }
    else {
      frmMain.RefreshHeading("Progress", "Processing progress.");
    }
  }
}

function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ===============
// pageUpdateItems
// ===============
function pageUpdateItems_Refresh() {
  // Refresh Grid
  if (mAccountSecuritisationAllocations) {
    gridUpdateItems_Refresh();
  }
}

// ====================
// gridCurrentProcesses
// ====================
function gridCurrentProcesses_Refresh() {
  // Add Columns
  if (C.gridCurrentProcesses.ColumnCount() == 0) {
    C.gridCurrentProcesses.AddColumnDrilldown();
    C.gridCurrentProcesses.AddColumnString("StatusText", { caption: "Status" });
    C.gridCurrentProcesses.AddColumnDateTime("CreatedDate", { caption: "Started" });

    // Actions
    C.gridCurrentProcesses.Actions().Define([{ actionId: "Cancel", caption:"Cancel", tooltipText:"Cancel the selected 'Refresh Complete' row", icon: "Trash" }]);
  }

  // Determine if Actions should be visible
  var found = false;
  for (var i = 0; i &lt; mRecord_CurrentProcesses.length; i++) {
    var item = mRecord_CurrentProcesses[i];

    if (item.Status == "InProgressRefreshComplete") {
      found = true;
      break;
    }
  }
  C.gridCurrentProcesses.Actions().SetVisible("Cancel", found);

  // Refresh
  C.gridCurrentProcesses.VirtualDataRefresh(mRecord_CurrentProcesses);

  // Activate no rows
  C.gridCurrentProcesses.ActiveDataRowIndex(-1);
}

function gridCurrentProcesses_Action(actionId) {
  var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];

  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      CancelRefreshCompleteBackgroundProcess(item.ProcessId, pageCurrentProcesses_Refresh);
      break;

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

function gridCurrentProcesses_AfterRowActivate(e) {
  // Refresh Buttons
  gridCurrentProcesses_RefreshButtons();
}

function gridCurrentProcesses_RefreshButtons() {
  if (C.gridCurrentProcesses.ActiveDataRowListIndex() == -1) {
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", false);
  }
  else {
    var item = mRecord_CurrentProcesses[C.gridCurrentProcesses.ActiveDataRowListIndex()];
    C.gridCurrentProcesses.Actions().SetEnabled("Cancel", item.Status == "InProgressRefreshComplete");
  }

  C.gridCurrentProcesses.RefreshButtons();
}

function gridCurrentProcesses_InitialiseRow(e) {
  var item = mRecord_CurrentProcesses[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Styles
  switch(item.Status) {
    case "Complete":
      e.row.cells.StatusText.colour = "green";
      break;

    case "CompleteWithErrors":
      e.row.cells.StatusText.colour = "darkred";
      break;

    case "CompleteWithWarnings":
      e.row.cells.StatusText.colour = "orange";
      break;

    case "Failed":
      e.row.cells.StatusText.colour = "red";
      break;

    case "Pending":
    case "InProgress":
    case "InProgressCancelRequested":
    case "InProgressRefreshComplete":
      e.row.bold = true;
      break;
  }
}

function gridCurrentProcesses_RowDrilldown(e) {
  ViewExistingProcess(e.row.listIndex);
}

// ===============
// gridUpdateItems
// ===============
function gridUpdateItems_Refresh() {
  var showCustomDisplayColumn1 = false;
  var showCustomDisplayColumn2 = false;
  var showCustomDisplayColumn3 = false;
  var showCustomDisplayColumn4 = false;
  var showWarnings = false;

  // Show / Hide Columns
  for (var i = 0; i &lt; mAccountSecuritisationAllocations.Items.length; i++) {
    var item = mAccountSecuritisationAllocations.Items[i];

    // Warnings
    if (item.InvalidMessageResolved) showWarnings = true;
    if (item.CustomDisplayColumn1) showCustomDisplayColumn1 = true;
    if (item.CustomDisplayColumn2) showCustomDisplayColumn2 = true;
    if (item.CustomDisplayColumn3) showCustomDisplayColumn3 = true;
    if (item.CustomDisplayColumn4) showCustomDisplayColumn4 = true;
  }

  // Add Columns
  C.gridUpdateItems.ClearColumns();
  C.gridUpdateItems.AddColumnIcon("Icon", { caption: "", visible: showWarnings });
  C.gridUpdateItems.AddColumnBoolean("Include", { caption: "Include", allowEdit: true });
  C.gridUpdateItems.AddColumnCode("AccountId", { caption: "Account" });
  C.gridUpdateItems.AddColumnString("AccountName", { caption: "Name" });
  C.gridUpdateItems.AddColumnString("AccountTypeId", { caption: "Type" });
  C.gridUpdateItems.AddColumnCurrency("BuybackValue", { caption: "Buyback Value", blankAsZero: false, visible: C.rblAllocationType.Value() != "SALE", backgroundColour: "rgba(255,0,0,0.05)" });
  C.gridUpdateItems.AddColumnCurrency("BuybackInterest", { caption: "Buyback Interest", visible: C.rblAllocationType.Value() != "SALE", backgroundColour: "rgba(255,0,0,0.05)" });
  C.gridUpdateItems.AddColumnCurrency("BuybackRebate", { caption: "Buyback Rebate", visible: C.rblAllocationType.Value() != "SALE", backgroundColour: "rgba(255,0,0,0.05)" });
  C.gridUpdateItems.AddColumnCurrency("DiscountedValue", { caption: "Discounted Value", visible: C.rblAllocationType.Value() != "BUYBACK" });
  C.gridUpdateItems.AddColumnCurrency("RepaymentsTotal", { caption: "Repayments Total", visible: C.rblAllocationType.Value() != "BUYBACK" });
  C.gridUpdateItems.AddColumnString("CustomDisplayColumn1", { caption: mRecord.CustomDisplayColumnHeading1, visible: showCustomDisplayColumn1, backgroundColour: "rgba(140,190,255,0.1)" });
  C.gridUpdateItems.AddColumnString("CustomDisplayColumn2", { caption: mRecord.CustomDisplayColumnHeading2, visible: showCustomDisplayColumn2, backgroundColour: "rgba(140,190,255,0.1)" });
  C.gridUpdateItems.AddColumnString("CustomDisplayColumn3", { caption: mRecord.CustomDisplayColumnHeading3, visible: showCustomDisplayColumn3, backgroundColour: "rgba(140,190,255,0.1)" });
  C.gridUpdateItems.AddColumnString("CustomDisplayColumn4", { caption: mRecord.CustomDisplayColumnHeading4, visible: showCustomDisplayColumn4, backgroundColour: "rgba(140,190,255,0.1)" });
  C.gridUpdateItems.AddColumnString("Notes", { caption: "Notes" });
  C.gridUpdateItems.AddColumnString("InvalidMessageResolved", { caption: "Error", visible: showWarnings });

  // Actions
  C.gridUpdateItems.Actions().Define([{ actionId: "SelectUp", tooltipText:"Select all rows above and including the current row", icon: "Select_Up" },
                                      { actionId: "SelectDown", tooltipText:"Select all rows below and including the current row", icon: "Select_Down" },
                                      { actionId: "SelectAll", tooltipText:"Select all valid rows", icon: "Select_All" },
                                      { actionId: "SelectNone", tooltipText:"Select no rows", icon: "Select_None" },
                                      { actionId: "SelectChecked", tooltipText: "Select all rows that are checked to include", icon: "Select_Checked" },
                                      { actionId: "SelectUnchecked", tooltipText: "Select all rows that are not checked to include", icon: "Select_Unchecked" },
                                      {},
                                      { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
                                      { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
                                     ]);

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mAccountSecuritisationAllocations.Items.GetCacheKey = function (index) {
    var item = mAccountSecuritisationAllocations.Items[index];
    return item.AccountPk + "." + mProcessId;
  };
  mAccountSecuritisationAllocations.Items.GetPreviewFetchParameters = function (index) {
    var item = mAccountSecuritisationAllocations.Items[index];
    var o = {};
    o.AccountId = item.AccountId;
    o.ProcessId = mProcessId;
    return o;
  };

  // Refresh
  C.gridUpdateItems.VirtualDataRefresh(mAccountSecuritisationAllocations.Items);

  // Select first row
  C.gridUpdateItems.ActivateFirstDataRow();

  // Update Totals
  divAllocationsSummary_Refresh();
}

function gridUpdateItems_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridUpdateItems.ActiveDataRowListIndex();
      var indexes = [];

      for(var i = 0; i &lt; mAccountSecuritisationAllocations.Items.length; i++) {
        if(mAccountSecuritisationAllocations.Items[i].CanCommit) {
          if(actionId.toUpperCase() == "SELECTUP" &amp;&amp; i &lt;= activeRowIndex) {
            indexes.push(i);
          }
          else if(actionId.toUpperCase() == "SELECTDOWN" &amp;&amp; i &gt;= activeRowIndex) {
            indexes.push(i);
          }
        }
      }
      break;

    case "SELECTALL":
      var indexes = [];
      for(var i = 0; i &lt; mAccountSecuritisationAllocations.Items.length; i++) {
        var item = mAccountSecuritisationAllocations.Items[i];
        if(item.CanCommit) indexes.push(i);
      }
      break;

    case "SELECTNONE":
      var indexes = [];
      break;

    case "SELECTCHECKED":
    case "SELECTUNCHECKED":
      var indexes = [];

      for(var i = 0; i &lt; mAccountSecuritisationAllocations.Items.length; i++) {
        var item = mAccountSecuritisationAllocations.Items[i];

        if(item.CanCommit) {
          if(actionId.toUpperCase() == "SELECTCHECKED" &amp;&amp; item.Status == "Active") {
            indexes.push(i);
          }
          else if(actionId.toUpperCase() == "SELECTUNCHECKED" &amp;&amp; item.Status != "Active") {
            indexes.push(i);
          }
        }
      }
      break;

    case "CHECK":
    case "UNCHECK":
      var selectedItems = C.gridUpdateItems.GetSelectedRowIndexes(true, true);

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mAccountSecuritisationAllocations.Items[selectedItems[i]];
        if (item.CanCommit) {
          if (actionId.toUpperCase() == "CHECK") {
            item.Status = "Active";
          }
          else {
            item.Status = "Exclude";
          }
        }
      }
      C.gridUpdateItems.VirtualDataRefresh(mAccountSecuritisationAllocations.Items, true, { retainSelectedRows: true });
      break;

    default:
      break;
  }

  // Set Indexes
  if(indexes) {
    C.gridUpdateItems.SetSelectedRowIndexes(indexes, true);
  }

  // Update Totals
  divAllocationsSummary_Refresh();
}

function gridUpdateItems_AfterRowActivate(e) {
  // Preview
  wbUpdateItemSummary_Preview();
}

function gridUpdateItems_BeforeCellUpdate(e) {
  var item = mAccountSecuritisationAllocations.Items[e.row.listIndex];

  switch(e.columnKey) {
    case "Include":
      if (e.newValue) {
        item.Status = "Active";
      }
      else {
        item.Status = "Exclude";
      }
      break;

    case "Notes":
      item.Notes = e.newValue;
      break;
  }

  // Update Totals
  divAllocationsSummary_Refresh();
}

function gridUpdateItems_InitialiseRow(e) {
  var item = mAccountSecuritisationAllocations.Items[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Invalid rows cannot be edited
  e.row.readOnly = !item.CanCommit;
  e.row.cells.Include.readOnly = !item.CanCommit;

  // Active / Exclude
  e.row.cells.Include.value = (item.Status == "Active");

  // Name
  e.row.cells.AccountName.small = true;

  // Icon
  if (item.InvalidMessageResolved) {
    e.row.cells.Icon.value = "Warning";
    e.row.cells.Icon.tooltipText = item.InvalidMessageResolved;
  }

  // Hyperlinks
  e.row.cells.AccountId.hyperlink = "app://FormShow?form=Accounts&amp;id=" + widget.UI.HtmlEncode(item.AccountId);
}

// ==========
// Tab Wizard
// ==========
function tabWizard_Cancel() {
  // Executing?
  if (mComplete) {
    tabWizard_Cancel_Post();
  }
  else if (mRecord_BackgroundProcessStatus &amp;&amp; !mMonitoringExisting) {
    widget.UI.MsgBoxConfirm("Securitisation Allocations are still running.\n\nThis will continue to run and you can re-open this form at any time to check on its status.\n\n\Close this form?", {}, tabWizard_Cancel_Post);
  }
  else if (mProcessId &amp;&amp; (tabWizard.SelectedTabId() == "UpdateItems" || mAccountSecuritisationAllocations)) {
    var list = [];
    list.push({ key: "CLOSE", caption: "Suspend and Close", icon: "Window_Close", details: "This will close the wizard but retain the list which can be reviewed later by re-opening this wizard." });
    list.push({ key: "CANCEL", caption: "Close and Cancel", icon: "Trash", details: "This will close the wizard and cancel this process. The list of Securitisation Allocations will not be retained." });

    var options = {
      closeOnEscape: true,
      title: "Close Securitisation Allocations",
      showClose: true
    };

    widget.UI.MsgBoxList("Select an option below to close", list, options, function(key) {
      switch (key) {
        case "CLOSE":
          tabWizard_Cancel_Save();
          break;

        case "CANCEL":
          CancelRefreshCompleteBackgroundProcess(mProcessId, tabWizard_Cancel_Post);
          break;
      }
    });
  }
  else {
    tabWizard_Cancel_Post();
  }
}

function tabWizard_Cancel_Save() {
  // Block UI
  widget.UI.Block("Saving, please wait...");

  // Parameters
  var params = CreateFinishParameters(true);

  // Update Refresh Data
  widget.GetString("UpdateRefreshData", params, tabWizard_Cancel_Post, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function tabWizard_Cancel_Post() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

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)) {
        case "Parameters":
          found = AllocationTypeHasParameters();
          break;

        case "UpdateItems":
          found = !mRecord.AutoCommit;
          break;

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "Parameters":
      C.phParameters.ResizeFromParent();
      break;

    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
  // Back and Next Buttons?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 1);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 2);

  // Finish Button
  if (tabWizard.SelectedTabId() == "UpdateItems") {
    cmdFinish.prop("disabled", false);
  }
  else if (mRecord.AutoCommit &amp;&amp; tabWizard.SelectedTabId() == "General" &amp;&amp; !AllocationTypeHasParameters()) {
    cmdFinish.prop("disabled", false);
    cmdNext.prop("disabled", true);
  }
  else if (mRecord.AutoCommit &amp;&amp; tabWizard.SelectedTabId() == "Parameters") {
    cmdFinish.prop("disabled", false);
    cmdNext.prop("disabled", true);
  }
  else {
    cmdFinish.prop("disabled", true);
  }

  // Page Exceptions
  if (mRecord_BackgroundProcessStatus) {
    cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
    cmdBack.prop("disabled", true);
    cmdHistory.prop("disabled", true);

    switch(mRecord_BackgroundProcessStatus.Status) {
      case "Pending":
      case "InProgress":
        cmdFinish.text("Stop");
        cmdFinish.prop("disabled", false);
        cmdFinish.addClass("negative");
        break;

      default:
        cmdFinish.text("Process");
        cmdFinish.prop("disabled", true);
        cmdFinish.removeClass("negative");
    }
  }
  else {
    cmdFinish.text("Process");
    cmdHistory.prop("disabled", false);
  }

  // Only show Advanced button on relevant pages
  if (mRecord) {
    cmdAdvanced.hide()
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (mRecord.PageGeneralHasAdvanced) cmdAdvanced.show();
        break;
    }
  }
  else {
    cmdAdvanced.hide();
  }

  // Never allow moving back from Progress page
  if (tabWizard.SelectedTabId() == "Progress") cmdBack.prop("disabled", true);

  // Recent Page exceptions
  if (mFromRecent) {
    cmdHistory.prop("disabled", false);

    cmdBack.prop("disabled", true);
    cmdNext.prop("disabled", true);
    cmdFinish.prop("disabled", true);
  }

  if (mComplete) {
    // Complete, i.e., Finish now closes the wizard
    cmdFinish.text("Close");
    cmdFinish.prop("disabled", false);

    // Allow viewing recent list
    cmdHistory.prop("disabled", false);
  }
}

function tabWizard_Validate(validCallback) {
  // Validate
  var Ok = tabWizard.Validate(true);

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // Same Funder
        if (C.rblAllocationType.Value() == "TRANSFER" &amp;&amp; !mRecord.PermissionTransferToSameBulkFunder &amp;&amp; C.cboFromBulkFunder.Text() == C.cboToBulkFunder.Text()) {
          Ok = false;
          widget.UI.MsgBoxAlert("'From' and 'To' Bulk Funders cannot be the same.");
        }

        // Refresh
        if (Ok &amp;&amp; !AllocationTypeHasParameters() &amp;&amp; !mRecord.AutoCommit) {
          RefreshSecuritisationAllocations();
        }
        break;

      case "Parameters":
        if (!mRecord.AutoCommit) {
          RefreshSecuritisationAllocations();
        }
        break;

      case "UpdateItems":
        var found = false;
        for (var i = 0; i &lt; mAccountSecuritisationAllocations.Items.length; i++) {
          var item = mAccountSecuritisationAllocations.Items[i];
          if (item.Status == "Active") {
            found = true;
            break;
          }
        }

        if (!found) {
          Ok = false;
          widget.UI.MsgBoxAlert("At least one item must be included to continue.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        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();
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks

  // General
  AdvancedInitialiseSection("SecuritisationType", mRecord.ShowSecuritisationType);
  AdvancedInitialiseSection("MaxValue", mRecord.ShowMaxValue);
}

function AdvancedInitialiseSection(id, option) {
  // Get elements
  var els=$("*[advancedId='" + id + "']");

  // Update
  switch(option.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      break;

    case "FALSE":
      // Never show
      els.hide();
      break;

    case "ADVANCED":
      // Only show in 'Advanced' mode
      els.addClass("advanced");
      break;
  }
}

function AdvancedToggle() {
  // Toggle Advanced
  mAdvancedVisible = !mAdvancedVisible;

  // Update Controls
  if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

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

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

// =================
// rblAllocationType
// =================
function rblAllocationType_GetList() {
  var list = [];

  list.push({ caption: "Sale", value: "SALE", enabled: mRecord.PermissionAllocateSale });
  list.push({ caption: "Transfer", value: "TRANSFER", enabled: mRecord.PermissionAllocateTransfer });
  list.push({ caption: "Buyback", value: "BUYBACK", enabled: mRecord.PermissionAllocateBuyback });

  return list;
}

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

  // Update Controls
  UpdateAllocationTypeControls();
}

// ========================
// Allocation Type Controls
// ========================
function UpdateAllocationTypeControls() {
  var parameterOptions = {
    alwaysCreateControls: true,
  };

  // Hide all
  C.lblSelectedlblAllocationType.VisibleRow(false);
  C.dateAllocationDate.VisibleRow(false);
  C.cboFromBulkFunder.VisibleRow(false);
  C.cboToBulkFunder.VisibleRow(false);

  C.phParameters.Visible(false);

  switch (C.rblAllocationType.Value()) {
    case "SALE":
      C.lblSelectedlblAllocationType.Text("Specify Sale Options");
      C.lblSelectedlblAllocationType.VisibleRow(true);
      C.dateAllocationDate.VisibleRow(true);
      C.cboToBulkFunder.VisibleRow(true);

      C.lblMaxValue.Text("Optionally, specify a maximum Sale value");

      if (mRecord.SaleParameters) {
        C.phParameters.Initialise(mRecord.SaleParameters, parameterOptions);
        C.phParameters.Visible(true);
      }
      break;

    case "TRANSFER":
      C.lblSelectedlblAllocationType.Text("Specify Transfer Options");
      C.lblSelectedlblAllocationType.VisibleRow(true);
      C.dateAllocationDate.VisibleRow(true);
      C.cboFromBulkFunder.VisibleRow(true);
      C.cboToBulkFunder.VisibleRow(true);

      C.lblMaxValue.Text("Optionally, specify a maximum Transfer value");

      if (mRecord.TransferParameters) {
        C.phParameters.Initialise(mRecord.TransferParameters, parameterOptions);
        C.phParameters.Visible(true);
      }
      break;

    case "BUYBACK":
      C.lblSelectedlblAllocationType.Text("Specify Buyback Options");
      C.lblSelectedlblAllocationType.VisibleRow(true);
      C.dateAllocationDate.VisibleRow(true);
      C.cboFromBulkFunder.VisibleRow(true);

      C.lblMaxValue.Text("Optionally, specify a maximum Buyback value");

      if (mRecord.BuybackParameters) {
        C.phParameters.Initialise(mRecord.BuybackParameters, parameterOptions);
        C.phParameters.Visible(true);
      }
      break;
  }

  // Update Buttons
  tabWizard_UpdateButtons();
}

// =======================================
// Selected Allocation Type has Parameters
// =======================================
function AllocationTypeHasParameters() {
  var hasParameters = false;

  switch (C.rblAllocationType.Value()) {
    case "SALE":
      if (mRecord.SaleParameters) {
        hasParameters = true;
      }
      break;

    case "TRANSFER":
      if (mRecord.TransferParameters) {
        hasParameters = true;
      }
      break;

    case "BUYBACK":
      if (mRecord.BuybackParameters) {
        hasParameters = true;
      }
      break;
  }

  return hasParameters;
}

// =======
// Refresh
// =======
function RefreshSecuritisationAllocations() {
  if (mLastRefreshParametersJson == JSON.stringify(CreateFinishParameters(false))) {
    // Parameters have not changed, so do not kick off another refresh
  }
  else {
    // Hide content
    frmMain.Visible(false);

    // Confirmation Message
    var message = "";

    // Build Message
    message += "&lt;p&gt;Click OK to build a list of Accounts to be Allocated.&lt;/p&gt;";

    // Background Process
    message += "&lt;p&gt;NOTE: This may take some time. You can close this form at any time and open it again to monitor progress.&lt;/p&gt;";

    // Process already in progress, warn this will be cancelled
    if (mAccountSecuritisationAllocations &amp;&amp; mProcessId) {
      message += "&lt;p style='color:red'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Accounts have already been refreshed. Continuing will cancel the existing process, and begin a new one.&lt;/p&gt;"
    }

    // Confirm
    widget.UI.MsgBoxConfirm(message, { heading: "Refresh Securitisation Allocations", messageIsHtml: true, icon: "Table|Refresh" },
      function () {
        if (mAccountSecuritisationAllocations &amp;&amp; mProcessId) {
          CancelRefreshCompleteBackgroundProcess(mProcessId, RefreshSecuritisationAllocations_Post, function() {
            // Move back a page
            tabWizard_Move(-1);

            // Show content
            frmMain.Visible(true);
          })
        }
        else {
          RefreshSecuritisationAllocations_Post();
        }
      },

      function() {
        // Move back a page
        tabWizard_Move(-1);

        // Show content
        frmMain.Visible(true);
      }
    );
  }
}

function RefreshSecuritisationAllocations_Post() {
  // Running new process
  mMonitoringExisting = false;
  mAccountSecuritisationAllocations = null;

  // Clear Progress Page
  pageProgress_Refresh(true);

  // Disable Form
  widget.UI.Block("Starting Securitisation Allocations Refresh, please wait...");

  // Create Parameters
  var params = CreateFinishParameters(true);

  // Refresh
  widget.GetString("Refresh", params,
    function (data) {
      // Show content
      frmMain.Visible(true);

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

      // Set Tab
      tabWizard.SelectedTabId("Progress");
      tabWizard_Refresh();

      // Save Status
      mProcessId = data.ProcessId;
      mRecord_BackgroundProcessStatus = data;

      // Update Wizard Buttons
      tabWizard_UpdateButtons();

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

      // Refresh Progress
      pageProgress_Refresh();

      // Poll Background Process
      window.setTimeout(Form_ExecuteAction_GetBackgroundProcessStatus, 3500);
    },

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

      // Show content
      frmMain.Visible(true);

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

// ==========================================
// Cancel Refresh Complete Background Process
// ==========================================
function CancelRefreshCompleteBackgroundProcess(processId, callback, cancelCallback) {
  widget.UI.MsgBoxConfirm("Are you sure you want to cancel this Background Process?", {},
  function() {
    // Block
    widget.UI.Block("Cancelling Background Process, please wait...");

    // Params
    var params = {
      processId: processId,
    }
    widget.GetString("CancelBackgroundProcess", params, function() { callback(); }, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();

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

// =====================
// divAllocationsSummary
// =====================
function divAllocationsSummary_Refresh() {
  var total = 0;
  var variance = 0;
  var html = "";

  // Only populate if 'Value' has been set
  if (mAccountSecuritisationAllocations.Value == 0) {
    C.divAllocationsSummary.hide();
  }
  else {
    // Total
    for (var i = 0; i &lt; mAccountSecuritisationAllocations.Items.length; i++) {
      var item = mAccountSecuritisationAllocations.Items[i];

      if (item.Status == "Active" &amp;&amp; item.CanCommit) {
        total += item.DiscountedValue;
      }
    }

    // Avoid rounding issues
    total = widget.RoundCurrency(total);
    variance = widget.RoundCurrency(mAccountSecuritisationAllocations.Value - total);

    var varianceClass = "";
    if (variance &lt; 0) {
      varianceClass = "variance-red";
    }
    else if (variance &gt; 0) {
      varianceClass = "variance-blue";
    }
    else {
      varianceClass = "variance-green";
    }

    // Message
    html = "&lt;div class='value-summary'&gt;";
    html += "&lt;div&gt;Value: &lt;b&gt;" + widget.FormatCurrency(mAccountSecuritisationAllocations.Value, true) + "&lt;/b&gt;&lt;/div&gt;";
    html += "&lt;div&gt;Selected: &lt;b&gt;" + widget.FormatCurrency(total, true) + "&lt;/b&gt;&lt;/div&gt;";
    html += "&lt;div&gt;Variance: &lt;b class='" + varianceClass + "'&gt;" + widget.FormatCurrency(variance, true) + "&lt;/b&gt;&lt;/div&gt;";
    html += "&lt;/div&gt;";
    C.divAllocationsSummary.html(html);

    // Show
    C.divAllocationsSummary.show();
  }
}

// ===================================
// View an existing Background Process
// ===================================
function ViewExistingProcess(itemIndex) {
  var item = mRecord_CurrentProcesses[itemIndex];
  var Ok = true;

  // Validate
  if (item.Status == "InProgressRefreshComplete" &amp;&amp; mRecord.AutoCommit) {
    Ok = false;
    widget.UI.MsgBoxInfo("Cannot resume a two-phase Process when this HTML Widget is configured to run in single-phase (Auto Commit) mode.");
  }

  if (Ok) {
    // Set Information from Process
    mProcessId = item.ProcessId;

    // Status-dependant
    switch (item.Status) {
      case "InProgressRefreshComplete":
        // Update Items
        mAccountSecuritisationAllocations = JSON.parse(item.RefreshData);

        // Update Controls
        Fields_Update_FromBackgroundProcess();

        // Save parameters
        mLastRefreshParametersJson = JSON.stringify(CreateFinishParameters(false));

        // Set Tab
        tabWizard.SelectedTabId("UpdateItems");
        tabWizard_Refresh();
        break;

      default:
        mFromRecent = true;
        mMonitoringExisting = true;

        // Switch to Progress Page
        tabWizard_Refresh(tabWizard.GetTabIndexById("Progress"));
        pageProgress_Refresh(true);

        // Start monitoring
        Form_ExecuteAction_GetBackgroundProcessStatus();
        break;
    }
  }
}

// ===================
// wbUpdateItemSummary
// ===================
function wbUpdateItemSummary_Preview() {
  C.wbUpdateItemSummary.PreviewFromGridCollection(C.gridUpdateItems, mAccountSecuritisationAllocations.Items, "GetUpdateItemPreview");
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "FORMCLOSE":
      // Closing Form
      tabWizard_Cancel();
      break;

    default:
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>yUFQGePfpEyTBAlyv0kLiw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</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="ShowMaxValue" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowSecuritisationType" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AutoCommit" type="Boolean">
            <BlankTip />
            <Caption>Auto Commit?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ProcessId" type="Text">
            <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>
            <MaxLength>50</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>