<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-09-14T04:06:25.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2020-02-10T21:58:50.0330000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-09-14T04:05:18.7300000</UpdatedUtcDate>
    <ScriptId>IIR</ScriptId>
    <Description>Investment Income Report Export</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_InvestmentIncomeReportExport
Option Explicit On
Option Strict On

' #################################################################
' Investment Income Report Export
'
' Version: 1.05 (14/09/2022)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.03  11/11/2020  ISS                Updated
'    1.04  11/05/2022  ISS      J028712   Removed obsoleted Functions
'    1.05  14/09/2022  ISS      J029580   Updated heading
' #################################################################

' Constants
Private Const FORM_KEY As String = "InvestmentIncomeReportExport"

' 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)

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

    Case "DownloadExport"
      ' Downloads an Investment Income Report Export
      Main = DownloadExport(returnValue)

    Case "Form_TaxPeriod_Change"
      ' Tax Period has changed
      Main = Form_TaxPeriod_Change(returnValue)

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

  End Select

End Function

''' &lt;summary&gt;
'''  Creates a loaded finTaxFileExport_InvestmentIncomeReport_NZ object.
''' &lt;/summary&gt;
Private Function CreateTaxFileExport(downloadType As String,
                                     taxPeriodId As String,
                                     ByRef filename As String,
                                     ByRef taxFileExport_InvestmentIncomeReport_NZ As finTaxFileExport_InvestmentIncomeReport_NZ) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  filename = ""
  taxFileExport_InvestmentIncomeReport_NZ = finBL.CreateTaxFileExport_InvestmentIncomeReport_NZ()

  ' Build Object
  With taxFileExport_InvestmentIncomeReport_NZ
    ' Tax Period
    .TaxPeriodId = taxPeriodId

    ' Download Type
    Select Case UCase(DownloadType)
      Case "ALL"
        .AIL_Export = True
        .RWT_Export = True
        .RWTD_Export = True
        .NRWT_Export = True

      Case "RWT"
        .AIL_Export = False
        .RWT_Export = True
        .RWTD_Export = False
        .NRWT_Export = False
        filename = .RWT_ExportFilenameResolved

      Case "RWTD"
        .AIL_Export = False
        .RWT_Export = False
        .RWTD_Export = True
        .NRWT_Export = False
        filename = .RWTD_ExportFilenameResolved

      Case "NRWT"
        .AIL_Export = False
        .RWT_Export = False
        .RWTD_Export = False
        .NRWT_Export = True
        filename = .NRWT_ExportFilenameResolved

      Case "AIL"
        .AIL_Export = True
        .RWT_Export = False
        .RWTD_Export = False
        .NRWT_Export = False
        filename = .AIL_ExportFilenameResolved

      Case Else
        Success = False
        finBL.Error.ErrorBegin("Invalid Download Type.")
    End Select

    ' Load
    If Success Then
      Success = .Load()
    End If
  End With

  Return Success

End Function

''' &lt;summary&gt;
'''  Downloads an Investment Income Report Export file.
''' &lt;/summary&gt;
Private Function DownloadExport(ByRef returnValue As String) As Boolean

  Dim DownloadType As String
  Dim FileData() As Byte
  Dim FileInfo As finFileDownloadInfo
  Dim Filename As String
  Dim Success As Boolean
  Dim TaxFileExport_InvestmentIncomeReport_NZ As finTaxFileExport_InvestmentIncomeReport_NZ
  Dim TaxPeriodId As String

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    DownloadType = .GetString("DownloadType")
    TaxPeriodId = .GetString("TaxPeriodId")
  End With

  ' Get Tax File Export Object
  Success = CreateTaxFileExport(DownloadType, TaxPeriodId, Filename, TaxFileExport_InvestmentIncomeReport_NZ)

  ' Execute Export
  If Success Then
    Success = TaxFileExport_InvestmentIncomeReport_NZ.ExecuteExport()
  End If

  ' Get File
  If Success Then
    Success = finBL.Runtime.FileUtilities.ReadBinaryFile(Filename, FileData)

    ' Create File Info
    If Success Then
      FileInfo = finBL.CreateFileDownloadInfo()
      If FileInfo.LoadByteArray(FileData, finBL.Runtime.FileUtilities.GetFileName(Filename)) Then
        returnValue = FileInfo.ToXmlString()
      Else
        Success = False
      End If
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Tax Period Dropdown has changed.
''' &lt;/summary&gt;
Private Function Form_TaxPeriod_Change(ByRef returnValue As String) As Boolean

  Dim AILHasData As Boolean
  Dim Data As Object
  Dim NRWTHasData As Boolean
  Dim RWTHasData As Boolean
  Dim RWTDHasData As Boolean
  Dim Success As Boolean
  Dim TaxFileExport_Account As finTaxFileExport_Account
  Dim TaxFileExport_InvestmentIncomeReport_NZ As finTaxFileExport_InvestmentIncomeReport_NZ
  Dim TaxPeriodId As String

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    TaxPeriodId = .GetString("TaxPeriodId")
  End With

  ' Create Object
  Success = CreateTaxFileExport("ALL", TaxPeriodId, "", TaxFileExport_InvestmentIncomeReport_NZ)

  ' Record which Withholding Tax types are present
  For Each TaxFileExport_Account In TaxFileExport_InvestmentIncomeReport_NZ.TaxFileExport_Accounts
    With TaxFileExport_Account
      If .RWT_HasData AndAlso .RWT_IsValid Then RWTHasData = True
      If .RWTD_HasData AndAlso .RWTD_IsValid Then RWTDHasData = True
      If .NRWT_HasData AndAlso .NRWT_IsValid Then NRWTHasData = True
      If .AIL_HasData AndAlso .AIL_IsValid Then AILHasData = True
    End With
    If RWTHasData AndAlso RWTDHasData AndAlso NRWTHasData AndAlso AILHasData Then Exit For
  Next

  ' Add to Object
  If Success Then
    Data = New With {
      .HasRWT = RWTHasData,
      .HasRWTD = RWTDHasData,
      .HasNRWT = NRWTHasData,
      .HasAIL = AILHasData
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Entity's Tax Periods.
''' &lt;/summary&gt;
Private Function GetEntityTaxPeriods(entityRO As finEntityRO,
                                     ByRef entity As Entity) As Boolean

  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  entity = New Entity()
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Entity Details
  entity.EntityId = entityRO.EntityId
  entity.EntityName = entityRO.Name

  ' Get Tax Periods
  With sqb
    .Table = "TaxPeriod"
    .TopLimit = 16
    .Fields.Add("TaxPeriodId")

    ' SQL Where
    With .SqlWhere
      .AppendComparisonInteger("EntityPk", "=", entityRO.Pk)
    End With

    ' Order By
    .OrderByFields.Add("Pk", True)
  End With

  If sqb.ExecuteDisconnectedDataReader(dr) Then
    Do While dr.Read()
      entity.TaxPeriods.Add(finBL.Database.GetFieldString(dr!TaxPeriodId))
    Loop
    finBL.Database.DataReaderClose(dr)
  Else
    Success = False
  End If

  Return Success

