<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-05-15T02:58:42.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-04-29T03:58:44.1840000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-05-15T02:57:01.0520000</UpdatedUtcDate>
    <ScriptId>HWCC</ScriptId>
    <Description>Combine Clients</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category>Client Utilities</Category>
    <Code>' HtmlWidget_ClientCombine
Option Explicit On
Option Strict On

' #################################################################
' Combine Clients wizard
'
' Version: 1.03 (15/05/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  07/10/2021  ISS      J025297   Created
'    1.01  14/12/2021  ISS      J027900   Spelling mistake in "Permission"
'    1.02  02/05/2024  ISS      J033379   Added new columns, Highlighting matching values
'    1.03  03/05/2024  ISS      J033379   Adjusted how columns are hidden
'          15/05/2024  ISS      J033470   Removed unused variable
' #################################################################

' Constants
Private Const FORM_KEY As String = "ClientCombine"

' Common Parameters
Private mClientId As String

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

Public Function Main(eventId As String,
                     parametersJson As String,
                     startUpParametersJson As String,
                     hostingContext As isefinHtmlWidgetHostingContext,
                     requestInfo As finScriptRequestInfo,
                     ByRef returnValue As String) As Boolean

  ' Assume Success
  Main = True

  ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

  ' Get Combined Parameters (Startup Parameters updated with event Parameters)
  mCombinedParameters = mStartupParameters.Clone()
  mCombinedParameters.UpdateFromKeyValueList(mParameters, True)

  ' Get Common Parameters
  With mCombinedParameters
    mClientId = .GetString("ClientId")
  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 "Finish"
      ' Finish wizard
      Main = Finish(parametersJson, requestInfo, returnValue)

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

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

    Case Else
      finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
      Main = False
  End Select

End Function

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

  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise

  ' Validate
  If finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.ClientCombine") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to combine Clients.")
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Record
      .ClientId = mClientId

      ' Column Captions
      .ColumnCaptionBusinessNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BusinessNumber)
      .ColumnCaptionOrganisationNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.CompanyNumber)
      .ColumnCaptionTaxNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberIndividual)
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Create a finClientMerge object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateClientMerge(clientId As String,
                                   parameters As WizardFinishParameters,
                                   ByRef clientMerge As finClientMerge) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  clientMerge = finBL.CreateClientMerge()

  ' Update
  With clientMerge
    ' Load Client
    If Len(mClientId) &lt;&gt; 0 Then
      If Not .Client1.Load(mClientId) Then
        ' Ignore, wizard validation will check this
      End If
    End If

    ' Update
    If Success AndAlso parameters IsNot Nothing Then
      ' Refresh
      Success = .Refresh(parameters.ClientId, parameters.ClientId2, parameters.Client1HasPriority)

      ' Update Merge Items
      If Success Then
        Success = .MergeItems.UpdateFromHtmlWidgetJsonString(parameters.CompareItemsJson)
      End If
    End If
  End With

  Return Success

End Function

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

  Dim ClientMerge As finClientMerge
  Dim obj As Object
  Dim Success As Boolean
  Dim Warnings As ISList
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

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

  ' Create Client Merge object
  If Success Then
    Success = CreateClientMerge(mClientId, WizardFinishParameters, ClientMerge)
  End If

  ' Execute
  If Success Then
    Success = ClientMerge.ExecuteCommit(Warnings)
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean
                        
  Dim ClientMerge As finClientMerge
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim MatchesRO As ISReadOnlyList(Of finClientMatch)
  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

  ' Create Client Merge object
  If Success Then
    Success = CreateClientMerge(mClientId, Nothing, ClientMerge)
  End If

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      If ClientMerge.Client1.IsNew Then
        FailedControlId = "cboClient1"
        FailedMessage = String.Format("Client '{0}' not found.", mClientId)
      Else
        ' Get Matches
        If finBL.ClientFunctions.GetMatches(ClientMerge.Client1, MatchesRO, ClientMerge.Client1.ClientId, True) Then
          Data = MatchesRO.ToList()
        Else
          Success = False
        End If
      End If

    Case "Matches"
      ' Matches
      If ClientMerge.Refresh(mClientId, mCombinedParameters.GetString("ClientId2"), mCombinedParameters.GetBoolean("client1HasPriority")) Then
        Data = ClientMerge.MergeItems.ToHtmlWidgetJsonObject()
      Else
        Success = False
      End If
  End Select

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

  Return Success

