<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-08-09T02:16:48.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-08-09T02:10:21.8660000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2023-08-09T02:11:40.0860000</UpdatedUtcDate>
    <ScriptId>SPGEW</ScriptId>
    <Description>Secured Party Group Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_SecuredPartyGroupEdit
Option Explicit On
Option Strict On

' #################################################################
' Secured Party Group Edit form HTML Widget
'
' Version: 1.01 (09/08/2023)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  17/05/2023  ISS      J030255   Created
'    1.01  19/07/2023  ISS      J031166   Improved auto-fill prevention on SPG Id &amp; Password fields
'          09/08/2023  ISS      J031767   Password now reveals when focused
' #################################################################

' Constants
Private Const FORM_KEY As String = "SecuredPartyGroups"

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

' Standard Parameters
Private mSecuredPartyGroupId As String
Private mDuplicateRecordId As String
Private mPage As String
Private mReadOnly As Boolean

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 Standard Parameters
  With mStartupParameters
    mSecuredPartyGroupId = .GetString("SecuredPartyGroupId") ' Always use Startup Parameters since the Secured Party Group Id may be updated
  End With
  With mCombinedParameters
    mDuplicateRecordId = .GetString("DuplicateRecordId")
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

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

  ' Handle Events
  If Main Then
    Select Case eventId
      Case ""
        ' Main event, i.e., return initial HTML content (excluding html and body tags)
        returnValue = ScriptInfo.TemplateText      
        
      Case "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, returnValue)

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

      Case "SecurityRegisterGetSpgDetails"
        ' Security Register Get SPG Details
        Main = SecurityRegisterGetSpgDetails(returnValue)
        
      Case Else
        Main = False
        finBL.Error.ErrorBeginFormat("Unhandled event '{0}'", eventId)
    End Select
  End If

End Function

