<?xml version="1.0" encoding="utf-8"?><finScript version="1.00" exportedUtcDate="2020-07-15T02:11:33.0000000"><CreatedUserId>ADMIN</CreatedUserId><CreatedUtcDate>2020-04-28T20:33:45.1170000</CreatedUtcDate><UpdatedUserId>ADMIN</UpdatedUserId><UpdatedUtcDate>2020-07-15T02:11:16.1470000</UpdatedUtcDate><ScriptId>ACTIVATEACCLEDGERS</ScriptId><Description>Activate Accounting Ledgers</Description><ScriptType>HtmlWidget</ScriptType><Active>true</Active><AllowUI>false</AllowUI><Category /><Code>' HtmlWidget_AccountAccountingLedgersActivate
Option Explicit On
Option Strict On

' #################################################################
' Activate Accounting Ledgers
'
' Version: 1.01 (15/07/2020)
'
' Usage: System-defined HTML Widget
' #################################################################

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

' Objects
Private mColumns As ISList
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)

  ' Other Parameters
  With mCombinedParameters
    mColumns = .GetListFromGroupingList("Columns")
  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
      Main = Finish(parametersJson, returnValue)

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

    Case "GetInitialisationInfo"
      ' Get Initialisation Info
      Main = GetInitialisationInfo(returnValue)

    Case "Form_PageAccountingLedgers_Refresh"
      ' The Accounting Ledger Page is being refreshed, fetch Accounting Ledgers
      Main = Form_PageAccountingLedgers_Refresh(returnValue)

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

End Function

''' &lt;summary&gt;
'''  Activates selected Accounting Ledgers.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        ByRef returnValue As String) As Boolean

  Dim obj As Object
  Dim ProcessedCount As Integer
  Dim Success As Boolean
  Dim WizardFinishParameter As WizardFinishParameter
  Dim WizardFinishParameters As List(Of WizardFinishParameter)

  ' Assume Success
  Success = True

  ' Deserialise
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(List(Of WizardFinishParameter)), obj) Then
    WizardFinishParameters = DirectCast(obj, List(Of WizardFinishParameter))
  Else
    Success = False
  End If

  ' Process Rows
  If Success Then
    For Each WizardFinishParameter In WizardFinishParameters
      With WizardFinishParameter
        If Not .Processed AndAlso Len(.ErrorMessage) = 0 Then
          ' Activate Accounting Ledger
          If finBL.AccountFunctions.AccountingLedgerActivate(.AccountPk, .AccountingLedgerPk) Then
            .Processed = True
          Else
            .ErrorMessage = finBL.Error.Message(True, False)
          End If

          ' Processing
          ProcessedCount += 1
          If ProcessedCount &gt;= BATCH_SIZE Then Exit For
        End If
      End With
    Next
  End If

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

  Return Success