End Function



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

  ' Record
  Public ClientId As String

  ' Column Captions
  Public ColumnCaptionBusinessNumber As String
  Public ColumnCaptionOrganisationNumber As String
  Public ColumnCaptionTaxNumber As String

End Class



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

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

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

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

  End Sub

End Class



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

  Public ClientId As String
  Public ClientId2 As String
  Public Client1HasPriority As Boolean
  Public CompareItemsJson As String

End Class

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

  Public Warnings As String

  Public Sub New(warnings As ISList)

    If warnings IsNot Nothing AndAlso warnings.Count &lt;&gt; 0 Then
      Me.Warnings = finBLShared.Runtime.TextUtilities.GetNumberedListFromIsList(warnings)
    End If

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes />
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&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="General" tooltipText="Select the main Client to merge another Client into."&gt;Main Client&lt;/li&gt;
        &lt;li tabId="Matches" tooltipText="Select the duplicate Client to merge into the main Client."&gt;Duplicate Client&lt;/li&gt;
        &lt;li tabId="MergeOptions" tooltipText="Select the Client details to be merged."&gt;Merge Options&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:5em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblClient1"&gt;Client&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboClient1"&gt;Client:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboClient1" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPriority"&gt;Does the main Client have priority in the merge?&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkClient1HasPriority" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Matches --&gt;
    &lt;div id="pageMatches" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:0"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:5em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblClient2"&gt;Select the duplicate Client to merge into the main Client&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboClient2"&gt;Client:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboClient2" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblMatches"&gt;A ranked list of possible matches for this Client is shown below&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      &lt;div style="flex-grow:1; position:relative"&gt;
        &lt;div id="gridMatches" class="is-dock-fill"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Merge Options --&gt;
    &lt;div id="pageMergeOptions" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:1; position:relative"&gt;
        &lt;div id="cigClientMerge" class="is-dock-fill"&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="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;Merge&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;

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

// Controls
var C = {
  //   General
  lblClient1: null,
  cboClient1: null,

  lblPriority: null,
  chkClient1HasPriority: null,

  //   Matches
  lblClient2: null,
  cboClient2: null,
  lblMatches: null,
  gridMatches: null,

  //   Merge Options
  cigClientMerge: null,
}

// Form
var frmMain;
var tabWizard;

// Other
var mRefreshRequired = false;

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

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

  // Controls
  //   General
  C.lblClient1 = widget.UI.Label("lblClient1", {});
  C.cboClient1 = widget.UI.DBCombo("cboClient1", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblPriority = widget.UI.Label("lblPriority", {});
  C.chkClient1HasPriority = widget.UI.CheckBox("chkClient1HasPriority", {
    caption: "Main Client has priority?",
  });

  //   Matches
  C.lblClient2 = widget.UI.Label("lblClient2", {});
  C.cboClient2 = widget.UI.DBCombo("cboClient2", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  //   Merge Options
  C.cigClientMerge = widget.UI.CompareItemsGrid("cigClientMerge", {});

  C.lblMatches = widget.UI.Label("lblMatches", {});

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

    onInitialiseRow: gridMatches_InitialiseRow,
    onRowDrilldown: gridMatches_RowDrilldown,
  });

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

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  C.chkClient1HasPriority.Value(true);

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_CompareItems = null;
  mRecord_Matches = 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);
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboClient1.Text(mRecord.ClientId);

    //C.chkCancelFutureChanges.Value(mRecord.CancelFutureChanges);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

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

  // Lists
  if (mRecord) {
    C.cboClient1.RefreshFromStandardRange("Clients");
    C.cboClient2.RefreshFromStandardRange("Clients");
  }

  // Controls
  if (mRecord) {
    if (mRecord.ClientId) {
      C.cboClient1.ReadOnly(true);
      C.cboClient1.ShowDropdown(false);
    }
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile optimisations

  // General

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

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

  // Finish Button
  if (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
}

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      break;

    default:
      break;
  }
}

