<?xml version="1.0" encoding="utf-8"?><finScript version="1.00" exportedUtcDate="2021-06-10T02:18:26.0000000"><CreatedUserId>ADMIN</CreatedUserId><CreatedUtcDate>2021-06-02T04:24:57.0330000</CreatedUtcDate><UpdatedUserId>ADMIN</UpdatedUserId><UpdatedUtcDate>2021-06-10T02:18:02.5930000</UpdatedUtcDate><ScriptId>CENTRIXPCBUR</ScriptId><Description>Centrix Commercial Data Upload Response</Description><ScriptType>HtmlWidget</ScriptType><Active>true</Active><AllowUI>false</AllowUI><Category /><Code>' HtmlWidget_CentrixNZ_CommercialDataUploadResponse
Option Explicit On
Option Strict On

' #################################################################
' Centrix (New Zealand) Commercial Data Upload Response
'
' Version: 1.00 (10/06/2021)
'
' Usage: System-defined HTML Widget
' #################################################################

' Constants
'#const "ArchiveFolder",String,"","The folder to move Response Files when they have been marked as Archived."
'#const "FTPFolder",String,"","The folder where the Centrix Commercial Data Upload Response Files are received."

' Script Constants
Private ArchiveFolder As String = ""
Private FTPFolder As String = ""

' Constants
Private Const FORM_KEY As String = "CentrixCommercialDataUploadResponse"

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

  ' Script Constants
  With ScriptInfo.Constants
    ArchiveFolder = .GetString("ArchiveFolder")
    FTPFolder = .GetString("FTPFolder")
  End With

  ' Ensure Folders have the trailing directory separator
  If Len(ArchiveFolder) &lt;&gt; 0 AndAlso Right(ArchiveFolder, 1) &lt;&gt; System.IO.Path.DirectorySeparatorChar Then
    ArchiveFolder &amp;= System.IO.Path.DirectorySeparatorChar
  End If
  If Len(FTPFolder) &lt;&gt; 0 AndAlso Right(FTPFolder, 1) &lt;&gt; System.IO.Path.DirectorySeparatorChar Then
    FTPFolder &amp;= System.IO.Path.DirectorySeparatorChar
  End If

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

    Case "ArchiveFile"
      ' Archive a file
      Main = ArchiveFile()

    Case "DirectFileUpload"
      ' Direct File Upload
      Main = DirectFileUpload(requestInfo, returnValue)

    Case "GetFileSummary"
      ' Get File Summary
      Main = GetFileSummary("", returnValue)

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

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

End Function

