<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-04T21:24:33.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2024-09-03T03:28:48.3300000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2024-09-04T21:20:47.2370000</UpdatedUtcDate>
    <ScriptId>HWCCAplyId</ScriptId>
    <Description>Cost Centre Edit (APLYiD)</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_CostCentreEdit_Aply
Option Explicit On
Option Strict On

' #################################################################
' Cost Centre Edit (APLYiD) form HTML Widget
'
' Copyright (C) Intersoft Systems Limited 2024
'
' Version: 1.01 (05/09/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  28/05/2024  ISS      J033580   Created
'          11/06/2024  ISS      J033649   Removed Duplicate Record Id, validating CostCentreId
'          17/07/2024  ISS      J033899   Showing/Hiding controls based on checkbox selection
'    1.01  05/09/2024  ISS      J034214   Added option for Fraud Analytics to Verify product
' #################################################################

' Constants
Private Const FORM_KEY As String = "CostCentres"

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

' Standard Parameters
Private mCostCentreId As String
Private mPage As String
Private mReadOnly As Boolean

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

  ' Assume Success
  Main = True

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

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

  ' Get Standard Parameters
  With mStartupParameters
    mCostCentreId = .GetString("CostCentreId") ' Always use Startup Parameters since the Cost Centre Id may be updated
    If Len(mCostCentreId) = 0 Then mCostCentreId = .GetString("Id")
  End With
  With mCombinedParameters
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

  ' Validate
  If Not finBL.HtmlWidgetUtilities.HasPermissionToViewFormKey(FORM_KEY) Then
    Main = False
  ElseIf Not finBL.CostCentreFunctions.IsServiceAvailable("Aply") Then
    Main = False
    finBL.Error.ErrorBegin("This service is not available.")
  ElseIf Len(mCostCentreId) = 0 Then
    Main = False
    finBL.Error.ErrorBegin("Cost Centre Id not specified.")    
  End If

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

      Case "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, returnValue)

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

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

End Function