End Function

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

  Dim Account As finAccount
  Dim AccountId As String
  Dim AccountingLedgerPk As Integer
  Dim i As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    AccountId = .GetString("accountId")
    AccountingLedgerPk = .GetInteger("accountingLedgerPk")
  End With

  ' Initialise
  Account = finBL.CreateAccount()

  If Account.Load(AccountId) Then
    ' Retrieve index of selected item
    If Account.AccountingLedgers.ExistsPk(AccountingLedgerPk) Then
      i = Account.AccountingLedgers.IndexOf(Account.AccountingLedgers.ItemByPk(AccountingLedgerPk))

      ' Get Summary page
      returnValue = finBL.SummaryPageFunctions.AccountAccountingLedgerSummary(False, Account, i, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
    Else
      returnValue = ""
    End If
  Else
    Success = False
  End If

  Return Success

End Function

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

  Dim Column As String
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Get Form Initialisation Info
  With FormInitialisationInfo
    ' Record    
    .DefaultEntityId = finBL.SettingsUser.DefaultEntityIdResolved
    .DefaultToDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(finBL.TimeZoneFunctions.GetCurrentDatabaseDate())
    .ShowOtherFilters = mCombinedParameters.GetString("ShowOtherFilters")

    ' Additional Grid Columns
    For Each Column In mColumns
      .Columns.Add(Column)
    Next

    ' Configuration
    .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    .ReadOnly = finBL.Database.IsReadOnly
    .ShowBranch = finBL.Settings.AddOns.Branch
    .ShowEntity = finBL.Settings.AddOns.Entity
  End With

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

  Return Success

End Function

''' &lt;summary&gt;
'''  The Accounting Ledger Page is being refreshed, fetch Accounting Ledgers
''' &lt;/summary&gt;
Private Function Form_PageAccountingLedgers_Refresh(ByRef returnValue As String) As Boolean

  Dim AccountAccountingLedgersActivate As finAccountAccountingLedgersActivate
  Dim AccountAccountingLedgersActivateItem As finAccountAccountingLedgersActivateItem
  Dim ActivationItems As New List(Of ActivationItem)
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  AccountAccountingLedgersActivate = finBL.CreateAccountAccountingLedgersActivate()

  ' Set Parameters
  With AccountAccountingLedgersActivate
    .ActivateToDate = mCombinedParameters.GetDate("ActivateToDate")
    .EntityId = mCombinedParameters.GetString("EntityId")

    ' Ranges
    .RangeAccounts = mCombinedParameters.GetString("RangeAccounts")
    .RangeAccountManagers = mCombinedParameters.GetString("RangeAccountManagers")
    .RangeAccountTypes = mCombinedParameters.GetString("RangeAccountTypes")
    .RangeBranches = mCombinedParameters.GetString("RangeBranches")
    .RangeDepartments = mCombinedParameters.GetString("RangeDepartments")

    ' Refresh
    Success = .Refresh()
  End With

  ' Process each result
  If Success Then
    For Each AccountAccountingLedgersActivateItem In AccountAccountingLedgersActivate
      ActivationItems.Add(New ActivationItem(finBL, AccountAccountingLedgersActivateItem, mColumns))
    Next

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

  Return Success

End Function



''' &lt;summary&gt;
'''  Accounting Ledger Activation Item for serialisation.
''' &lt;/summary&gt;
Public Class ActivationItem

  Public AccountId As String
  Public AccountingLedgerPk As Integer
  Public AccountName As String
  Public AccountPk As Integer
  Public CanInclude As Boolean
  Public DateBegin As Date
  Public DateEnd As Date
  Public DateFirst As Date
  Public Description As String
  Public ElementId As String
  Public Include As Boolean
  Public InvalidMessage As String
  Public MethodDescription As String
  Public Notes As String
  Public Value As Decimal

  ' Other
  Private mColumns As ISList

  Public Sub New(finBL As ISfinSupport,
                 accountAccountingLedgersActivateItem As finAccountAccountingLedgersActivateItem,
                 columns As ISList)

    mColumns = columns

    With accountAccountingLedgersActivateItem
      Me.AccountId = .AccountId
      Me.AccountingLedgerPk = .AccountingLedgerPk
      Me.AccountName = .AccountName
      Me.AccountPk = .AccountPk
      Me.CanInclude = .CanInclude
      Me.Include = Me.CanInclude
      Me.InvalidMessage = .InvalidMessage
      Me.Value = .Value

      ' Optional Columns
      If columns.Exists("Description") Then Me.Description = .Description
      If columns.Exists("Element Id") Then Me.ElementId = .ElementId
      If columns.Exists("Ending") Then Me.DateEnd = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.DateEnd)
      If columns.Exists("First") Then Me.DateFirst = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.DateFirst)
      If columns.Exists("Method") Then Me.MethodDescription = .MethodDescription
      If columns.Exists("Notes") Then Me.Notes = .Notes
      If columns.Exists("Opening") Then Me.DateBegin = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.DateBegin)
    End With

  End Sub

  ' Prevent Serialisation for Not Applicable Properties
  Public Function ShouldSerializeDescription() As Boolean
    Return mColumns.Exists("Description")
  End Function

  Public Function ShouldSerializeElementId() As Boolean
    Return mColumns.Exists("Element Id")
  End Function

  Public Function ShouldSerializeEnding() As Boolean
    Return mColumns.Exists("Ending")
  End Function

  Public Function ShouldSerializeFirst() As Boolean
    Return mColumns.Exists("First")
  End Function

  Public Function ShouldSerializeInvalidMessage() As Boolean
    Return Len(Me.InvalidMessage) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeMethod() As Boolean
    Return mColumns.Exists("Method")
  End Function

  Public Function ShouldSerializeNotes() As Boolean
    Return mColumns.Exists("Notes") AndAlso Len(Me.Notes) &lt;&gt; 0
  End Function

  Public Function ShouldSerializeOpening() As Boolean
    Return mColumns.Exists("Opening")
  End Function