''' &lt;summary&gt;
'''  Archives a file.
''' &lt;/summary&gt;
Private Function ArchiveFile() As Boolean

  Dim Success As Boolean
  Dim Filename As String

  ' Assume Success
  Success = True

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

  ' Validate
  If (Len(ArchiveFolder) &lt;&gt; 0 AndAlso finBL.Runtime.FileUtilities.FolderExists(ArchiveFolder)) Then
    ' Ok
  Else
    Success = False
    finBL.Error.ErrorBegin("Archiving has been disabled as no valid archive path has been specified.")
  End If

  ' Validate Filename
  If Success Then
    If Not finBL.Runtime.FileUtilities.FileExists(FTPFolder &amp; Filename) Then
      Success = False
      finBL.Error.ErrorBegin("File has since been removed, cannot archive.")
    End If
  End If

  ' Move file
  If Success Then
    Success = finBL.Runtime.FileUtilities.MoveFile(FTPFolder &amp; Filename, ArchiveFolder &amp; Filename)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Generate Summary from a Direct File Upload.
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function DirectFileUpload(requestInfo As finScriptRequestInfo,
                                  ByRef returnValue As String) As Boolean

  Dim FileCreated As Boolean
  Dim Filename As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get full filename to temp path
  Filename = finBL.Runtime.FileUtilities.TempPath &amp; requestInfo.Files(0).FileName

  ' Create File
  If finBL.Runtime.FileUtilities.WriteFileFromByteArray(Filename, requestInfo.Files(0).FileData) Then
    FileCreated = True
  Else
    Success = False
  End If

  ' Get Summary
  If Success Then
    Success = GetFileSummary(Filename, returnValue)
  End If

  ' Clean up temp file
  If FileCreated Then
    If Not finBL.Runtime.FileUtilities.DeleteFile(Filename) Then
      ' Ignore error
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get a Files summary.
''' &lt;/summary&gt;
Private Function GetFileSummary(tempFileName As String,
                                ByRef returnValue As String) As Boolean

  Dim AccountId As String
  Dim AccountNode As XmlNode
  Dim BackgroundColour As String
  Dim Filename As String
  Dim HeaderNode As XmlNode
  Dim MessageNode As XmlNode
  Dim RootNode As XmlNode
  Dim SnapshotDateTime As Date
  Dim Success As Boolean
  Dim XmlDocument As XmlDocument
  Dim WizardFinishDetails As WizardFinishDetails

  ' Assume Success
  Success = True

  ' Initialise
  WizardFinishDetails = New WizardFinishDetails()

  ' Parameters
  If Len(tempFileName) = 0 Then
    ' File has been selected from the FTP list
    Filename = FTPFolder &amp; mCombinedParameters.GetString("Filename")
  Else
    ' File has been directly uploaded
    Filename = tempFileName
  End If

  ' Load and validate Document
  If finBL.Runtime.XmlUtilities.LoadXmlDocumentFromFile(Filename, XmlDocument) Then
    ' Load XML Document
    RootNode = XmlDocument.SelectSingleNode("//PositiveCommercialBureauResponse")

    If RootNode Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("Invalid file. 'PositiveCommercialBureauResponse' node not found.")
    Else
      ' Header
      HeaderNode = RootNode.SelectSingleNode("Header")

      If HeaderNode Is Nothing Then
        Success = False
        finBL.Error.ErrorBegin("Invalid file. 'PositiveCommercialBureauResponse/Header' node not found.")
      End If
    End If
  Else
    Success = False
  End If

  ' Add Header information
  If Success Then
    ' Get Snapshot Date and Time
    SnapshotDateTime = finBL.Runtime.DateUtilities.ConvertToDate(finBL.Runtime.XmlUtilities.GetSubNodeString(HeaderNode, "SnapshotDate"), "YMD")
    SnapshotDateTime = SnapshotDateTime.AddTicks(finBL.Runtime.DateUtilities.ConvertToTime(finBL.Runtime.XmlUtilities.GetSubNodeString(HeaderNode, "SnapshotTime")).Ticks())

    With WizardFinishDetails
      .Filename = finBL.Runtime.FileUtilities.GetFileName(Filename)
      .SubscriberCode = finBL.Runtime.XmlUtilities.GetSubNodeString(HeaderNode, "SubscriberCode")
      .Date = finBL.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(SnapshotDateTime)
      .RecordsReceived = finBL.Runtime.XmlUtilities.GetSubNodeInteger(HeaderNode, "RecordsReceived")
      .RecordsSuccessful = finBL.Runtime.XmlUtilities.GetSubNodeInteger(HeaderNode, "RecordsSuccessfullyProcessed")
      .RecordsNotProcessed = finBL.Runtime.XmlUtilities.GetSubNodeInteger(HeaderNode, "RecordsNotProcessed")
      .RecordsLinked = finBL.Runtime.XmlUtilities.GetSubNodeInteger(HeaderNode, "RecordsSuccessfullyLinked")
      .RecordsNotLinked = finBL.Runtime.XmlUtilities.GetSubNodeInteger(HeaderNode, "RecordsNotLinked")
    End With
  End If

  ' Accounts
  If Success Then
    For Each AccountNode In RootNode.SelectNodes("Accounts/Account")
      ' Get Account Id
      AccountId = finBL.Runtime.XmlUtilities.GetSubNodeString(AccountNode, "AccountId")

      ' Set Background Colour
      If BackgroundColour = "" OrElse BackgroundColour = "#f8f8f8" Then
        BackgroundColour = "white"
      Else
        BackgroundColour = "#f8f8f8"
      End If

      ' Messages
      For Each MessageNode In AccountNode.SelectNodes("Messages/Message")
        With finBL.Runtime.XmlUtilities
          WizardFinishDetails.WizardFinishDetailAccounts.Add(New WizardFinishDetailAccount(AccountId, .GetSubNodeString(MessageNode, "Category"), .GetSubNodeString(MessageNode, "ActionRequired"), .GetSubNodeString(MessageNode, "ErrorCode"), .GetSubNodeString(MessageNode, "ErrorText"), BackgroundColour))
        End With

        ' Only display the Account Id for the first Account
        'AccountId = ""
      Next
    Next
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(WizardFinishDetails, returnValue)
  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 FileCount As Integer
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim ResponseFileList As ISList
  Dim Success As Boolean
  Dim AllowFtpFolderSelection As Boolean

  ' Assume Success
  Success = True

  ' Parameters

  ' Initialise
  FormInitialisationInfo = New FormInitialisationInfo()

  ' Determine if the FTP folder should be read
  AllowFtpFolderSelection = (Not finBL.IsRunningFromWeb AndAlso Len(FTPFolder) &lt;&gt; 0)

  ' Validate
  If finBL.CountryCode &lt;&gt; "NZ" Then
    Success = False
    finBL.Error.ErrorBegin("The Centrix Commercial Data Upload is only available in NZ databases.")
  ElseIf AllowFtpFolderSelection AndAlso Len(FTPFolder) &lt;&gt; 0 AndAlso Not finBL.Runtime.FileUtilities.FolderExists(FTPFolder) Then
    Success = False
    finBL.Error.ErrorBegin("A valid Centrix FTP Response Folder must be configured as a Constant to use this utility.")
  ElseIf AllowFtpFolderSelection AndAlso Len(FTPFolder) &lt;&gt; 0 AndAlso StrComp(FTPFolder, ArchiveFolder, CompareMethod.Text) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("The Archive folder cannot be the same directory as the source FTP folder.")
  End If

  ' Get File List and Validate
  If Success AndAlso AllowFtpFolderSelection Then
    If finBL.Runtime.FileUtilities.GetFileList(FTPFolder, ResponseFileList, "*.xml", False) Then
      FileCount = ResponseFileList.Count
    Else
      Success = False
    End If
  End If

  ' Build Object
  If Success Then
    With FormInitialisationInfo
      ' Record
      If FileCount &lt;&gt; 0 Then
        .ResponseFiles = ResponseFileList.ToJsonObject()
      End If

      ' Configuration
      .IsRunningFromWeb = (finBL.IsRunningFromWeb OrElse FileCount = 0)
      .AllowArchive = (Not .IsRunningFromWeb AndAlso Len(ArchiveFolder) &lt;&gt; 0 AndAlso finBL.Runtime.FileUtilities.FolderExists(ArchiveFolder))

      ' Form Heading
      .FormHeading = ScriptInfo.ScriptCaption
      If Len(.FormHeading) = 0 Then .FormHeading = "Centrix Commercial Data Upload Response"
    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

  ' Record
  Public ResponseFiles As Object

  ' Configuration
  Public AllowArchive As Boolean
  Public FormHeading As String
  Public IsRunningFromWeb As Boolean