''' &lt;summary&gt;
'''  Load Secured Party Group.
''' &lt;/summary&gt;
Private Function GetSecuredPartyGroup(ByRef securedPartyGroup As finSecuredPartyGroup) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Secured Party Group
  If Success Then
    ' Create Secured Party Group
    securedPartyGroup = finBL.CreateSecuredPartyGroup()

    ' Load Secured Party Group
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = securedPartyGroup.Load(mDuplicateRecordId)
      If Success Then Success = securedPartyGroup.Duplicate()        
    ElseIf Len(mSecuredPartyGroupId) = 0 Then
      ' New record
    Else
      Success = securedPartyGroup.Load(mSecuredPartyGroupId)
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Initialisation Information required for this wizard.
''' &lt;/summary&gt;
Public Function GetInitialisationInfo(ByRef response As String) As Boolean

  Dim SecuredPartyGroup As finSecuredPartyGroup
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim SecuredPartyGroupServiceDetail As finSecuredPartyGroupServiceDetail

  ' Assume Success
  Success = True

  ' Validate
  If Not finBL.Settings.AddOns.SecurityRegister Then
    Success = False
    finBL.Error.ErrorBegin("You are not licenced for the Security Register addon.")
  ElseIf UCase(mPage) = "SERVICE" AndAlso finBL.CountryCode &lt;&gt; "AU" Then
    Success = False
    finBL.Error.ErrorBeginFormat("'Service' page is not supported for country '{0}'", finBL.CountryCode)
  End If

  ' Get Secured Party Group
  If Success Then
    Success = GetSecuredPartyGroup(SecuredPartyGroup)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Form
      .PageId = mPage
      If finBL.Database.IsReadOnly OrElse mReadOnly OrElse Not finBL.CurrentUser.Permissions.Allow("Admin.SecuredPartyGroups") Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .Pk = SecuredPartyGroup.Pk
      .Timestamp = SecuredPartyGroup.Timestamp

      ' Page Permissions (defined here since they are used below)
      .AllowPageGeneral = True
      .AllowPageService = (finBL.CountryCode = "AU")

      ' General
      .SecuredPartyGroupId = SecuredPartyGroup.SecuredPartyGroupId ' Always need to return Secured Party Group Id
      If .AllowPageGeneral Then
        .Active = SecuredPartyGroup.Active
        .Description = SecuredPartyGroup.Description
        
        .SpgId = SecuredPartyGroup.SpgId
        .Password = SecuredPartyGroup.Password
      End If

      ' Service
      If .AllowPageService Then
        For Each SecuredPartyGroupServiceDetail In SecuredPartyGroup.ServiceDetails
          .ServiceDetails.Add(New ServiceDetail(SecuredPartyGroupServiceDetail))          
        Next 
        
        ' Add Templates (for action)
        If Not finBL.Settings.AddOns.SecurityRegisterPPSR Then
          With .ServiceDetailsTemplate
            .Add(New ServiceDetail("Secured Party Details", True))
            .Add(New ServiceDetail("Organisation name", False))
            .Add(New ServiceDetail("Address for Service", True))
            .Add(New ServiceDetail("Contact name", False))
            .Add(New ServiceDetail("Email", False))
            .Add(New ServiceDetail("Fax", False))
            .Add(New ServiceDetail("Mailing address", False))
            .Add(New ServiceDetail("Physical address", False))
          End With          
        End If
      End If
      
      ' Other

      ' Permissions

      ' Lists

      ' Configuration
      .AddonsSecurityRegisterPPSR = finBL.Settings.AddOns.SecurityRegisterPPSR
      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .SecurityRegisterPPSRHasApi = finBL.Settings.AddOns.SecurityRegisterPPSRHasApi
      .Terminology_Password = finBL.SecurityRegister.Terminology(iseSecurityRegisterTerminology.SecuredPartyGroupPassword)
      .Terminology_Spg = finBL.SecurityRegister.Terminology(iseSecurityRegisterTerminology.SecuredPartyGroupId)
    End With
  End If

  ' Response
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(FormInitialisationInfo, response)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Save Secured Party Group.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted record (FormInitialisationInfo) object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim SecuredPartyGroup As finSecuredPartyGroup
  Dim ServiceDetail As ServiceDetail
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Secured Party Group
  If Success Then
    Success = GetSecuredPartyGroup(SecuredPartyGroup)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; SecuredPartyGroup.Timestamp Then
      Success = False
      finBL.Error.ErrorBegin("This record has been updated by another User.")
    End If
  End If

  ' Update and Save
  ' NOTE: Recheck Permissions in addition to the 'AllowPage' properties before updating to prevent spoofing
  If Success Then
    ' Begin Transaction
    If finBL.Database.TransactionBegin() Then
      ' Update Secured Party Group
      With SecuredPartyGroup
        ' General
        If Record.AllowPageGeneral Then
          .SecuredPartyGroupId = Record.SecuredPartyGroupId
          .Active = Record.Active
          .Description = Record.Description
          
          If finBL.Settings.AddOns.SecurityRegisterPPSRHasApi Then
            .SpgId = Record.SpgId
            .Password = Record.Password
          End If          
        End If
        
        ' Security
        If Record.AllowPageService Then
          ' Clear Service Details (entire collection will come from the UI)
          .ServiceDetails.Clear()
          
          For Each ServiceDetail In Record.ServiceDetails
            If Not .ServiceDetails.Add(ServiceDetail.Header, ServiceDetail.Caption, ServiceDetail.Value) Then
              Success = False
              Exit For
            End If           
          Next 
        End If
      End With

      ' Save
      If Success Then
        Success = SecuredPartyGroup.Save()
      End If

      ' Commit/ Rollback Transaction
      If Success Then
        finBL.Database.TransactionCommit()
      Else
        finBL.Database.TransactionRollback()
      End If
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Security Register SPG Details.
''' &lt;/summary&gt;
Private Function SecurityRegisterGetSpgDetails(ByRef returnValue As String) As Boolean
  
  Dim SecuredPartyGroup As finSecuredPartyGroup
  Dim SecuredPartyGroupServiceDetail As finSecuredPartyGroupServiceDetail
  Dim ServiceDetails As List(Of ServiceDetail)
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Load Secured Party Group and get details
  If GetSecuredPartyGroup(SecuredPartyGroup) Then
    Success = finBL.SecurityRegister.SecuredPartyGroupB2GGetServiceDetails(SecuredPartyGroup)
  Else 
    Success = False
  End If
  
  ' Get object to serialise
  If Success Then
    ServiceDetails = New List(Of ServiceDetail)
    
    For Each SecuredPartyGroupServiceDetail In SecuredPartyGroup.ServiceDetails
      ServiceDetails.Add(New ServiceDetail(SecuredPartyGroupServiceDetail))
    Next 
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(ServiceDetails, returnValue)
  End If
  
  Return Success
  
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 "General"
      ' General
  End Select

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardValidateResponse(Data, FailedMessage, FailedControlId), returnValue)
  End If

  Return Success

End Function


''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
''' &lt;remarks&gt;
'''  This object is also used to save the Employment.
''' &lt;/remarks&gt;
Public Class FormInitialisationInfo

  ' Form
  Public PageId As String
  Public [ReadOnly] As Boolean

  ' Record
  Public Pk As Integer
  Public Timestamp As Integer

  ' General
  Public SecuredPartyGroupId As String
  Public Active As Boolean
  Public Description As String

  Public SpgId As String
  Public Password As String

  ' Service
  Public ServiceDetails As New List(Of ServiceDetail)
  Public ServiceDetailsTemplate As New List(Of ServiceDetail)
  
  ' Permissions
  Public AllowPageGeneral As Boolean
  Public AllowPageService As Boolean

  ' Lists

  ' Configuration
  Public AddonsSecurityRegisterPPSR As Boolean
  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean
  Public SecurityRegisterPPSRHasApi As Boolean
  Public Terminology_Password As String
  Public Terminology_Spg As String
  