End Class



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

  ' Record
  Public DefaultEntityId As String
  Public DefaultToDate As Date
  Public ShowOtherFilters As String

  ' Additional Grid Columns
  Public Columns As List(Of String)

  ' Configuration
  Public PromptOnCommit As Boolean
  Public [ReadOnly] As Boolean
  Public ShowBranch As Boolean
  Public ShowEntity As Boolean

  Public Sub New()
    Me.Columns = New List(Of String)
  End Sub

End Class



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

  Public AccountingLedgerPk As Integer
  Public AccountPk As Integer
  Public ErrorMessage As String
  Public Processed As Boolean

End Class</Code><Language>VisualBasic</Language><Notes /><PermissionKeyExecute /><RunWithoutPrompts>false</RunWithoutPrompts><TemplateText>&lt;div id="frmMain" class="is-widget-content"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Select the Accounting Ledgers to activate."&gt;Accounting Ledger Options&lt;/li&gt;
        &lt;li tabId="AccountingLedgers" tooltipText="Select the Accounting Ledgers to activate."&gt;Accounting Ledgers&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:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;!-- Standard Controls --&gt;
        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblEntity"&gt;Select the Entity&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboEntity"&gt;Entity:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboEntity" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDateAsAt"&gt;Activate Accounting Ledgers opening on or before&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateDateAsAt"&gt;Ledgers To:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateDateAsAt" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;!-- Other Filters --&gt;
        &lt;tbody id="tbOtherFilters"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label&gt;Enter ranges to filter information&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtRangeAccounts"&gt;Accounts:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRangeAccounts" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtRangeAccountManagers"&gt;Account&amp;nbsp;Managers:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRangeAccountManagers" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtRangeAccountTypes"&gt;Account Types:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRangeAccountTypes" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr id="trRangeBranches"&gt;
            &lt;th&gt;&lt;label for="txtRangeBranches"&gt;Branches:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRangeBranches" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtRangeDepartments"&gt;Departments:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtRangeDepartments" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Accounting Ledgers --&gt;
    &lt;div id="pageAccountingLedgers"&gt;
      &lt;div class="is-dock-fill is-split-container split5050"&gt;
        &lt;div class="panel"&gt;
          &lt;div id="gridAccountingLedgers"&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="panel"&gt;
          &lt;div id="wbAccountingLedgers" 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="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;
    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdBack" class="is-button"&gt;Back&lt;/button&gt;
    &lt;button id="cmdNext" class="is-button"&gt;Next&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Activate&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;

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

// Other
var mAdvancedVisible = false;
var mHasAdvancedOptions = false;

// Controls
var C = {
  lblEntity: null,
  cboEntity: null,
  lblDateAsAt: null,
  dateDateAsAt: null,
  tbOtherFilters: null,
  txtRangeAccounts: null,
  txtRangeAccountManagers: null,
  txtRangeAccountTypes: null,
  trRangeBranches: null,
  txtRangeBranches: null,
  txtRangeDepartments: null,

  // Accounting Ledgers
  gridAccountingLedgers: null,
  wbAccountingLedgers: null
};

// Form
var frmMain;
var tabWizard;

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

var cmdAdvanced;

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

  // Controls
  C.lblEntity = widget.UI.Label("lblEntity", {});
  C.cboEntity = widget.UI.DBCombo("cboEntity", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_5
  });
  C.lblDateAsAt = widget.UI.Label("lblDateAsAt", {});
  C.dateDateAsAt = widget.UI.DateBox("dateDateAsAt", {
    allowBlank: false
  });
  C.tbOtherFilters = $("#tbOtherFilters");
  C.trRangeBranches = $("#trRangeBranches");

  C.wbAccountingLedgers = widget.UI.PreviewPane("wbAccountingLedgers", {});

  // Ranges
  for(var k in C) {
    if (k.startsWith("txtRange")) {
      C[k] = widget.UI.TextBox(k, {
        maxLength: 255,
        onButtonClick: txtRange_ButtonClick,
      });
      var buttons = [];

      // Lookup button
      buttons.push({id: "Lookup", icon: "Find", tooltipText: "Lookup"});

      // Define buttons
      C[k].ButtonsDefine(buttons);
    }
  }

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

    onAction: gridAccountingLedgers_Action,
    onAfterRowActivate: gridAccountingLedgers_AfterRowActivate,
    onBeforeCellUpdate: gridAccountingLedgers_BeforeCellUpdate,
    onInitialiseRow: gridAccountingLedgers_InitialiseRow
  });

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

  // Create Tabs
  tabWizard = new widget.UI.Tabs("tabWizard", { style: "wizard" });

  // Handle Wizard Buttons
  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(function () {
    // Toggle Advanced
    mAdvancedVisible = !mAdvancedVisible;

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

    // Resize
    Form_Resize();
  });

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

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

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

  // Resize
  Form_Resize();

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

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

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