End Class



''' &lt;summary&gt;
'''  Wizard Finish Details.
''' &lt;/summary&gt;
Private Class WizardFinishDetails

  Public Filename As String
  Public SubscriberCode As String
  Public [Date] As Date
  Public RecordsReceived As Integer
  Public RecordsSuccessful As Integer
  Public RecordsNotProcessed As Integer
  Public RecordsLinked As Integer
  Public RecordsNotLinked As Integer
  Public WizardFinishDetailAccounts As New List(Of WizardFinishDetailAccount)

End Class



''' &lt;summary&gt;
'''  Wizard Finish Detail Account.
''' &lt;/summary&gt;
Private Class WizardFinishDetailAccount

  Public AccountId As String
  Public Category As String
  Public Action As String
  Public Code As String
  Public ErrorMessage As String
  Public GridBackgroundColour As String

  Public Sub New(accountId As String,
                 category As String,
                 action As String,
                 code As String,
                 errorMessage As String,
                 gridBackgroundColour As String)

    Me.AccountId = accountId
    Me.Category = category
    Me.Action = action
    Me.Code = code
    Me.ErrorMessage = errorMessage
    Me.GridBackgroundColour = gridBackgroundColour

  End Sub

End Class</Code><Language>VisualBasic</Language><Notes>System defined HTML Widget.

Used to import a "Centrix (New Zealand)" Centrix Commercial Data Upload Response.