''' &lt;summary&gt;
'''  Load Cost Centre.
''' &lt;/summary&gt;
Private Function GetCostCentre(ByRef costCentre As finCostCentre) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Cost Centre
  If Success Then
    ' Create Cost Centre
    costCentre = finBL.CreateCostCentre()

    ' Load Cost Centre
    Success = CostCentre.Load(mCostCentreId)
  End If

  Return Success

End Function

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

  Dim CostCentre As finCostCentre
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Get Cost Centre
  If Success Then
    Success = GetCostCentre(CostCentre)
  End If

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

      ' Record
      .CostCentreId = CostCentre.CostCentreId
      .Pk = CostCentre.Pk
      .Timestamp = CostCentre.Timestamp

      ' Page Permissions (defined here since they are used below)
      ' NOTE: Not applicable to this form

      ' Service
      .UseService = CostCentre.Aply.UseService
      
      ' Credentials
      .ApiKeyProduction = CostCentre.Aply.CredentialsProduction.ApiKey
      .ApiSecretProduction = CostCentre.Aply.CredentialsProduction.ApiSecret
      .BearerTokenProduction = CostCentre.Aply.CredentialsProduction.WebhookBearerToken
      .RequestUrlProduction = CostCentre.Aply.CredentialsProduction.RequestUrl
      .RequestUrlProductionBlankTip = ISServiceAply.DefaultRequestUrl
      
      ' Test Credentials
      .ApiKeyTest = CostCentre.Aply.CredentialsTest.ApiKey
      .ApiSecretTest = CostCentre.Aply.CredentialsTest.ApiSecret
      .BearerTokenTest = CostCentre.Aply.CredentialsTest.WebhookBearerToken
      .RequestUrlTest = CostCentre.Aply.CredentialsTest.RequestUrl
      .RequestUrlTestBlankTip = ISServiceAply.DefaultRequestUrlTest
      
      ' Options
      .AddClientImage = CostCentre.Aply.OptionsCreditEnquiry.ClientImageAdd
      .AddIdentificationItem = CostCentre.Aply.OptionsCreditEnquiry.ClientIdentificationAdd
      .DefaultProduct = CostCentre.Aply.OptionsCreditEnquiry.DefaultProduct
      .IncludeFraudAnalytics = CostCentre.Aply.OptionsCreditEnquiry.IncludeFraudAnalytics
      .EnableCreditEnquiry = CostCentre.Aply.OptionsCreditEnquiry.EnableCreditEnquiry 
      .FlowType = CostCentre.Aply.OptionsCreditEnquiry.DefaultFlowTypeText
      .SaveDownloadedImages = CostCentre.Aply.OptionsCreditEnquiry.ClientDownloadImages 
      .UpdateClientImage = CostCentre.Aply.OptionsCreditEnquiry.ClientImageUpdate
      .WebhookUrl = finBL.CreditBureau.Service_Aply.SuggestedWebhookUrl

      ' Permissions

      ' Lists
      .ListFlowTypes = finBL.CreditBureau.Enums.iseCreditBureau_Aply_FlowType_GetList()      
      .ListProducts = finBL.CreditBureau.GetServiceProductIdsList("Aply", iseProductClass.CreditEnquiry, iseProductTarget.Individual, False).ToList()
      
      ' Configuration
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      Select Case UCase(finBL.CountryCode)
        Case "AU"
          .ShowFlowType = True
          
        Case Else
          .ShowFlowType = False
          
      End Select
    End With
  End If

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

  Return Success

End Function

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

  Dim CostCentre As finCostCentre
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Cost Centre
  If Success Then
    Success = GetCostCentre(CostCentre)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; CostCentre.Timestamp Then
      Success = False
      finBL.Error.ErrorBegin("This record has been updated by another User.")
    End If
  End If

  ' Update and Save
  If Success Then
    ' Begin Transaction
    If finBL.Database.TransactionBegin() Then
      ' Update Cost Centre
      With CostCentre.Aply
        ' Service
        .UseService = Record.UseService
        
        ' Credentials
        With .CredentialsProduction
          .ApiKey = Record.ApiKeyProduction
          .ApiSecret = Record.ApiSecretProduction
          .WebhookBearerToken = Record.BearerTokenProduction
          .RequestUrl = Record.RequestUrlProduction
        End With
          
        ' Test Credentials
        With .CredentialsTest
          .ApiKey = Record.ApiKeyTest
          .ApiSecret = Record.ApiSecretTest
          .WebhookBearerToken = Record.BearerTokenTest
          .RequestUrl = Record.RequestUrlTest
        End With
        
        ' Options
        With .OptionsCreditEnquiry
          .ClientDownloadImages = Record.SaveDownloadedImages    
          .ClientIdentificationAdd = Record.AddIdentificationItem
          .ClientImageAdd = Record.AddClientImage          
          .ClientImageUpdate = Record.UpdateClientImage
          .DefaultFlowTypeText = Record.FlowType          
          .DefaultProduct = Record.DefaultProduct
          .EnableCreditEnquiry = Record.EnableCreditEnquiry
          .IncludeFraudAnalytics = Record.IncludeFraudAnalytics
        End With
      End With

      ' Save
      If Success Then
        Success = CostCentre.Save()
      End If

      ' Commit/ Rollback Transaction
      If Success Then
        finBL.Database.TransactionCommit()
      Else
        finBL.Database.TransactionRollback()
      End If
    Else
      Success = False
    End If
  End If

  Return Success

End Function



''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
''' &lt;remarks&gt;
'''  This object is also used to save the Employment.
''' &lt;/remarks&gt;
Public Class FormInitialisationInfo

  ' Form
  Public PageId As String
  Public [ReadOnly] As Boolean

  ' Record
  Public CostCentreId As String
  Public Pk As Integer
  Public Timestamp As Integer

  ' Service
  Public UseService As Boolean
  
  ' Credentials
  Public ApiKeyProduction As String
  Public ApiSecretProduction As String
  Public BearerTokenProduction As String
  Public RequestUrlProduction As String  
  Public RequestUrlProductionBlankTip As String
  
  ' Test Credentials
  Public ApiKeyTest As String
  Public ApiSecretTest As String
  Public BearerTokenTest As String
  Public RequestUrlTest As String   
  Public RequestUrlTestBlankTip As String
  
  ' Options
  Public AddClientImage As Boolean  
  Public AddIdentificationItem As Boolean
  Public DefaultProduct As String  
  Public EnableCreditEnquiry As Boolean
  Public FlowType As String
  Public IncludeFraudAnalytics As Boolean
  Public SaveDownloadedImages As Boolean
  Public UpdateClientImage As Boolean
  Public WebhookUrl As String
  
  ' Permissions

  ' Lists
  Public ListFlowTypes As ISList  
  Public ListProducts As ISList

  ' Configuration
  Public PromptOnSave As Boolean
  Public ShowFlowType As Boolean

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to edit the "APLYiD" page of a Cost Centre.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="Service"&gt;Service&lt;/li&gt;
        &lt;li tabId="Credentials"&gt;Credentials&lt;/li&gt;
        &lt;li tabId="TestCredentials"&gt;Test Credentials&lt;/li&gt;
        &lt;li tabId="Options"&gt;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;!-- Service --&gt;
    &lt;div id="pageService"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblService"&gt;Use the APLYiD Service?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUseService" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
  
    &lt;!-- Credentials --&gt;
    &lt;div id="pageCredentials"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRequestUrlProduction"&gt;Production Service Request URL&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRequestUrlProduction"&gt;Request URL:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRequestUrlProduction"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCredentialsProduction"&gt;Production API Credentials&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtApiKeyProduction"&gt;API Key:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtApiKeyProduction"/&gt;&lt;/td&gt;
        &lt;/tr&gt;        
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtApiSecretProduction"&gt;API Secret:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtApiSecretProduction"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCallbackConfigurationProduction"&gt;Production Callback Configuration&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;        
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtBearerTokenProduction"&gt;Bearer Token:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtBearerTokenProduction"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Test Credentials --&gt;
    &lt;div id="pageTestCredentials"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRequestUrlTest"&gt;Test Service Request URL&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRequestUrlTest"&gt;Request URL:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRequestUrlTest"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCredentialsTest"&gt;Test API Credentials&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtApiKeyTest"&gt;API Key:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtApiKeyTest"/&gt;&lt;/td&gt;
        &lt;/tr&gt;        
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtApiSecretTest"&gt;API Secret:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtApiSecretTest"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCallbackConfigurationTest"&gt;Test Callback Configuration&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;             
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtBearerTokenTest"&gt;Bearer Token:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtBearerTokenTest"/&gt;&lt;/td&gt;
        &lt;/tr&gt;        
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Options --&gt;
    &lt;div id="pageOptions"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOptionsCreditEnquiry"&gt;Credit Enquiry options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkEnableCreditEnquiry" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboProduct"&gt;Default&amp;nbsp;Product:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboProduct"/&gt;&lt;/td&gt;        
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkIncludeFraudAnalytics" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;       
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOptionsVerification"&gt;Verification options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboFlowType"&gt;Flow Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboFlowType"/&gt;&lt;/td&gt;        
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblWebhookUrl"&gt;Suggested Webhook URL&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtWebhook"&gt;Webhook:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtWebhook"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOptionsClient"&gt;Client options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;     
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkSaveDownloadedImages" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAddClientImage" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUpdateClientImage" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAddIdentificationItem" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&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;Cancel&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Save&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


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