// ===========
// Wizard Move
// ===========
function tabWizard_Move(direction) {
  var Ok;

  // Validate
  if (direction &gt; 0) {
    tabWizard_Validate(function () { tabWizard_MovePost(direction); });
  }
  else {
    // Can always move backwards
    tabWizard_MovePost(direction);
  }
}

function tabWizard_MovePost(direction) {
  var Ok = true;

  // Find Next Tab to Move To
  if (Ok) {
    var found = false;
    var newTab = tabWizard.SelectedTabIndex();

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        default:
          found = true;
          break;
      }

      // Found?
      if (found) {
        break;
      }
      else if (newTab == tabWizard.TabCount() - 1) {
        // Just in case!
        widget.UI.MsgBoxAlert("tabWizard_MovePost: Tab not handled!");
        break;
      }
    }
    while (true);

    // Refresh the New Tab
    tabWizard_Refresh(newTab);
  }
}

// ===========
// Refresh Tab
// ===========
function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "General":
        // General
        break;

      case "Matches":
        // Matches
        break;

      default:
        break;
    }
  }

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

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

  // Back, Next command buttons valid?
  tabWizard_UpdateButtons();

  // Resize Wizard
  tabWizard_Resize();

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        params = { clientId: C.cboClient1.Text() };
        break;

      case "Matches":
        // Matches
        if (C.cboClient1.Text() == C.cboClient2.Text()) {
          widget.UI.MsgBoxAlert("Main and Duplicate Client cannot be the same.", {}, function () {
            C.cboClient2.Focus();
          });
          Ok = false;
        }
        else {
          params = { clientId: C.cboClient1.Text(),
                     client1HasPriority: C.chkClient1HasPriority.Value(),
                     clientId2: C.cboClient2.Text()
                   };
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // 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, {}, function () {
      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
        mRecord_Matches = o.Data;
        gridMatches_Refresh();
        break;

      case "Matches":
        // Matches
        mRecord_CompareItems = o.Data;
        C.cigClientMerge.Refresh(mRecord_CompareItems, true, "&lt;html&gt;Main &lt;small&gt;(" + widget.UI.HtmlEncode(C.cboClient1.Text()) + ")&lt;/small&gt;", "&lt;html&gt;Duplicate &lt;small&gt;(" + widget.UI.HtmlEncode(C.cboClient2.Text()) + ")&lt;/small&gt;");
        break;

//      case "General":
//        // General
//        if (o.Data &amp;&amp; o.Data.length != 0) {
//          // Confirm warnings
//          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
//                                      o.Data,
//                                      {
//                                        heading: "Additional Confirmation",
//                                        icon: "Warning",
//                                      },
//                                      function () { validCallback(); },
//                                      null);
//
//          // Allow callbacks to continue
//          return;
//        };
//
//        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    var list = [];
    list.push("Merge Client '" + C.cboClient2.Text() + "' into Client '" + C.cboClient1.Text() + "'");
    list.push("PERMANENTLY delete Client '" + C.cboClient2.Text() + "'");

    widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                list,
                                {
                                  heading: "Combine Clients",
                                  icon: "Warning",
                                },
                                Form_ExecuteAction_FinishPost,
                                null);
  });
}

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

  // Create Parameters
  var params = { clientId: C.cboClient1.Text(),
                 client1HasPriority: C.chkClient1HasPriority.Value(),
                 clientId2: C.cboClient2.Text(),
                 compareItemsJson: JSON.stringify(mRecord_CompareItems)
               };

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

      // Unblock
      widget.UI.Unblock();

      if (data.Warnings) {
        widget.UI.MsgBoxAlert("Client Combine completed but the following warnings were given:\n\n" + data.Warnings, {}, function () {
          // Close Form
          widget.Close();

          // Refresh Parent (to show updated status)
          widget.RefreshParent();
        })
      }
      else {
        // Close Form
        widget.Close();

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

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

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

// ===========
// gridMatches
// ===========
function gridMatches_Refresh() {
  // Anything to show?
  if (!mRecord_Matches || mRecord_Matches.length == 0) {
    C.lblMatches.VisibleRow(false);
    C.gridMatches.Visible(false);
    return;
  }
  else {
    C.lblMatches.VisibleRow(true);
    C.gridMatches.Visible(true);
  }

  // Show Columns?
  var showBusinessNumber = false;
  var showDateOfBirth = false;
  var showGender = false;
  var showLegalName = false;
  var showLocation = false;  
  var showOrganisationNumber = false;   
  var showTaxNumber = false;

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

    if (item.BusinessNumber) showBusinessNumber = true;
    if (item.DateOfBirthJson) showDateOfBirth = true;
    if (item.Gender) showGender = true;
    if (item.LegalName) showLegalName = true;
    if (item.Location) showLocation = true;
    if (item.OrganisationNumber) showOrganisationNumber = true;
    if (item.TaxNumber) showTaxNumber = true;
  }

  // Add Columns
  C.gridMatches.ClearColumns();
  C.gridMatches.AddColumnDrilldown("Drilldown", { icon: "Clipboard_Paste" });
  C.gridMatches.AddColumnCode("ClientId", { caption: "Client" });
  C.gridMatches.AddColumnString("Name", { caption: "Name" });
  C.gridMatches.AddColumnString("LegalName", { caption: "Legal Name", visible: showLegalName });  
  C.gridMatches.AddColumnCode("Gender", { caption: "Gender", visible: showGender });  
  C.gridMatches.AddColumnDate("DateOfBirthJson", { caption: "DOB", visible: showDateOfBirth });
  C.gridMatches.AddColumnString("Location", { caption: "Location", width: "6em", visible: showLocation });  
  C.gridMatches.AddColumnString("TaxNumber", { caption: mRecord.ColumnCaptionTaxNumber, visible: showTaxNumber });
  C.gridMatches.AddColumnString("BusinessNumber", { caption: mRecord.ColumnCaptionBusinessNumber, visible: showBusinessNumber });
  C.gridMatches.AddColumnString("OrganisationNumber", { caption: mRecord.ColumnCaptionOrganisationNumber, visible: showOrganisationNumber });

  // Refresh Grid
  C.gridMatches.VirtualDataRefresh(mRecord_Matches);
}

