<?xml version="1.0" encoding="utf-8"?><finScript version="1.00" exportedUtcDate="2021-12-07T01:39:38.0000000"><CreatedUserId>Admin</CreatedUserId><CreatedUtcDate>2020-07-21T01:31:44.5630000</CreatedUtcDate><UpdatedUserId>Admin</UpdatedUserId><UpdatedUtcDate>2021-11-28T21:40:31.1510000</UpdatedUtcDate><ScriptId>CTE</ScriptId><Description>Client Type Edit</Description><ScriptType>HtmlWidget</ScriptType><Active>true</Active><AllowUI>false</AllowUI><Category /><Code>' HtmlWidget_ClientTypeEdit
Option Explicit On
Option Strict On

' #################################################################
' Client Type Edit form HTML Widget
'
' Version: 1.03 (29/11/2021)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.03  29/11/2021  ISS      J027891   Prompt on close
' #################################################################


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

' Standard Parameters
Private mClientTypeId 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
    mClientTypeId = .GetString("ClientTypeId") ' Always use Startup Parameters since the Client Type Id may be updated
  End With
  With mCombinedParameters
    mDuplicateRecordId = .GetString("DuplicateRecordId")
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

  ' Validate
  If finBL.CloudConnectFunctions.CloudConnectSettings.ExcludeAdministrationTools Then
    Main = False
    finBL.Error.ErrorBegin("Administration tools are excluded from being accessed from finPOWER Connect Cloud.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("Admin.ClientTypes") Then
    Main = False
    finBL.Error.ErrorBegin("You do not have permission to add or update Client Types.")
  End If

  ' 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 Else
        Main = False
        finBL.Error.ErrorBeginFormat("Unhandled event '{0}'", eventId)
    End Select
  End If

End Function

''' &lt;summary&gt;
'''  Load Client Type.
''' &lt;/summary&gt;
Private Function GetClientType(ByRef clientType As finClientType) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Client Type
  If Success Then
    ' Create Client Type
    clientType = finBL.CreateClientType()

    ' Load Client Type
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = clientType.Load(mDuplicateRecordId)
      If Success Then clientType.Duplicate()
    ElseIf Len(mClientTypeId) = 0 Then
      ' New record
    Else
      Success = clientType.Load(mClientTypeId)
    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 ClientType As finClientType
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim TaxCategory As finClientTypeTaxCategory

  ' Assume Success
  Success = True

  ' Validate
  If Not finBL.CurrentUser.Permissions.Allow("Admin.ClientTypes") OrElse Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.ClientTypes") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to edit Client Types.")
  End If

  ' Get Client Type
  If Success Then
    Success = GetClientType(ClientType)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Form
      .PageId = mPage
      If finBL.Database.IsReadOnly OrElse mReadOnly Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .Pk = ClientType.Pk
      .Timestamp = ClientType.Timestamp

      ' Page Permissions (defined here since they are used below)
      .AllowPageGeneral = True
      .AllowPageTaxCategories = True

      ' General
      .ClientTypeId = ClientType.ClientTypeId ' Always need to return Client Type Id
      If .AllowPageGeneral Then
        .Active = ClientType.Active
        .Description = ClientType.Description

        .ClientClassDescription = ClientType.ClientClassDescription

        .UseIndustryCode = ClientType.UseIndustryCode
        .UseCreditBureauMonitoring = ClientType.UseCreditBureauMonitoring
      End If

      ' Tax Categories
      If .AllowPageTaxCategories Then
        .DefaultTaxCategoryId = ClientType.DefaultTaxCategoryId

        .TaxCategories = New List(Of ClientTypeTaxCategory)
        For Each TaxCategory In ClientType.TaxCategories
          .TaxCategories.Add(New ClientTypeTaxCategory(finBL, TaxCategory))
        Next
      End If

      ' Other

      ' Permissions

      ' Lists
      .ClientClasses = finBL.ClientClasses.GetDescriptionsList().ToCsvString()

      ' Configuration
      .AddOnCreditBureauMonitor = finBL.Settings.AddOns.CreditBureauMonitor

      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
    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 Client Type.
''' &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 ClientTypeTaxCategory As ClientTypeTaxCategory
  Dim ClientType As finClientType
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  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 Client Type
  If Success Then
    Success = GetClientType(ClientType)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; ClientType.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 Client Type
      With ClientType
        ' General
        If Record.AllowPageGeneral Then
          .ClientTypeId = Record.ClientTypeId
          .Active = Record.Active
          .Description = Record.Description

          .ClientClassDescription = Record.ClientClassDescription

          .UseIndustryCode = Record.UseIndustryCode
          .UseCreditBureauMonitoring = Record.UseCreditBureauMonitoring
        End If

        ' Tax Categories
        If Record.AllowPageTaxCategories Then
          .DefaultTaxCategoryId = Record.DefaultTaxCategoryId

          For Each ClientTypeTaxCategory In Record.TaxCategories
            If .TaxCategories.Exists(ClientTypeTaxCategory.TaxCategoryId) Then
              .TaxCategories(ClientTypeTaxCategory.TaxCategoryId).Available = ClientTypeTaxCategory.Available
            End If
          Next

          ' Ensure Default Tax Category is available
          If Len(.DefaultTaxCategoryId) &lt;&gt; 0 Then
            .TaxCategories(.DefaultTaxCategoryId).Available = True
          End If
        End If
      End With

      ' Save
      If Success Then
        Success = ClientType.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;
'''  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 ClientTypeId As String
  Public Active As Boolean
  Public Description As String

  Public ClientClassDescription As String

  Public UseIndustryCode As Boolean
  Public UseCreditBureauMonitoring As Boolean

  ' Tax Categories
  Public DefaultTaxCategoryId As String
  Public TaxCategories As List(Of ClientTypeTaxCategory)

  ' Permissions
  Public AllowPageGeneral As Boolean
  Public AllowPageTaxCategories As Boolean

  ' Lists
  Public ClientClasses As String

  ' Configuration
  Public AddOnCreditBureauMonitor As Boolean

  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean

End Class


''' &lt;summary&gt;
'''  Client Type Tax Category.
''' &lt;/summary&gt;
Public Class ClientTypeTaxCategory

  Public Active As Boolean
  Public Available As Boolean
  Public TaxCategoryId As String
  Public TaxCategoryDescription As String

  Public Sub New()
  End Sub

  Public Sub New(finBL As ISfinSupport,
                 clientTypeTaxCategory As finClientTypeTaxCategory)

    With clientTypeTaxCategory
      Me.Active = .Active
      Me.Available = .Available
      Me.TaxCategoryId = .TaxCategoryId
      Me.TaxCategoryDescription = finBL.TaxCategories(.TaxCategoryId).Description
    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 Client Type.</Notes><PermissionKeyExecute /><RunWithoutPrompts>false</RunWithoutPrompts><TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;!-- 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="TaxCategories"&gt;Tax Categories&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="txtClientTypeId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtClientTypeId"/&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&gt;Class of Client&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboClientClass"&gt;Class:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboClientClass"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label&gt;Other options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUseIndustryCode" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUseCreditBureauMonitoring" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Tax Categories --&gt;
    &lt;div id="pageTaxCategories"&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&gt;Default Tax Category&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboDefaultTaxCategory"&gt;Tax Category:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboDefaultTaxCategory"/&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label&gt;Available Tax Categories&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="gridTaxCategories" 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 mRecord_TaxCategories;

var mOriginalJson;

// Controls
var C = {
  //   General
  lblCodeAndName: null,
  chkActive: null,
  txtClientTypeId: null,
  txtDescription: null,

  cboClientClass: null,

  chkUseIndustryCode: null,
  chkUseCreditBureauMonitoring: null,

  //   Tax Categories
  cboDefaultTaxCategory: null,
  gridTaxCategories: 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.txtClientTypeId = widget.UI.TextBox("txtClientTypeId", {
    allowBlank: false,
    maxLength: 5,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.chkActive = widget.UI.CheckBox("chkActive", {
    caption: "Active?",
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 50,
  });

  C.cboClientClass = widget.UI.ComboBox("cboClientClass", {
    allowBlank: false,
    limitToList: true,
    maxLength: 40,
    width: "24em",
  });

  C.chkUseIndustryCode = widget.UI.CheckBox("chkUseIndustryCode", {
    caption: "Use Industry Code?",
  });
  C.chkUseCreditBureauMonitoring = widget.UI.CheckBox("chkUseCreditBureauMonitoring", {
    caption: "Use Credit Bureau Monitoring?",
  });

  //   Tax Categories
  C.cboDefaultTaxCategory = widget.UI.DBCombo("cboDefaultTaxCategory", {
    allowBlank: false,
    maxLength: 5,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });

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

    onBeforeCellUpdate: gridTaxCategories_BeforeCellUpdate,
    onInitialiseRow: gridTaxCategories_InitialiseRow,
  });

  // 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);
  mRecord_TaxCategories = mRecord.TaxCategories;

  // 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.AllowPageTaxCategories) tabDetails.TabVisible("TaxCategories", 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.txtClientTypeId.Text(mRecord.ClientTypeId);
    C.chkActive.Value(mRecord.Active);
    C.txtDescription.Text(mRecord.Description);

    C.cboClientClass.Text(mRecord.ClientClassDescription);

    C.chkUseIndustryCode.Value(mRecord.UseIndustryCode);
    C.chkUseCreditBureauMonitoring.Value(mRecord.UseCreditBureauMonitoring);

    // Tax Categories
    C.cboDefaultTaxCategory.Text(mRecord.DefaultTaxCategoryId);
    if (mRecord_TaxCategories) gridTaxCategories_Refresh();
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

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

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.ClientTypeId = C.txtClientTypeId.Text();
  mRecord.Active = C.chkActive.Value();
  mRecord.Description = C.txtDescription.Text();

  mRecord.ClientClassDescription = C.cboClientClass.Text();

  mRecord.UseIndustryCode = C.chkUseIndustryCode.Value();
  mRecord.UseCreditBureauMonitoring = C.chkUseCreditBureauMonitoring.Value();

  // Tax Categories
  mRecord.DefaultTaxCategoryId = C.cboDefaultTaxCategory.Text();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.ClientTypeId) {
      widget.SetHeading("Client Type (" + mRecord.ClientTypeId + ")");
    }
    else {
      widget.SetHeading("New Client Type");
    }
  }

  // Lists
  if (mRecord) {
    // General
    C.cboClientClass.ListFromCsvString(mRecord.ClientClasses);

    // Tax Categories
    C.cboDefaultTaxCategory.RefreshFromStandardRange("TaxCategories");
  }

  // Controls
  if (mRecord) {
    C.chkUseCreditBureauMonitoring.Visible(mRecord.AddOnCreditBureauMonitor);
  }

  // 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();
    pageTaxCategories_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;

    case "TaxCategories":
      // Tax Categories
      break;
  }
}

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

    case "TaxCategories":
      pageTaxCategories_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.txtClientTypeId.Text());
    },

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

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

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

  // Controls
}