var mOriginalJson;

// Controls
var C = {
  //   Service
  lblService: null,
  chkUseService: null,
  
  //   Credentials
  lblRequestUrlProduction: null,
  txtRequestUrlProduction: null,
  
  lblCredentialsProduction: null,
  txtApiKeyProduction: null,
  txtApiSecretProduction: null,
  
  lblCallbackConfigurationProduction: null,
  txtBearerTokenProduction: null,

  //   Test Credentials
  lblRequestUrlTest: null,
  txtRequestUrlTest: null,
  
  lblCredentialsTest: null,
  txtApiKeyTest: null,
  txtApiSecretTest: null,

  lblCallbackConfigurationTest: null,
  txtBearerTokenTest: null,
  
  //   Options
  lblOptionsCreditEnquiry: null,
  chkEnableCreditEnquiry: null,
  cboProduct: null,
  chkIncludeFraudAnalytics: null,
  
  lblOptionsVerification: null,
  cboFlowType: null,
  
  lblWebhookUrl: null,
  txtWebhook: null,
  
  lblOptionsClient: null,
  chkSaveDownloadedImages: null,
  chkAddClientImage: null,
  chkUpdateClientImage: null,
  chkAddIdentificationItem: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

// Other

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

  // --------
  // Controls
  // --------
  //   Service
  C.lblService = widget.UI.Label("lblService", {});
  C.chkUseService = widget.UI.CheckBox("chkUseService", {
    caption: "Use Service?",
    
    onChange: chkUseService_Change,
  });
  
  //   Credentials
  C.lblRequestUrlProduction = widget.UI.Label("lblRequestUrlProduction", {});
  C.txtRequestUrlProduction = widget.UI.TextBox("txtRequestUrlProduction", {
    maxLength: 200,
  });
  
  C.lblCredentialsProduction = widget.UI.Label("lblCredentialsProduction", {});
  C.txtApiKeyProduction = widget.UI.TextBox("txtApiKeyProduction", {
    maxLength: 50,
  });
  C.txtApiSecretProduction = widget.UI.TextBox("txtApiSecretProduction", {
    maxLength: 50,
    password: true,
    passwordRevealOnFocus: true,
  });  
  
  C.lblCallbackConfigurationProduction = widget.UI.Label("lblCallbackConfigurationProduction", {});
  C.txtBearerTokenProduction = widget.UI.TextBox("txtBearerTokenProduction", {
    maxLength: 100,
  });
  
  //   Test Credentials
  C.lblRequestUrlTest = widget.UI.Label("lblRequestUrlTest", {});
  C.txtRequestUrlTest = widget.UI.TextBox("txtRequestUrlTest", {
    maxLength: 200,
  });
  
  C.lblCredentialsTest = widget.UI.Label("lblCredentialsTest", {});
  C.txtApiKeyTest = widget.UI.TextBox("txtApiKeyTest", {
    maxLength: 50,
  });
  C.txtApiSecretTest = widget.UI.TextBox("txtApiSecretTest", {
    maxLength: 50,
    password: true,
    passwordRevealOnFocus: true,
  });  
  
  C.lblCallbackConfigurationTest = widget.UI.Label("lblCallbackConfigurationTest", {});
  C.txtBearerTokenTest = widget.UI.TextBox("txtBearerTokenTest", {
    maxLength: 100,
  });
  
  //   Options
  C.lblOptionsCreditEnquiry = widget.UI.Label("lblOptionsCreditEnquiry", {});
  C.chkEnableCreditEnquiry = widget.UI.CheckBox("chkEnableCreditEnquiry", {
    caption: "Enable Credit Enquiry?",
    
    onChange: chkEnableCreditEnquiry_Change,
  });
  C.cboProduct = widget.UI.ComboBox("cboProduct", {
    limitToList: true
  });  
  C.chkIncludeFraudAnalytics = widget.UI.CheckBox("chkIncludeFraudAnalytics", {
    caption: "Include 'Fraud Analytics' data?"
  });
  
  C.lblOptionsVerification = widget.UI.Label("lblOptionsVerification", {});
  C.cboFlowType = widget.UI.ComboBox("cboFlowType", {
    limitToList: true,
    allowBlank: false
  });
  
  C.lblWebhookUrl = widget.UI.Label("lblWebhookUrl", {
    tooltipText: "Change the Base URL in Global Settings, Web, Base URL. Then Copy and paste the suggested URL into your APLYiD Developers page, under Web hook configuration."
  });
  // This is an internal URL and should always be read-only
  C.txtWebhook = widget.UI.TextBox("txtWebhook", {
    readOnly: true
  });
  
  C.lblOptionsClient = widget.UI.Label("lblOptionsClient", {});
  C.chkSaveDownloadedImages = widget.UI.CheckBox("chkSaveDownloadedImages", {
    caption: "Save downloaded Images?"
  });
  C.chkAddClientImage = widget.UI.CheckBox("chkAddClientImage", {
    caption: "Add Client Image?"
  });
  C.chkUpdateClientImage = widget.UI.CheckBox("chkUpdateClientImage", {
    caption: "Update Client Image?"
  });
  C.chkAddIdentificationItem = widget.UI.CheckBox("chkAddIdentificationItem", {
    caption: "Add Identification Item?"
  });

  // Grids

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

  // Create Tabs
  tabDetails = new widget.UI.Tabs("tabDetails", {
    style: "normal",
    onSelectedTabChanged: tabDetails_Refresh,
  });

  // Handle resize
  $(window).resize(Form_Resize);

  // Disable Close Button (this causes the 'FormClose' notification action to be invoked instead)
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler)

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabDetails_Cancel);
  cmdFinish.click(Form_ExecuteAction_Finish);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

  // Block UI
  widget.UI.Block("Initialising, please wait...");

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    Record_Load_Done,

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