function gridMatches_InitialiseRow(e) {
  var item = mRecord_Matches[e.row.listIndex];

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

  // Matching colours
  // NOTE: A item will only have a match colour if it matches
  
  // Business Number
  if (item.BusinessNumberMatchColour &amp;&amp; e.row.cells.BusinessNumber) {
    e.row.cells.BusinessNumber.backgroundColour = item.BusinessNumberMatchColour
  }
  
  // Date of Birth
  if (item.DateOfBirthMatchColour &amp;&amp; e.row.cells.DateOfBirthJson) {
    e.row.cells.DateOfBirthJson.backgroundColour = item.DateOfBirthMatchColour;
  }
  
  // Gender
  if (item.GenderMatchColour &amp;&amp; e.row.cells.Gender) {
    e.row.cells.Gender.backgroundColour = item.GenderMatchColour;
  }
  
  // Legal Name
  if (item.LegalNameMatchColour &amp;&amp; e.row.cells.LegalName) {
    e.row.cells.LegalName.backgroundColour = item.LegalNameMatchColour;
  }
  
  // Location
  if (item.LocationMatchColour &amp;&amp; e.row.cells.Location) {
    e.row.cells.Location.backgroundColour = item.LocationMatchColour;
  }
  
  // Name
  if (item.NameMatchColour &amp;&amp; e.row.cells.Name) {
    e.row.cells.Name.backgroundColour = item.NameMatchColour;
  }
  
  // Organisation Number
  if (item.OrganisationNumberMatchColour &amp;&amp; e.row.cells.OrganisationNumber) {
    e.row.cells.OrganisationNumber.backgroundColour = item.OrganisationNumberMatchColour;
  }
  
  // Tax Number
  if (item.TaxNumberMatchColour &amp;&amp; e.row.cells.TaxNumber) {
    e.row.cells.TaxNumber.backgroundColour = item.TaxNumberMatchColour;
  }

  // Hyperlink ClientId
  e.row.cells.ClientId.hyperlink = "app://FormShow?form=Client&amp;id=" + encodeURI(item.ClientId);
}

function gridMatches_RowDrilldown(e) {
  C.cboClient2.Text(mRecord_Matches[C.gridMatches.ActiveDataRowListIndex()].ClientId);
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>QFBg93qqVEm0YI4WLcWURA</UniqueId>
    <AllowRefresh>false</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1024</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon />
    <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>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ClientId" 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.Clients</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>