End Function

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

  Dim dr As IDataReader
  Dim Entity As Entity
  Dim EntityPk As Integer
  Dim EntityRO As finEntityRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim sqb As ISSelectQueryBuilder
  Dim Success As Boolean
  Dim TaxPeriodId As String

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    TaxPeriodId = .GetString("TaxPeriodId")
  End With

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Validate
  If finBL.CountryCode &lt;&gt; "NZ" Then
    Success = False
    finBL.Error.ErrorBegin("Investment Income Reporting is only available in NZ databases.")
  ElseIf Not finBL.Settings.AddOns.DepositAccount Then
    Success = False
    finBL.Error.ErrorBegin("This database is not licenced for Deposit Accounts.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("WithholdingTax.TaxFileExport_InvestmentIncomeReport") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to run the Investment Income Report Export.")
  End If

  ' Build Object
  If Success Then
    With FormInitialisationInfo
      .HasInterestAsDividendAccountTypes = (finBL.AccountTypes.CountInterestIsFromDividends(True) &lt;&gt; 0)

      If Len(TaxPeriodId) = 0 Then
        ' No Tax Period specified so retreive
        For Each EntityRO In finBL.Entities
          If EntityRO.Active Then
            If GetEntityTaxPeriods(EntityRO, Entity) Then
              If Entity.TaxPeriods.Count &gt; 0 Then
                .Entities.Add(Entity)

                ' Set Default Entity
                If Len(TaxPeriodId) = 0 AndAlso EntityRO.Pk = finBL.CurrentUserInformation.EntityPk Then
                  .DefaultEntityId = EntityRO.EntityId
                  .DefaultEntityName = EntityRO.Name
                End If
              End If
            Else
              Success = False
              Exit For
            End If
          End If
        Next
      Else
        ' Tax Period specified
        sqb = finBL.Database.CreateSelectQueryBuilder()
        With sqb
          .Table = "TaxPeriod"
          .Fields.AddList("TaxPeriodId,EntityPk")

          ' SQL Where
          With .SqlWhere
            .AppendComparisonString("TaxPeriodId", "=", TaxPeriodId)
          End With
        End With

        ' Execute
        If sqb.ExecuteDisconnectedDataReader(dr) Then
          If dr.Read() Then
            EntityPk = finBL.Database.GetFieldInteger(dr!EntityPk)

            If finBL.Entities.ExistsPk(EntityPk) Then
              EntityRO = finBL.Entities.ItemByPk(EntityPk)
              .DefaultEntityId = EntityRO.EntityId
              .DefaultEntityName = EntityRO.Name
              .TaxPeriodId = TaxPeriodId
            Else
              Success = False
              finBL.Error.ErrorBegin("Invalid Tax Period.")
            End If
          Else
            Success = False
            finBL.Error.ErrorBegin("Invalid Tax Period.")
          End If

          ' Close DataReader
          finBL.Database.DataReaderClose(dr)
        Else
          Success = False
        End If
      End If
    End With
  End If

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

  Return Success