// =================
// pageTaxCategories
// =================
function pageTaxCategories_Refresh() {
  if (!mRecord) return;

  // Controls
}

// =================
// gridTaxCategories
// =================
function gridTaxCategories_Refresh() {
  // Add Columns
  C.gridTaxCategories.ClearColumns();
  C.gridTaxCategories.AddColumnBoolean("Available", { caption: "Available", allowEdit: true });
  C.gridTaxCategories.AddColumnString("TaxCategoryId", { caption: "Category", width: widget.UI.FIELD_WIDTH_CODE_5 });
  C.gridTaxCategories.AddColumnString("TaxCategoryDescription", { caption: "Description" });

  // Refresh
  C.gridTaxCategories.VirtualDataRefresh(mRecord_TaxCategories);

  // Activate First Row
  C.gridTaxCategories.ActivateFirstDataRow();
}

function gridTaxCategories_InitialiseRow(e) {
  var item = mRecord_TaxCategories[e.row.listIndex];

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

  // Colour cells to show read-only state
  e.row.cells.TaxCategoryId.readOnly = true;
  e.row.cells.TaxCategoryDescription.readOnly = true;
}

function gridTaxCategories_BeforeCellUpdate(e) {
  var item = mRecord_TaxCategories[e.row.listIndex];

  switch(e.columnKey) {
    case "Available":
      item.Available = 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>BKuvQRpGqkSwhR10dPjYDg</UniqueId><AllowRefresh>true</AllowRefresh><Caption>Client Type</Caption><HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight><HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth><HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling><HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2><HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget><HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery><HtmlWidgetResourceJQueryVersion /><Icon /><JavaScriptDebugger>None</JavaScriptDebugger><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="ClientTypeId" 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>ClientTypes</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.ClientTypes</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,TaxCategories</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>