// ===========
// Fields Load
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboEntity.Text(mRecord.DefaultEntityId);
    C.dateDateAsAt.Value(mRecord.DefaultToDate);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

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

  // Information Lists

  // Lists
  C.cboEntity.RefreshFromStandardRange("Entities", "", true);

  // Advanced Options
  mHasAdvancedOptions = false;
  if (mRecord) {
    if (mRecord.ShowOtherFilters.toUpperCase() == "ADVANCED") mHasAdvancedOptions = true;
  }

  // Controls
  C.lblEntity.VisibleRow(mRecord.ShowEntity);
  C.cboEntity.VisibleRow(mRecord.ShowEntity);
  if(mRecord) {
    // Show other filters
    switch(mRecord.ShowOtherFilters.toUpperCase()) {
      case "TRUE":
        C.tbOtherFilters.show();
        break;

      case "FALSE":
        C.tbOtherFilters.hide();
        break;

      case "ADVANCED":
        C.tbOtherFilters.find("tr").each(function(index, tr) {
          $(tr).addClass("advanced");
        });
        break;
    }
  }
  if(!mRecord.ShowBranch) {
    C.trRangeBranches.remove();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize
  tabWizard_Resize();
}

function tabWizard_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "AccountingLedgers":
        pageAccountingLedgers_Refresh();
        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;
  }
}