function Record_Load_Done(data) {
  // Initialise
  mRecord = JSON.parse(data);

  // Set Tab
  if (mRecord &amp;&amp; mRecord.PageId) {
    tabDetails.SelectedTabId(mRecord.PageId);

    // Hide other Pages | NOT APPLICABLE FOR COST CENTER WIDGETS
//    if (mRecord.HideOtherPages) {
//      tabDetails.ShowSingleTab(mRecord.PageId);
//    }
  }
  else {
    tabDetails.SelectedTabId("Service");
  }

  // Page Permissions
  // NOTE: Not applicable to this form

  // Load Fields
  Fields_Load();

  // Save Fields (so UserData is in correct format for mOriginalJson)
  Fields_Save();

  // Save original JSON for Form_IsDirty
  mOriginalJson = JSON.stringify(mRecord);
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // Service
    C.chkUseService.Value(mRecord.UseService);
    
    // Credentials
    C.txtApiKeyProduction.Text(mRecord.ApiKeyProduction);
    C.txtApiSecretProduction.Text(mRecord.ApiSecretProduction);
    C.txtBearerTokenProduction.Text(mRecord.BearerTokenProduction);
    C.txtRequestUrlProduction.Text(mRecord.RequestUrlProduction);
    
    // Test Credentials
    C.txtApiKeyTest.Text(mRecord.ApiKeyTest);
    C.txtApiSecretTest.Text(mRecord.ApiSecretTest);
    C.txtBearerTokenTest.Text(mRecord.BearerTokenTest);
    C.txtRequestUrlTest.Text(mRecord.RequestUrlTest);
    
    // Options
    C.chkEnableCreditEnquiry.Value(mRecord.EnableCreditEnquiry);
    C.cboProduct.Text(mRecord.DefaultProduct);    
    C.chkIncludeFraudAnalytics.Value(mRecord.IncludeFraudAnalytics);
    C.cboFlowType.Text(mRecord.FlowType);    
    C.txtWebhook.Text(mRecord.WebhookUrl);    
    C.chkSaveDownloadedImages.Value(mRecord.SaveDownloadedImages);
    C.chkAddClientImage.Value(mRecord.AddClientImage);    
    C.chkUpdateClientImage.Value(mRecord.UpdateClientImage);
    C.chkAddIdentificationItem.Value(mRecord.AddIdentificationItem);    
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

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

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Service
  mRecord.UseService = C.chkUseService.Value();
    
  // Credentials
  mRecord.ApiKeyProduction = C.txtApiKeyProduction.Text();
  mRecord.ApiSecretProduction = C.txtApiSecretProduction.Text();
  mRecord.BearerTokenProduction = C.txtBearerTokenProduction.Text();
  mRecord.RequestUrlProduction = C.txtRequestUrlProduction.Text();
  
  // Test Credentials
  mRecord.ApiKeyTest = C.txtApiKeyTest.Text();
  mRecord.ApiSecretTest = C.txtApiSecretTest.Text();
  mRecord.BearerTokenTest = C.txtBearerTokenTest.Text();
  mRecord.RequestUrlTest = C.txtRequestUrlTest.Text();
  
  // Options
  mRecord.EnableCreditEnquiry = C.chkEnableCreditEnquiry.Value();
  mRecord.DefaultProduct = C.cboProduct.Text();
  mRecord.IncludeFraudAnalytics = C.chkIncludeFraudAnalytics.Value();
  mRecord.FlowType = C.cboFlowType.Text();
  mRecord.WebhookUrl = C.txtWebhook.Text();
  mRecord.SaveDownloadedImages = C.chkSaveDownloadedImages.Value();
  mRecord.AddClientImage = C.chkAddClientImage.Value();
  mRecord.UpdateClientImage = C.chkUpdateClientImage.Value();
  mRecord.AddIdentificationItem = C.chkAddIdentificationItem.Value();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.CostCentreId) {
      widget.SetHeading("&lt;HTML&gt;&lt;b&gt;APLYiD:&lt;/b&gt; Cost Centre (" + mRecord.CostCentreId + ")");
    }
    else {
      widget.SetHeading("New Cost Centre");
    }
  }

  // Information Lists
  if (mRecord) {
  }

  // Lists
  if (mRecord) {
    C.cboFlowType.ListFromArray(mRecord.ListFlowTypes);
    C.cboProduct.ListFromArray(mRecord.ListProducts);
  }

  // Controls
  if (mRecord) {
    // Production Credentials
    C.txtRequestUrlProduction.BlankTip(mRecord.RequestUrlProductionBlankTip);

    // Test Credentials
    C.txtRequestUrlTest.BlankTip(mRecord.RequestUrlTestBlankTip);
    
    // Options
    C.lblOptionsVerification.VisibleRow(mRecord.ShowFlowType);
    C.cboFlowType.VisibleRow(mRecord.ShowFlowType);
    
    // Trigger change events
    chkUseService_Change();  
    chkEnableCreditEnquiry_Change();
  }

  // Pages
  if (mRecord) {
  }

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdFinish.prop("disabled", true);
    frmMain.FormReadOnly(C, true);
  }

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

  // Resize Tab
  tabDetails_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile Optimisations
  var el = $(".mobile-indent th.indent1, .mobile-indent th.no-indent1");
  if (window.innerWidth &lt; 500) {
    el.addClass("no-indent1").removeClass("indent1");
  }
  else {
    el.addClass("indent1").removeClass("no-indent1");
  }

  // General

  // Tab
  tabDetails_Resize();
}