Configuration of the FTP Response folder is required before this HTML Widget can be used.</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 a file below to view the export response provided by Centrix."&gt;Centrix Commercial Data Upload Response&lt;/li&gt;
        &lt;li tabId="Response" tooltipText="Centrix Commercial Response File."&gt;Centrix Commercial Data Upload Response&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:4em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblFilename"&gt;Select a Response File to view&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="gridFiles"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblViewDirectFile"&gt;Or, browse for a Response File to view&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;
            &lt;label for="fileDirectFile"&gt;Only a valid Centrix Commercial Data Upload Response file will be processed.&lt;/label&gt;
            &lt;input id="fileDirectFile" type="file" accept=".xml" field-type="file" max-files="1" /&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Response --&gt;
    &lt;div id="pageResponse"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:16em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblResponse"&gt;Response Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFilename"&gt;File:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFilename" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtSubscriberCode"&gt;Subscriber Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtSubscriberCode" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateResponse"&gt;Date / Time:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateResponse" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numRecordsReceived"&gt;Records Received:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRecordsReceived" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numRecordsSuccessful"&gt;Records Successfully Processed:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRecordsSuccessful" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numRecordsNotProcessed"&gt;Records Not Processed:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRecordsNotProcessed" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numRecordsLinked"&gt;Records Successfully Linked:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRecordsLinked" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numRecordsNotLinked"&gt;Records Not Linked:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numRecordsNotLinked" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblResponseAccounts"&gt;Accounts&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;

      &lt;!-- Accounts Grid --&gt;
      &lt;div id="gridAccounts"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdArchive" class="is-button" style="float:left"&gt;Archive Selected File&lt;/button&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;Finish&lt;/button&gt;
  &lt;/footer&gt;
&lt;/div&gt;


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

// Controls
var C = {
  //   General
  lblFilename: null,
  gridFiles: null,

  lblViewDirectFile: null,

  //   Response
  lblResponse: null,
  txtFilename: null,
  txtSubscriberCode: null,
  dateResponse: null,
  numRecordsReceived: null,
  numRecordsSuccessful: null,
  numRecordsNotProcessed: null,
  numRecordsLinked: null,
  numRecordsNotLinked: null,

  lblResponseAccounts: null,
  gridAccounts: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdArchive;

// Other
var mFileData;
var mIsDirectFile;

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

  // Controls
  //   General
  C.lblFilename = widget.UI.Label("lblFilename", {});
  C.lblViewDirectFile = widget.UI.Label("lblViewDirectFile", {});

  // Special handling for File Upload change event
  $(document).on("input", "input:file", function(e) {
    var files = e.target.files;

    if (files &amp;&amp; files.length != 0) {
      // File has been uploaded directly
      DirectFileUpload();
    }
  });

  //   Response
  C.lblResponse = widget.UI.Label("lblResponse", {});
  C.txtFilename = widget.UI.TextBox("txtFilename", {
    readOnly: true,
  });
  C.txtSubscriberCode = widget.UI.TextBox("txtSubscriberCode", {
    readOnly: true,
    width: "190px",
  });
  C.dateResponse = widget.UI.DateBox("dateResponse", {
    allowTime: true,
    readOnly: true,
  });
  C.numRecordsReceived = widget.UI.NumberBox("numRecordsReceived", {
    decimals: 0,
    readOnly: true,
    width: "80px",
  });
  C.numRecordsSuccessful = widget.UI.NumberBox("numRecordsSuccessful", {
    decimals: 0,
    readOnly: true,
    width: "80px",
  });
  C.numRecordsNotProcessed = widget.UI.NumberBox("numRecordsNotProcessed", {
    decimals: 0,
    readOnly: true,
    width: "80px",
  });
  C.numRecordsLinked = widget.UI.NumberBox("numRecordsLinked", {
    decimals: 0,
    readOnly: true,
    width: "80px",
  });
  C.numRecordsNotLinked = widget.UI.NumberBox("numRecordsNotLinked", {
    decimals: 0,
    readOnly: true,
    width: "80px",
  });

  C.lblResponseAccounts = widget.UI.Label("lblResponseAccounts", {
    tooltipText: "Legend\n\nAction Required\nN=None\nC=Correct error and re-submit\nR=Review error and re-submit if necessary\nB=Contact Credit Reporter",
  });

  // Grids
  C.gridFiles = widget.UI.Grid("gridFiles", {
    onAfterRowActivate: gridFiles_AfterRowActivate,
    onInitialiseRow: gridFiles_InitialiseRow,
    onRowDrilldown: gridFiles_RowDrilldown,
  });
  C.gridAccounts = widget.UI.Grid("gridAccounts", {
    allowCellSelect: false,
    rowNumbering: true,

    onInitialiseRow: gridAccounts_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
  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("Cancel"); });

  cmdArchive = $("#cmdArchive");
  cmdArchive.click(function() { Form_ExecuteAction("Archive"); });

  // 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;
  mFileData = 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) {
      // Unblock
      widget.UI.Unblock();

      // Special case - close HTML Widget on error
      widget.UI.MsgBoxAlert("fail: " + message, {}, tabWizard_Cancel);
    }
  );
}