// ========================
// Create Finish Parameters
// ========================
function CreateFinishParameters() {
  var records = [];

  // Identify which Accounting Ledgers are being included
  for(var i = 0; i &lt; mRecord_AccountingLedgers.length; i++) {
    var item = mRecord_AccountingLedgers[i];

    if(item.Include &amp;&amp; item.CanInclude) {
      var o = {
        accountPk: item.AccountPk,
        accountingLedgerPk: item.AccountingLedgerPk
      }
      records.push(o);
    }
  }

  return records;
}

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

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function() {
    if (mRecord.PromptOnCommit) {
      // Confirm
      var heading = "Activate Accounting Ledgers";
      var message = "Are you sure you want to activate the selected Accounting Ledgers?";

      widget.UI.MsgBoxConfirm(message,
                              {
                                heading: heading,
                              },
                              Form_ExecuteAction_FinishPost,
                              null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

function Form_ExecuteAction_FinishPost() {
  // Disable Form
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Committing 0%, please wait...");

  // Get Parameters
  var params = CreateFinishParameters();

  // Process records
  Form_ExecuteAction_FinishPost_Process(JSON.stringify(params));
}

// ==========================================================================
// This function is called recursively until all records have been processed.
// Batch size is determined by Parameter BATCH_SIZE in the Script Code.
// Once all records have been processed, the recursive call is stopped by
// calling Form_ExecuteAction_FinishPost_Process_Done.
// ==========================================================================
function Form_ExecuteAction_FinishPost_Process(data) {
  var results = JSON.parse(data);
  var processedCount = 0;

  // Records still to be processed?
  for(var i = 0; i &lt; results.length; i++) {
    if(results[i].Processed || results[i].ErrorMessage) processedCount++
  }

  // Process if there are unprocessed rows left.
  if(processedCount &lt; results.length) {
    // Update Block text
    var percentageComplete;
    if(results.length == 0) {
      percentageComplete = "100";
    }
    else {
      percentageComplete = widget.FormatNumber((processedCount / results.length) * 100, 0);
    }

    // Update Block
    widget.UI.Block("Committing " + percentageComplete + "%, please wait...");

    // Process records - recursive call
    widget.GetString("Finish", results, Form_ExecuteAction_FinishPost_Process, Form_ExecuteAction_FinishPost_Process_Fail);
  }
  else {
    // Update grid with successful / unsuccessful records
    Form_ExecuteAction_FinishPost_Process_Done(results);
  }
}

// Recursive calls complete
function Form_ExecuteAction_FinishPost_Process_Done(results) {
  // Update Block
  widget.UI.Block("Committing 100%, please wait...");

  // Update Results
  for(var i = 0; i &lt; results.length; i++) {
    var result = results[i];

    //TODO: Review, can we use indexOf or something to avoid inner loop?
    for(var j = 0; j &lt; mRecord_AccountingLedgers.length; j++) {
      var accountingLedger = mRecord_AccountingLedgers[j];

      if(result.AccountingLedgerPk == accountingLedger.AccountingLedgerPk) {
        if(result.Processed) {
          accountingLedger.Processed = true;
          accountingLedger.Include = false;
          accountingLedger.CanInclude = false;
          accountingLedger.Icon = "Check";
        }
        else if(result.ErrorMessage) {
          accountingLedger.Icon = "Warning";
          accountingLedger.InvalidMessage = result.ErrorMessage;
        }
        break;
      }
    }
  }

  // Refresh Grid
  pageAccountingLedgers_Refresh_Done(JSON.stringify(mRecord_AccountingLedgers));
}

function Form_ExecuteAction_FinishPost_Process_Fail(errorMessage) {
  // Show Form
  frmMain.Visible(true);

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

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

function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// =====================
// gridAccountingLedgers
// =====================
function gridAccountingLedgers_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "REFRESH":
      pageAccountingLedgers_Refresh(true);
      break;

    case "SELECTUP":
    case "SELECTDOWN":
      var activeRowIndex = C.gridAccountingLedgers.ActiveDataRowListIndex();
      var indexes = [];

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

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

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

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

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

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

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

      for(var i = 0; i &lt; selectedItems.length; i++) {
        var item = mRecord_AccountingLedgers[selectedItems[i]];
        if(item.CanInclude) item.Include = (actionId.toUpperCase() == "CHECK");
      }
      C.gridAccountingLedgers.VirtualDataRefresh(mRecord_AccountingLedgers, true, { retainSelectedRows: true });
      break;

    default:
      break;
  }

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

function gridAccountingLedgers_AfterRowActivate(e) {
  // Preview
  wbAccountingLedgers_Preview();
}

function gridAccountingLedgers_BeforeCellUpdate(e) {
  var item = mRecord_AccountingLedgers[e.row.listIndex];

  switch(e.columnKey) {
    case "Include":
      item.Include = e.newValue;
      break;
  }
}

function gridAccountingLedgers_InitialiseRow(e) {
  var item = mRecord_AccountingLedgers[e.row.listIndex];

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

  // Tooltip
  e.row.cells.Icon.tooltipText = item.InvalidMessage;

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

  // Cell hyperlinks
  if(item.AccountId) {
    e.row.cells.AccountId.hyperlink = "app://formshow?form=Account&amp;id=" + encodeURI(item.AccountId);
  }
}

function gridAccountingLedgers_Refresh() {
  var showColumnElementId = false;
  var showColumnFirst = false;
  var showColumnEnding = false;
  var showColumnMethod = false;
  var showColumnNotes = false;
  var showColumnOpening = false;
  var showColumnDescription = false;

  // Determine which columns should be included
  for(var i = 0; i &lt; mRecord.Columns.length; i++) {
    switch(mRecord.Columns[i].toUpperCase()) {
      case "DESCRIPTION":
        showColumnDescription = true;
        break;

      case "ELEMENT ID":
        showColumnElementId = true;
        break;

      case "ENDING":
        showColumnEnding = true;
        break;

      case "FIRST":
        showColumnFirst = true;
        break;

      case "METHOD":
        showColumnMethod = true;
        break;

      case "NOTES":
        showColumnNotes = true;
        break;

      case "OPENING":
        showColumnOpening = true;
        break;
    }
  }

  // Add Columns
  C.gridAccountingLedgers.ClearColumns();
  C.gridAccountingLedgers.AddColumnIcon("Icon", { caption: "" });
  C.gridAccountingLedgers.AddColumnBoolean("Include", { caption: "Include", allowEdit: true });
  C.gridAccountingLedgers.AddColumnCode("AccountId", { caption: "Account" });
  C.gridAccountingLedgers.AddColumnString("AccountName", { caption: "Name" });
  C.gridAccountingLedgers.AddColumnDate("DateBegin", { caption: "Opening", visible: showColumnOpening });
  C.gridAccountingLedgers.AddColumnString("ElementId", { caption: "Element", visible: showColumnElementId });
  C.gridAccountingLedgers.AddColumnString("Description", { caption: "Description", visible: showColumnDescription });
  C.gridAccountingLedgers.AddColumnDate("DateFirst", { caption: "First", visible: showColumnFirst });
  C.gridAccountingLedgers.AddColumnDate("DateEnd", { caption: "Ending", visible: showColumnEnding });
  C.gridAccountingLedgers.AddColumnString("MethodDescription", { caption: "Method", visible: showColumnMethod });
  C.gridAccountingLedgers.AddColumnCurrency("Value", { caption: "Value" });
  C.gridAccountingLedgers.AddColumnString("InvalidMessage", { caption: "Error" });
  C.gridAccountingLedgers.AddColumnString("Notes", { caption: "Notes", visible: showColumnNotes });

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

  // Give collection ability to form a unique cache key and preview parameters for the Widget
  mRecord_AccountingLedgers.GetCacheKey = function (index) {
    var item = mRecord_AccountingLedgers[index];
    return item.AccountingLedgerPk;
  };
  mRecord_AccountingLedgers.GetPreviewFetchParameters = function (index) {
    var item = mRecord_AccountingLedgers[index];
    var o = {};

    o.accountId = item.AccountId;
    o.accountingLedgerPk = item.AccountingLedgerPk;
    o.target = "WebInternal";
    o.highDpi = widget.IsHighDpi();

    return o;
  };

  // Refresh
  C.gridAccountingLedgers.VirtualDataRefresh(mRecord_AccountingLedgers);

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

// =====================
// pageAccountingLedgers
// =====================
function pageAccountingLedgers_Refresh(forceRefresh) {
  // Parameters
  var params = {
    activateToDate: C.dateDateAsAt.Value(),
    entityId: C.cboEntity.Text(),
    rangeAccounts: C.txtRangeAccounts.Text(),
    rangeAccountManagers: C.txtRangeAccountManagers.Text(),
    rangeAccountTypes: C.txtRangeAccountTypes.Text(),
    rangeBranches: C.txtRangeBranches.Text(),
    rangeDepartments: C.txtRangeDepartments.Text()
  }

  if(JSON.stringify(params) == mGridParams &amp;&amp; !forceRefresh) {
    // Parameters have not changed
  }
  else {
    // Hide Form
    frmMain.Visible(false);

    // Block UI
    widget.UI.Block("Getting Accounting Ledgers, please wait...");

    // Save Parameters
    mGridParams = JSON.stringify(params);

    // Get Grid data
    widget.GetString("Form_PageAccountingLedgers_Refresh", params, pageAccountingLedgers_Refresh_Done, function(errorMessage) {
      mGridParams = "";

      // Show Form
      frmMain.Visible(true);

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

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

function pageAccountingLedgers_Refresh_Done(data) {
  mRecord_AccountingLedgers = JSON.parse(data);

  // Clear Preview Cache
  C.wbAccountingLedgers.CacheClear();

  // Refresh Grid
  gridAccountingLedgers_Refresh();

  // Show Form
  frmMain.Visible(true);

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

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

function tabWizard_Move(direction) {
  var Ok;

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

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

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

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // NOTE: Due to this page being quite long and vertical scrollbars potentially interfering, call serveral times to layout correctly
      tabWizard_Resize_General();
      window.setTimeout(tabWizard_Resize_General, 10);
      window.setTimeout(tabWizard_Resize_General, 20);
      break;

    default:
      break;
  }
}

function tabWizard_Resize_General() {
  C.txtRangeAccounts.WidthResizeFromParent();
  C.txtRangeAccountManagers.WidthResizeFromParent();
  C.txtRangeAccountTypes.WidthResizeFromParent();
  C.txtRangeBranches.WidthResizeFromParent();
  C.txtRangeDepartments.WidthResizeFromParent();
}

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

  // Database is read only?
  if(mRecord) {
    if(mRecord.ReadOnly) {
      cmdCancel.hide();
      cmdFinish.text("Close");
    }
  }

  // Advanced Options
  if (mHasAdvancedOptions) {
    switch(tabWizard.SelectedTabId()) {
      case "General":
        cmdAdvanced.show();
        break;

      default:
        cmdAdvanced.hide();
    }
  }
  else {
    cmdAdvanced.hide();
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "AccountingLedgers":
        var found = false;

        // At least one row must be selected for update.
        for(var i = 0; i &lt; mRecord_AccountingLedgers.length; i++) {
          if(mRecord_AccountingLedgers[i].Include) {
            found = true;
            break;
          }
        }

        if(!found) {
          Ok = false;
          widget.UI.MsgBoxAlert("You have not selected any Accounting Ledgers to activate.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        break;
    }

    if (params) {
      // Disable Form
      frmMain.FormDisable("Validating");

      // Extend parameters
      params.pageId = tabWizard.SelectedTabId();

      // Call WizardValidate method in Script
      widget.GetString("WizardValidate",
                       params,
                       function (data) { tabWizard_ValidatePost(validCallback, data); },
                       tabWizard_ValidateFail);
    }
    else {
      // No server-side validation
      validCallback();
    }
  }
}

function tabWizard_ValidatePost(validCallback, data) {
  // Enable form
  frmMain.FormEnable();

  // Parse Data
  var o = {};
  if (data) o = JSON.parse(data);

  if (o.FailedMessage) {
    // -----------------
    // Validation failed
    // -----------------
    var o = JSON.parse(data);
    widget.UI.MsgBoxAlert(o.FailedMessage);
    if (o.FailedControlId) $("#" + o.FailedControlId).focus();
  }
  else {
    // ---------------------
    // Validation successful
    // ---------------------
    // Validation could pass back additional information, e.g., to use in tabWizard_Refresh
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        if (o.Data &amp;&amp; o.Data.length != 0) {
          // Confirm warnings
          widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                      o.Data,
                                      {
                                        heading: "Additional Confirmation",
                                        icon: "Warning",
                                      },
                                      function () { validCallback(); },
                                      null);

          // Allow callbacks to continue
          return;
        };
        break;
    }

    // Callback
    validCallback();
  }
}

// ========
// txtRange
// ========
function txtRange_ButtonClick(sender, e) {
  if (e.id == "Lookup") {
    var caption = sender.Caption();
    var range = sender.Element().attr("id");
    caption = caption.substr(0, caption.length - 1);
    range = range.substr(8);

    var options = {
      caption: "Lookup " + caption
    }

    // Limit Branches to selected Entity
    if (range &amp;&amp; range == "Branches" &amp;&amp; C.cboEntity.Text()) {
      options.sqlWhere = "EntityId='" + C.cboEntity.Text() + "'";
    }

    widget.UI.Forms.ShowRangeLookupFromStandardRange(range, sender.Text(), options,
    function (newRange) {
      sender.Text(newRange);
      sender.Focus();
    });
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ===================
// wbAccountingLedgers
// ===================
function wbAccountingLedgers_Preview() {
  C.wbAccountingLedgers.PreviewFromGridCollection(C.gridAccountingLedgers, mRecord_AccountingLedgers, "GetAccountingLedgerPreview");
}

&lt;/script&gt;</TemplateText><TemplateTextBookmarks>940</TemplateTextBookmarks><TimeoutSeconds>60</TimeoutSeconds><UniqueId>xw-g6qGkjk+eCE+8OBdN-g</UniqueId><AllowRefresh>true</AllowRefresh><Caption /><HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight><HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth><HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling><HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2><HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget><HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery><HtmlWidgetResourceJQueryVersion /><Icon>AccountingLedgers_Activate</Icon><JavaScriptDebugger>None</JavaScriptDebugger><RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled><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>Other Filter Options.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="ShowOtherFilters" type="List"><BlankTip /><Caption /><StandaloneOnly>false</StandaloneOnly><TooltipText /><DefaultValueExpression /><Enabled>true</Enabled><HideDescription>false</HideDescription><IndentLevel>0</IndentLevel><Mandatory>false</Mandatory><NonPersistable>false</NonPersistable><ReadOnly>false</ReadOnly><ReadOnly2>false</ReadOnly2><Value>Advanced</Value><Visible>true</Visible><List>True,False,Advanced</List><LimitToList>true</LimitToList><MaxLength>8</MaxLength><Rows>1</Rows></Parameter><Parameter name="" type="SectionStart"><BlankTip /><Caption>Additional Columns to display in the Grid.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="Columns" type="GroupingList"><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>Opening;False|Description;False</Value><Visible>true</Visible><List>Opening,Element Id,Description,First,Ending,Method,Notes</List><GroupingListShowPageBreakButton>false</GroupingListShowPageBreakButton><NoIndent>true</NoIndent></Parameter></Parameters></ISParameterDefs></Parameters></finScript>