// ========
// Is Dirty
// ========
function Form_IsDirty() {
  if (mRecord) {
    // Save Fields
    Fields_Save();

    // Is Dirty?
    return mOriginalJson != JSON.stringify(mRecord);
  }
  else {
    return false;
  }
}

// ==============
// Wizard Buttons
// ==============
function tabDetails_Cancel() {
  if (Form_IsDirty()) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", { heading: "Close Form" }, tabDetails_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabDetails_Cancel_Finalise();
  }
}

function tabDetails_Cancel_Finalise() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

// ==========
// Resize Tab
// ==========
function tabDetails_Resize() {
  switch (tabDetails.SelectedTabId()) {
    case "Credentials":
      // Credentials
      C.txtRequestUrlProduction.WidthResizeFromParent();
      C.txtApiKeyProduction.WidthResizeFromParent();
      C.txtApiSecretProduction.WidthResizeFromParent();
      C.txtBearerTokenProduction.WidthResizeFromParent();
      break;
      
    case "TestCredentials":
      // Test Credentials
      C.txtRequestUrlTest.WidthResizeFromParent();
      C.txtApiKeyTest.WidthResizeFromParent();
      C.txtApiSecretTest.WidthResizeFromParent();
      C.txtBearerTokenTest.WidthResizeFromParent();
      break;
      
    case "Options":
      // Options
      C.cboFlowType.WidthResizeFromParent();
      C.cboProduct.WidthResizeFromParent();
      C.txtWebhook.WidthResizeFromParent();
      break

  }
}