End Function



''' &lt;summary&gt;
'''  Form Initialisation Information.
''' &lt;/summary&gt;
Private Class FormInitialisationInfo

  Public DefaultEntityId As String
  Public DefaultEntityName As String
  Public Entities As New List(Of Entity)
  Public HasInterestAsDividendAccountTypes As Boolean
  Public TaxPeriodId As String

End Class



''' &lt;summary&gt;
'''  Entity Information.
''' &lt;/summary&gt;
Private Class Entity

  Public EntityId As String
  Public EntityName As String
  Public TaxPeriods As New List(Of String)

End Class</Code>
    <Language>VisualBasic</Language>
    <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;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 Tax Period Export options."&gt;Investment Income Report Export 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:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&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="lblTaxPeriod"&gt;Select the Tax Period to export&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboTaxPeriod"&gt;Tax Period:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboTaxPeriod" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;div id="divInactiveButtons" class="is-info-text info small" style="display:none"&gt;Inactive button(s) indicate the Tax Type is not applicable for this Tax Period.&lt;/div&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDownloadIPS"&gt;Resident Withholding Tax on Interest (IPS)&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;button id="cmdDownloadRWT" class="is-button ok" title="Resident Withholding Tax on Interest" style="width:140px;"&gt;Download RWTI&lt;/button&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbDownloadRWTD"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDownloadRWT"&gt;Resident Withholding Tax on Dividends (RWT)&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;button id="cmdDownloadRWTD" class="is-button ok" title="Resident Withholding Tax on Dividends" style="width:140px;"&gt;Download RWTD&lt;/button&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDownloadNRT"&gt;Non-Resident Withholding Tax (NRT)&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;button id="cmdDownloadNRWT" class="is-button ok" title="Non-Resident Withholding Tax" style="width:140px;"&gt;Download NRWT&lt;/button&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblDownloadAIL"&gt;Approved Issuer Levy (AIL)&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;button id="cmdDownloadAIL" class="is-button ok" title="Approved Issuer Levy" style="width:140px;"&gt;Download AILI&lt;/button&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdCancel" class="is-button"&gt;Close&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;


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

// Controls
var C = {
  lblEntity: null,
  cboEntity: null,

  lblTaxPeriod: null,
  cboTaxPeriod: null,

  lblDownloadIPS: null,
  tbDownloadRWTD: null,
  lblDownloadRWT: null,
  lblDownloadNRT: null,
  lblDownloadAIL: null,

  divInactiveButtons: null
}

// Form
var frmMain;
var tabWizard;

// Wizard Buttons
var cmdCancel;