End Class



''' &lt;summary&gt;
'''  Service detail.
''' &lt;/summary&gt;
Public Class ServiceDetail

  Public Caption As String
  Public Header As Boolean
  Public Value As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(caption As String,
                 header As Boolean)
    
    Me.Caption = caption
    Me.Header = header
    Me.Value = ""
                 
  End Sub
  
  Public Sub New(securedPartyGroupServiceDetail As finSecuredPartyGroupServiceDetail)
    
    With securedPartyGroupServiceDetail
      Me.Caption = .Caption      
      Me.Header = .Header
      Me.Value = .Value
    End With
    
  End Sub
  
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</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to edit a Secured Party Group.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

 &lt;style type="text/less"&gt;
   div.colour-preview {
      display:inline-block;
      border:1px solid rgba(0,0,0,0.1);
      height:32px;
      line-height:32px;
      margin:4px 0 0 0;
      padding:0;
      text-align:center;
      width:100px;
   }
 &lt;/style&gt;


  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;General&lt;/li&gt;
        &lt;li tabId="Service"&gt;Service&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


  &lt;!-- Pages --&gt;
  &lt;div class="is-widget-form-body"&gt;
    &lt;!-- General --&gt;
    &lt;div id="pageGeneral"&gt;
      &lt;table class="is-form"&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="lblCodeAndName"&gt;Code and Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtSecuredPartyGroupId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtSecuredPartyGroupId"/&gt; &lt;input id="chkActive" type="checkbox"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDescription"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSPGInformation"&gt;Secured Party Group information&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtSPGId"&gt;SPG Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtSPGId" autocomplete="off" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPassword"&gt;Password:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtPassword" autocomplete="new-password" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSPGValidation"&gt;SPG Validation&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divSpgVerify" class="is-info-text info"&gt;This Secured Party Group can be validated by clicking the 'Verify' button on the read-only version of this SPG&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Service --&gt;
    &lt;div id="pageService"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&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="lblService"&gt;Secured Party Group details&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;        
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div style="position:relative; flex-grow:1; max-width:1024px; margin-left:8px"&gt;
          &lt;div id="gridService" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&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="cmdFinish" class="is-button ok"&gt;Save&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


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

var mOriginalJson;

// Controls
var C = {
  //   General
  lblCodeAndName: null,
  chkActive: null,
  txtSecuredPartyGroupId: null,
  txtDescription: null,
  
  lblSPGInformation: null,
  txtSPGId: null,
  txtPassword: null,
  
  lblSPGValidation: null,
  divSpgVerify: null,
  
  //   Service
  lblService: null,
  gridService: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

// Other

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

  // --------
  // Controls
  // --------
  //   General
  C.lblCodeAndName = widget.UI.Label("lblCodeAndName", {});
  C.txtSecuredPartyGroupId = widget.UI.TextBox("txtSecuredPartyGroupId", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.chkActive = widget.UI.CheckBox("chkActive", {
    caption: "Active?",
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 50,
  });

  C.lblSPGInformation = widget.UI.Label("lblSPGInformation", {});
  C.txtSPGId = widget.UI.TextBox("txtSPGId", {
    maxLength: 20,
  });
  C.txtPassword = widget.UI.TextBox("txtPassword", {
    maxLength: 20,
    password: true,
    passwordRevealOnFocus: true,
  });

  C.lblSPGValidation = widget.UI.Label("lblSPGValidation", {});
  C.divSpgVerify = $("#divSpgVerify");

  //   Service
  C.lblService = widget.UI.Label("lblService", {
    tooltipText: "This information is used when printing the Grantor Advice document.",
  });

  // Grids
  C.gridService = widget.UI.Grid("gridService", {
    allowAddRows: true,
    allowMultiRowSelect: true,    
    docked: true,    
    stickyHeader: true,

    onAction: gridService_Action,
    onAfterRowActivate: gridService_AfterRowActivate,
    onBeforeCellUpdate: gridService_BeforeCellUpdate,
    onInitialiseRow: gridService_InitialiseRow,
    onRowAdd: gridService_RowAdd,
    onSelectedRowsChanged: gridService_SelectedRowsChanged,
  });  

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

  // Create Tabs
  tabDetails = new widget.UI.Tabs("tabDetails", {
    style: "normal",
    onSelectedTabChanged: tabDetails_Refresh,
  });

  // Handle resize
  $(window).resize(Form_Resize);

  // Disable Close Button (this causes the 'FormClose' notification action to be invoked instead)
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler)

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabDetails_Cancel);
  cmdFinish.click(Form_ExecuteAction_Finish);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    Record_Load_Done,

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

function Record_Load_Done(data) {
  // Initialise
  mRecord = JSON.parse(data);

  // Set Tab
  if (mRecord &amp;&amp; mRecord.PageId) {
    tabDetails.SelectedTabId(mRecord.PageId);

    // Hide other Pages
    if (mRecord.HideOtherPages) {
      tabDetails.ShowSingleTab(mRecord.PageId);
    }
  }
  else {
    tabDetails.SelectedTabId("General");
  }

  // Page Permissions
  if (!mRecord.AllowPageGeneral) tabDetails.TabVisible("General", false);
  if (!mRecord.AllowPageService) tabDetails.TabVisible("Service", false);

  // Load Fields
  Fields_Load();

  // Save Fields (so UserData is in correct format for mOriginalJson)
  Fields_Save();

  // Save original JSON for Form_IsDirty
  mOriginalJson = JSON.stringify(mRecord);
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.txtSecuredPartyGroupId.Text(mRecord.SecuredPartyGroupId);
    C.chkActive.Value(mRecord.Active);
    C.txtDescription.Text(mRecord.Description);
    
    C.txtSPGId.Text(mRecord.SpgId);
    C.txtPassword.Text(mRecord.Password);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabDetails_Refresh();
  tabDetails_Resize();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.SecuredPartyGroupId = C.txtSecuredPartyGroupId.Text();
  mRecord.Active = C.chkActive.Value();
  mRecord.Description = C.txtDescription.Text();
  
  mRecord.SpgId = C.txtSPGId.Text();
  mRecord.Password = C.txtPassword.Text();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.SecuredPartyGroupId) {
      widget.SetHeading("Secured Party Group (" + mRecord.SecuredPartyGroupId + ")");
    }
    else {
      widget.SetHeading("New Secured Party Group");
      C.divSpgVerify.html("This Secured Party Group can be validated by clicking the 'Verify' button on the read-only version of this SPG once saved");
    }
  }

  // Information Lists
  if (mRecord) {
  }

  // Lists
  if (mRecord) {
    // General
  }

  // Controls
  if (mRecord) {
    if (mRecord.SecurityRegisterPPSRHasApi) {
      C.txtSPGId.Caption(mRecord.Terminology_Spg + ":");
      C.txtPassword.Caption(mRecord.Terminology_Password + ":");
    }
    else {
      C.lblSPGInformation.VisibleRow(false);
      C.txtSPGId.VisibleRow(false);
      C.txtPassword.VisibleRow(false);
      C.lblSPGValidation.VisibleRow(false);
      C.divSpgVerify.hide();
    }
  }

  // Pages
  if (mRecord) {
    // NOTE: Even though many pages are updated in tabDetails_Refresh, we must update them here to ensure controls are hidden since this is not a wizard and all pages are validated on "Finish"
    pageGeneral_Refresh();
    pageService_Refresh();
  }

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdFinish.prop("disabled", true);
    frmMain.FormReadOnly(C, true);
  }

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

  // Resize Tab
  tabDetails_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile Optimisations
  var el = $(".mobile-indent th.indent1, .mobile-indent th.no-indent1");
  if (window.innerWidth &lt; 500) {
    el.addClass("no-indent1").removeClass("indent1");
  }
  else {
    el.addClass("indent1").removeClass("no-indent1");
  }

  // General

  // Tab
  tabDetails_Resize();
}

// ========
// Is Dirty
// ========
function Form_IsDirty() {
  if (mRecord) {
    // Save Fields
    Fields_Save();

    // Is Dirty?
    return mOriginalJson != JSON.stringify(mRecord);
  }
  else {
    return false;
  }
}

// ==============
// Wizard Buttons
// ==============
function tabDetails_Cancel() {
  if (Form_IsDirty()) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", { heading: "Close Form" }, tabDetails_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabDetails_Cancel_Finalise();
  }
}

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

// ==========
// Resize Tab
// ==========
function tabDetails_Resize() {
  switch (tabDetails.SelectedTabId()) {
    case "General":
      // General
      C.txtDescription.WidthResizeFromParent();
      break;
  }
}

// ===========
// Refresh Tab
// ===========
function tabDetails_Refresh() {
   // Load details
  switch (tabDetails.SelectedTabId()) {
    case "General":
      pageGeneral_Refresh();
      break;

    case "Service":
      pageService_Refresh();
      break;

    default:
      break;
  }

  // Resize
  tabDetails_Resize();

  // Focus
  switch (tabDetails.SelectedTabId()) {
    default:
      tabDetails.FocusFirst();
      break;
  }
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch(actionId) {
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Assume Success
  var Ok = true;

  // Validate
  Ok = tabDetails.Validate();

  // Prompt
  if (Ok) {
    if (mRecord.PromptOnSave) {
      // Confirm
      widget.UI.MsgBoxConfirm("Are you sure you want to save this record?",
                              { heading: "Save" },
                              Form_ExecuteAction_FinishPost);

    }
    else {
      // Save without prompting
      Form_ExecuteAction_FinishPost();
    }
  }
}

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

  // Create Parameters
  // NOTE: We will simply update mRecord, clone this and send back (less some information)
  Fields_Save();
  var params = JSON.parse(JSON.stringify(mRecord));
  //params.GendersList = null;

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      // Close Form
      widget.Close();

      // Refresh Parent (to show updated details)
      // NOTE: Pass in Record Id just in case this has changed
      widget.RefreshParent(C.txtSecuredPartyGroupId.Text());
    },

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

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

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  if (!mRecord) return;
}

// ===========
// pageService
// ===========
function pageService_Refresh() {
  if (!mRecord) return;
  
  // Refresh Grid
  gridService_Refresh();
}

// ===========
// gridService
// ===========
function gridService_Refresh() {
  var showWarning = false;

  // Add Columns
  C.gridService.ClearColumns();
  C.gridService.AddColumnBoolean("Header", { caption: "Header", allowEdit: true });
  C.gridService.AddColumnString("Caption", { caption: "Caption", allowEdit: true });
  C.gridService.AddColumnString("Value", { caption: "Value", allowEdit: true });

  // Actions
  var actions = [];    
  if (!mRecord.ReadOnly) {
    if (mRecord.AddonsSecurityRegisterPPSR) {
      actions.push({ actionId: "SPGDetails", caption: "SPG Details", tooltipText:"Download SPG details from the PPSR", icon: "Logo_PPSR_AU" });
    }
    else {
      actions.push({ actionId: "InsertTemplate", tooltipText:"Insert Secured Party Group template", icon: "Script_Standard" });
    }
    actions.push({});
    actions.push({ actionId: "Delete", tooltipText:"Delete selected row(s)", icon: "Grid_Row_Delete" });
    actions.push({});
    actions.push({ actionId: "RowMoveUp", tooltipText:"Move current row up", icon: "Grid_Row_MoveUp" });
    actions.push({ actionId: "RowMoveDown", tooltipText:"Move current row down", icon: "Grid_Row_MoveDown" });
  }  
  C.gridService.Actions().Define(actions);

  // Refresh
  C.gridService.VirtualDataRefresh(mRecord.ServiceDetails);
}

function gridService_InitialiseRow(e) {
  var item = mRecord.ServiceDetails[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Styles
  e.row.cells.Caption.bold = item.Header;
}

function gridService_Action(actionId) {
  switch (actionId.toUpperCase()) {    
    case "DELETE":      
      C.gridService.RemoveSelectedRowsAndCollectionItems();
      break;
      
    case "INSERTTEMPLATE":
      gridService_Action_InsertTemplate();
      break;  
      
    case "ROWMOVEUP":
      C.gridService.RowMoveUp();
      break;
    
    case "ROWMOVEDOWN":
      C.gridService.RowMoveDown();
      break;
      
    case "SPGDETAILS":
      gridService_Action_SpgDetails();
      break;
      
    default:
      break;
  }
}

function gridService_Action_InsertTemplate() {
  for (var i = 0; i &lt; mRecord.ServiceDetailsTemplate.length; i++) {
    var item = mRecord.ServiceDetailsTemplate[i];
    
    mRecord.ServiceDetails.push(item);
  }
  
  // Refresh Grid
  C.gridService.VirtualDataRefresh(mRecord.ServiceDetails);
}

function gridService_Action_SpgDetails() {
  // Block UI
  widget.UI.Block("Getting SPG details, please wait...");
  
  // Get SPG details
  widget.GetString("SecurityRegisterGetSpgDetails", {}, 
    function(data) {
      // Update
      mRecord.ServiceDetails = JSON.parse(data);
      
      // Refresh Grid
      C.gridService.VirtualDataRefresh(mRecord.ServiceDetails);
      
      // Unblock
      widget.UI.Unblock();
    }, 
  
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();
      
      // Error
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}

function gridService_AfterRowActivate(e) {
  // Refresh Buttons
  gridService_RefreshButtons();
}

function gridService_RowAdd(e) {
  // Create item
  var item = {
    Caption: "",
    Header: false,
    Value: "",
  };

  // Add
  mRecord.ServiceDetails.push(item);
}

function gridService_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridService_RefreshButtons();
}

function gridService_RefreshButtons() {
  var rows = C.gridService.GetSelectedRowIndexes(true, false);

  C.gridService.Actions().SetEnabled("SPGDetails", mRecord.SecuredPartyGroupId);
  C.gridService.Actions().SetEnabled("InsertTemplate", mRecord.SecuredPartyGroupId);

  C.gridService.Actions().SetEnabled("Delete", rows.length &gt; 0);
  C.gridService.Actions().SetEnabled("RowMoveUp", rows.length == 1);
  C.gridService.Actions().SetEnabled("RowMoveDown", rows.length == 1);

  C.gridService.RefreshButtons();
}

function gridService_BeforeCellUpdate(e) {
  var item = mRecord.ServiceDetails[e.row.listIndex];
  
  switch(e.columnKey) {
    case "Header":
      item.Header = e.newValue;
      break;
      
    case "Caption":
      item.Caption = e.newValue;
      break;
    
    case "Value":
      item.Value = e.newValue;
      break;
  }
  
  // Refresh row to update styles
  e.refreshRow = true;
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabDetails_Cancel();
      break;
   }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>hQUaDgext0KhUc6Yr0Li1w</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Secured Party Group</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>
    <Icon>SecuredPartyGroup</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="HideOtherPages" type="Boolean">
            <BlankTip />
            <Caption>Hide pages other than the one being edited?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Configuration options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="SecuredPartyGroupId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>SecuredPartyGroups</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="DuplicateRecordId" 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.SecuredPartyGroups</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="Page" 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>General,Service</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ReadOnly" type="Boolean">
            <BlankTip />
            <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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>