// ===========
// Refresh Tab
// ===========
function tabDetails_Refresh() {
   // Load details
  switch (tabDetails.SelectedTabId()) {
    default:
      break;
  }

  // Resize
  tabDetails_Resize();

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

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch(actionId) {
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Assume Success
  var Ok = true;

  // Validate
  Ok = tabDetails.Validate();

  // Prompt
  if (Ok) {
    if (mRecord.PromptOnSave) {
      // Confirm
      widget.UI.MsgBoxConfirm("Are you sure you want to save this record?",
                              { heading: "Save" },
                              Form_ExecuteAction_FinishPost);

    }
    else {
      // Save without prompting
      Form_ExecuteAction_FinishPost();
    }
  }
}

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

  // Create Parameters
  // NOTE: We will simply update mRecord, clone this and send back (less some information)
  Fields_Save();
  var params = mRecord
  
  params.ListFlowTypes = "";
  params.ListProducts = "";
  
  params = JSON.parse(JSON.stringify(params));
  //params.GendersList = null;

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      // Close Form
      widget.Close();

      // Refresh Parent (to show updated details)
      // NOTE: Pass in Record Id just in case this has changed
      widget.RefreshParent(mRecord.CostCentreId);
    },

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

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

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabDetails_Cancel();
      break;
   }
}