// ===========
// Fields Load
// ===========
function Fields_Load() {
  var strTemp = "";

  if (mRecord) {
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh(0);
}

// =============
// Fields Update
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    widget.SetHeading(mRecord.FormHeading);
  }

  // Information Lists

  // Lists
  if (mRecord) {
  }

  // Controls
  if(mRecord) {
    if (mRecord.IsRunningFromWeb) {
      C.lblFilename.VisibleRow(false);
      C.gridFiles.Visible(false);

      C.lblViewDirectFile.Text("Select a Response File to view");
    }
    else {
      // Configure Grid
      gridFiles_Refresh();
    }
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "ARCHIVE":
      // Archive a file
      Form_ExecuteAction_Archive();
      break;

    case "CANCEL":
      // Cancel
      tabWizard_Cancel();
      break;

    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

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

// ==============
// Archive Action
// ==============
function Form_ExecuteAction_Archive() {
  widget.UI.MsgBoxConfirm("Are you sure you want to archive file '" + mRecord.ResponseFiles[C.gridFiles.ActiveDataRowListIndex()] + "'?", {}, Form_ExecuteAction_ArchivePost);
}

function Form_ExecuteAction_ArchivePost() {
  // Block UI
  widget.UI.Block("Archiving, please wait...");

  // Params
  var params = {
    filename: mRecord.ResponseFiles[C.gridFiles.ActiveDataRowListIndex()],
  }

  // Archive
  widget.GetString("ArchiveFile", params,
    function() {
      // Reset Form
      Form_Reset();
    },

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

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

// ==========
// 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_Refresh(newTab) {
  // Moving forward onto tab, so Load information
  if (newTab &gt;= tabWizard.SelectedTabIndex()) {
    switch (tabWizard.GetTabIdByIndex(newTab)) {
      case "Response":
        pageResponse_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
    case "General":
      // Reset Direct File flag
      mIsDirectFile = false;

      // Always attempt to reset manual file upload
      $(".is-file-upload &gt; div &gt; div &gt; button.is-button").click();
      break;

    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()) {
    case "Response":
      C.txtFilename.WidthResizeFromParent();
      break;

    default:
      break;
  }
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (C.gridFiles.ActiveDataRowIndex() == -1) {
          Ok = false;
          widget.UI.MsgBoxAlert("You must select a valid response file to view.");
        }
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      default:
        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
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

function tabWizard_UpdateButtons() {
  var tabIndex = tabWizard.SelectedTabIndex();

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

  // Archive handling
  if (mRecord.AllowArchive &amp;&amp; !mIsDirectFile) {
    cmdArchive.show();
    cmdArchive.prop("disabled", C.gridFiles.ActiveDataRowIndex() == -1);
  }
  else {
    cmdArchive.hide();
  }

  // Tweaks
  cmdCancel.hide();
  cmdFinish.html("Close");
}

// ==================
// Direct File Upload
// ==================
function DirectFileUpload() {
  // Block UI
  widget.UI.Block("Importing file, please wait...");

  // Direct File Upload
  mIsDirectFile = true;

  // Upload File
  widget.UploadFiles("DirectFileUpload", {}, fileDirectFile,
    function(data) {
      // Show Summary
      mFileData = JSON.parse(data);

      // Move page (skipping validation)
      tabWizard_MovePost(1);

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

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

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

// ============
// pageResponse
// ============
function pageResponse_Refresh() {
  if (mIsDirectFile &amp;&amp; mFileData) {
    // Data already retrieved from a direct file upload
    pageResponse_Refresh_Done();
  }
  else {
    // Block UI
    widget.UI.Block("Getting Response Information, please wait...");

    // Params
    var params = {
      filename: mRecord.ResponseFiles[C.gridFiles.ActiveDataRowListIndex()],
    }

    // Get HTML
    widget.GetString("GetFileSummary", params,
      function(data) {
        mFileData = JSON.parse(data);

        // Configure Page
        pageResponse_Refresh_Done();

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

      function(errorMessage) {
        // Move back to General page
        tabWizard_Move(-1);

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

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

function pageResponse_Refresh_Done() {
  // Populate Fields
  if (mFileData) {
    C.txtFilename.Text(mFileData.Filename);
    C.txtSubscriberCode.Text(mFileData.SubscriberCode);
    C.dateResponse.Value(mFileData.Date);
    C.numRecordsReceived.Value(mFileData.RecordsReceived);
    C.numRecordsSuccessful.Value(mFileData.RecordsSuccessful);
    C.numRecordsNotProcessed.Value(mFileData.RecordsNotProcessed);
    C.numRecordsLinked.Value(mFileData.RecordsLinked);
    C.numRecordsNotLinked.Value(mFileData.RecordsNotLinked);
  }

  // Refresh Grid
  gridAccounts_Refresh();
}

// =========
// gridFiles
// =========
function gridFiles_Refresh() {
  // Add Columns
  C.gridFiles.ClearColumns();
  C.gridFiles.AddColumnString("Filename", { caption: "Response Files" });

  // Refresh
  C.gridFiles.VirtualDataRefresh(mRecord.ResponseFiles);
}

function gridFiles_AfterRowActivate(e) {
  tabWizard_UpdateButtons();
}

function gridFiles_InitialiseRow(e) {
  var item = mRecord.ResponseFiles[e.row.listIndex];

  // Update cells
  e.row.cells.Filename.value = item;
}

function gridFiles_RowDrilldown(e) {
  tabWizard_Move(1);
}

// ============
// gridAccounts
// ============
function gridAccounts_Refresh() {
  // Add Columns
  C.gridAccounts.ClearColumns();
  C.gridAccounts.AddColumnString("AccountId", { caption: "Account" });
  C.gridAccounts.AddColumnString("Category", { caption: "Category" });
  C.gridAccounts.AddColumnString("Action", { caption: "Action" });
  C.gridAccounts.AddColumnString("Code", { caption: "Code" });
  C.gridAccounts.AddColumnString("ErrorMessage", { caption: "Error" });

  // Refresh
  C.gridAccounts.VirtualDataRefresh(mFileData.WizardFinishDetailAccounts);
}

function gridAccounts_InitialiseRow(e) {
  var item = mFileData.WizardFinishDetailAccounts[e.row.listIndex];

  // Automatic data binding
  e.row.AutoBind(item);

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

  // Text Colour
  if (item.Category.toUpperCase() == "SEVERE") {
    e.row.colour = "red";
  }

  // Background Colour
  e.row.backgroundColour = item.GridBackgroundColour;

  // Tooltip
  switch (item.Action.toUpperCase()) {
    case "N":
      e.row.cells.Action.tooltipText = "None";
      break;

    case "C":
      e.row.cells.Action.tooltipText = "Correct error and re-submit";
      break;

    case "R":
      e.row.cells.Action.tooltipText = "Review error and re-submit if necessary";
      break;

    case "B":
      e.row.cells.Action.tooltipText = "Contact Credit Reporter";
      break;
  }
}
&lt;/script&gt;</TemplateText><TemplateTextBookmarks /><TimeoutSeconds>60</TimeoutSeconds><UniqueId>IEUs8vmYJkW9FVDF97i7SQ</UniqueId><AllowRefresh>true</AllowRefresh><Caption /><HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight><HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth><HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling><HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2><HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget><HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery><HtmlWidgetResourceJQueryVersion /><Icon /><JavaScriptDebugger>None</JavaScriptDebugger><RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled><RunAsAdministrator>false</RunAsAdministrator><WebServiceName /><WebServiceAllowAnonymous>false</WebServiceAllowAnonymous><WebServiceSendDebugInformation>false</WebServiceSendDebugInformation><ShowInMenu>None</ShowInMenu><ParametersType>None</ParametersType><Constants><ISScriptConstants version="1.00"><ScriptConstant name="ArchiveFolder" constantType="String"><Notes>The folder to move Response Files when they have been marked as Archived.</Notes><Value /><Encrypt>false</Encrypt></ScriptConstant><ScriptConstant name="FTPFolder" constantType="String"><Notes>The folder where the Centrix Commercial Data Upload Response Files are received.</Notes><Value /><Encrypt>false</Encrypt></ScriptConstant></ISScriptConstants></Constants></finScript>