var cmdDownloadRWT;
var cmdDownloadRWTD;
var cmdDownloadNRWT;
var cmdDownloadAIL;


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

  // Controls
  C.lblEntity = widget.UI.Label("lblEntity", {});
  C.cboEntity = widget.UI.DBCombo("cboEntity", {
    limitToList: true,
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    onChange: cboEntity_Change,
  });
  C.lblTaxPeriod = widget.UI.Label("lblTaxPeriod", {});
  C.cboTaxPeriod = widget.UI.ComboBox("cboTaxPeriod", {
    limitToList: true,
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,
    onChange: cboTaxPeriod_Change,
  });
  C.lblDownloadIPS = widget.UI.Label("lblDownloadIPS", {});
  C.tbDownloadRWTD = $("#tbDownloadRWTD");
  C.lblDownloadRWT = widget.UI.Label("lblDownloadRWT", {});
  C.lblDownloadNRT = widget.UI.Label("lblDownloadNRT", {});
  C.lblDownloadAIL = widget.UI.Label("lblDownloadAIL", {});

  C.divInactiveButtons = $("#divInactiveButtons");

  // 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");
  cmdCancel.click(tabWizard_Cancel);

  cmdDownloadRWT = $("#cmdDownloadRWT");
  cmdDownloadRWTD = $("#cmdDownloadRWTD");
  cmdDownloadNRWT = $("#cmdDownloadNRWT");
  cmdDownloadAIL = $("#cmdDownloadAIL");
  cmdDownloadRWT.click(function() { DownloadFile("RWT"); });
  cmdDownloadRWTD.click(function() { DownloadFile("RWTD"); });
  cmdDownloadNRWT.click(function() { DownloadFile("NRWT"); });
  cmdDownloadAIL.click(function() { DownloadFile("AIL"); });

  // Reset Form
  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;

  // 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() {
  var strTemp = "";

  if (mRecord) {
    // General
    C.cboEntity.Text(mRecord.DefaultEntityId);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

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

  // Lists

  // Controls
  if(mRecord) {
    // Default Tax Period
    if(mRecord.TaxPeriodId) {
      // Disable dropdown lists
      C.cboEntity.ReadOnly(true);
      C.cboTaxPeriod.ReadOnly(true);

      // Set Tax Period (and therefore Entity)
      C.cboEntity.RefreshUnbound(mRecord.DefaultEntityId, mRecord.DefaultEntityName);
      C.cboTaxPeriod.Text(mRecord.TaxPeriodId);
    }
    else {
      C.cboEntity.RefreshFromCollection(mRecord.Entities, "EntityId", "EntityName");
      cboEntity_Change();
    }

    // RWTD applicable?
    if (!mRecord.HasInterestAsDividendAccountTypes) {
      C.tbDownloadRWTD.hide();
    }

    cboTaxPeriod_Change();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// =============
// Download File
// =============
function DownloadFile(downloadType) {
  // Block UI
  widget.UI.Block("Generating file, please wait...");

  // Parameters
  var params = {
    downloadType: downloadType,
    taxPeriodId: C.cboTaxPeriod.Text(),
  }

  // Download File
  widget.DownloadFile("DownloadExport", params,
    // Success
    function() {
      // Unblock UI
      widget.UI.Unblock();
    },

    // Fail
    function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();

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

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

  if(C.cboEntity.Text()) {
    for(var i = 0; i &lt; mRecord.Entities.length; i++) {
      var item = mRecord.Entities[i];

      if(item.EntityId == C.cboEntity.Text()) {
        C.cboTaxPeriod.ListFromCsvString(item.TaxPeriods);
        C.cboTaxPeriod.Text(item.TaxPeriods[0]);

        cboTaxPeriod_Change();
        break;
      }
    }
  }
  else {
    C.cboTaxPeriod.ListFromCsvString("");
    C.cboTaxPeriod.Text("");
  }
}

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

  // Disable by default
  cmdDownloadRWT.attr("disabled", true);
  cmdDownloadRWTD.attr("disabled", true);
  cmdDownloadNRWT.attr("disabled", true);
  cmdDownloadAIL.attr("disabled", true);
  C.divInactiveButtons.hide();

  // Call back to see if selected Tax Period has items for each Withholding Tax Type
  if(C.cboTaxPeriod.Text()) {
    // Block UI
    widget.UI.Block("Getting Tax Period Information, please wait...");

    // Get Data
    widget.GetString("Form_TaxPeriod_Change", { taxPeriodId: C.cboTaxPeriod.Text() }, cboTaxPeriod_Change_Done, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();

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

function cboTaxPeriod_Change_Done(data) {
  var o = JSON.parse(data);

  // Set buttons
  if(o) {
    cmdDownloadRWT.attr("disabled", !o.HasRWT);
    cmdDownloadRWTD.attr("disabled", !o.HasRWTD);
    cmdDownloadNRWT.attr("disabled", !o.HasNRWT);
    cmdDownloadAIL.attr("disabled", !o.HasAIL);

    // If there are inactive buttons, add information message
    if(!o.HasRWT || (!o.HasRWTD &amp;&amp; mRecord.HasInterestAsDividendAccountTypes) || !o.HasNRWT || !o.HasAIL) {
      C.divInactiveButtons.show();
    }
  }

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

// ===========
// Form Resize
// ===========
function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

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

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

function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    default:
      break;
  }
}

function tabWizard_UpdateButtons() {
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>8dXfNo6qBEu7Rv0eNCyT3Q</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>700</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>700</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="TaxPeriodId" 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.TaxPeriods</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>