// ======================
// Control Event Handlers
// ======================
function chkUseService_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  if (C.chkUseService.Value()) {
    // set all tabs to be visible
    tabDetails.ShowAllTabs();
  } else {
    // only show the Service tab
    tabDetails.ShowSingleTab("Service");
  }
}

function chkEnableCreditEnquiry_Change(sender, e) {
  C.cboProduct.ReadOnly(! C.chkEnableCreditEnquiry.Value());
  C.chkIncludeFraudAnalytics.ReadOnly(! C.chkEnableCreditEnquiry.Value());
  
  C.cboFlowType.ReadOnly(! C.chkEnableCreditEnquiry.Value());
  
  C.chkSaveDownloadedImages.ReadOnly(! C.chkEnableCreditEnquiry.Value());
  C.chkAddClientImage.ReadOnly(! C.chkEnableCreditEnquiry.Value());
  C.chkUpdateClientImage.ReadOnly(! C.chkEnableCreditEnquiry.Value());
  C.chkAddIdentificationItem.ReadOnly(! C.chkEnableCreditEnquiry.Value());
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>TjfTz0f+e0Ca3VuJ+IiO4w</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Cost Centre</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>CostCentre</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>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Configuration options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="CostCentreId" type="Range">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>CostCentres</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="Page" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>Service,Credentials,TestCredentials,Options</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ReadOnly" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>