<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-30T20:38:18.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-08-25T20:51:56.3180000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-30T20:36:16.4780000</UpdatedUtcDate>
    <ScriptId>HWCCTWILIO</ScriptId>
    <Description>Cost Centre Edit (Twilio)</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_CostCentreEdit_Twilio
Option Explicit On
Option Strict On

' #################################################################
' Cost Centre Edit (Twilio) form HTML Widget
'
' Copyright (C) Intersoft Systems Limited 2024
'
' Version: 1.00 (01/10/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  01/10/2024  ISS      J034095   Created
' #################################################################

' 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("Twilio") 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 "WizardValidate"
        ' Validate wizard page
        Main = WizardValidate(parametersJson, 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.Twilio.UseService
      
      ' Credentials
      .RequestUrlProduction = CostCentre.Twilio.CredentialsProduction.RequestUrl
      .RequestUrlProductionTooltip = ISMessaging_Twilio.DefaultRequestUrl
      
      .AccountIdProduction = CostCentre.Twilio.CredentialsProduction.AccountId
      .AuthenticationTokenProduction = CostCentre.Twilio.CredentialsProduction.AuthenticationToken
      
      .CallbackUrlProduction = CostCentre.Twilio.CredentialsProduction.StatusCallbackUrl
      .CallbackUrlProductionTooltip = finBL.Messaging.Service_Twilio.SuggestedStatusCallbackUrl
      
      ' Credentials Test
      .RequestUrlTest = CostCentre.Twilio.CredentialsTest.RequestUrl
      .RequestUrlTestTooltip = ISMessaging_Twilio.DefaultRequestUrl
      
      .AccountIdTest = CostCentre.Twilio.CredentialsTest.AccountId
      .AuthenticationTokenTest = CostCentre.Twilio.CredentialsTest.AuthenticationToken
      
      .CallbackUrlTest = CostCentre.Twilio.CredentialsTest.StatusCallbackUrl
      .CallbackUrlTestTooltip = finBL.Messaging.Service_Twilio.SuggestedStatusCallbackUrl
      
      .ReturnMockedResponseTest = CostCentre.Twilio.CredentialsTest.TestModeMocked
      .SendToPhoneNumberTest = CostCentre.Twilio.CredentialsTest.TestModeSendPhoneNumberSms
      
      ' Other
      .EnableSms = CostCentre.Twilio.OptionsMessaging.EnableSms
      .EnableSmsFeeCharging = CostCentre.Twilio.OptionsMessaging.SmsEnableFeeCharging
      .UseConnectWizard = CostCentre.Twilio.OptionsMessaging.UseSmsUpdates
      
      Select Case CostCentre.Twilio.OptionsMessaging.SmsFromNumberType          
        Case iseMessaging_Twilio_FromNumberType.PhoneNumber
          .DedicatedNumber = True
          
        Case iseMessaging_Twilio_FromNumberType.SenderId
          .SenderId = True
          
      End Select
      .DedicatedNumberText = CostCentre.Twilio.OptionsMessaging.SmsFromNumber
      .SenderIdText = CostCentre.Twilio.OptionsMessaging.SmsFromSenderId
      .FromName = CostCentre.Twilio.OptionsMessaging.SmsFromName
      
      ' Permissions

      ' Lists
      .ListSendToPhoneNumberTest = "+15005550001 *Invalid Number,+15005550002 *Cannot route to Number,+15005550003 *No international permissions,+15005550004 *Blocked,+15005550009 *Incapable of receiving SMS"
      
      ' Configuration
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      Select Case UCase(finBL.CountryCode)
        Case "NZ"
          .chkDedicatedNumberCaption = "Dedicated Short Code?"
          .txtDedicatedNumberCaption = "Short" &amp; Chr(160) &amp; "Code:"
          .txtDedicatedNumberMaxLength = 10
          
        Case Else
          .chkDedicatedNumberCaption = "Dedicated Number?"
          .txtDedicatedNumberCaption = "Number:"
          .txtDedicatedNumberMaxLength = 50
          
      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 Message As String
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim SendToPhonenumberTest As String
  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    
    
  ' Format the SendToPhoneNumber (if applicable)
  If Success Then
    ' Set the SendToPhonenumber to the raw user input incase it cannot be parsed
    ' Validation should have been done in WizardValidate
    SendToPhonenumberTest = Record.SendToPhoneNumberTest       
    
    ' Parse the Send To Phonenumber 
    If Len(Record.SendToPhoneNumberTest) &lt;&gt; 0 Then
      With finBL.Runtime.CreatePhoneNumberDetails2()
        If .ParsePhoneNumber(Record.SendToPhoneNumberTest, Message) Then
          SendToPhonenumberTest = .GetPhoneNumberE164 
        End If
      End With
    End If
  End If

  ' Update and Save
  If Success Then
    ' Begin Transaction
    If finBL.Database.TransactionBegin() Then
      ' Update Cost Centre
      With CostCentre.Twilio
        ' Service
        .UseService = Record.UseService
        
        ' Credentials
        With .CredentialsProduction
          .RequestUrl = Record.RequestUrlProduction
          
          .AccountId = Record.AccountIdProduction
          .AuthenticationToken = Record.AuthenticationTokenProduction
          
          .StatusCallbackUrl = Record.CallbackUrlProduction
        End With
          
        ' Test Credentials
        With .CredentialsTest
          .RequestUrl = Record.RequestUrlTest
          
          .AccountId = Record.AccountIdTest
          .AuthenticationToken = Record.AuthenticationTokenTest

          .StatusCallbackUrl = Record.CallbackUrlTest
          
          .TestModeMocked = Record.ReturnMockedResponseTest
          .TestModeSendPhoneNumberSms = SendToPhonenumberTest
        End With
        
        ' Options
        With .OptionsMessaging
          .EnableSms = Record.EnableSms
          .SmsEnableFeeCharging = Record.EnableSmsFeeCharging
          .UseSmsUpdates = Record.UseConnectWizard
          
          If Record.SenderId Then
            .SmsFromNumberType = iseMessaging_Twilio_FromNumberType.SenderId
          Else If Record.DedicatedNumber Then
            .SmsFromNumberType = iseMessaging_Twilio_FromNumberType.PhoneNumber
          End If
          
          .SmsFromNumber = Record.DedicatedNumberText
          .SmsFromSenderId = Record.SenderIdText
          .SmsFromName = Record.FromName
        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;
'''  Validate a Wizard page.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted object containing information required to validate a Wizard page.
''' &lt;/param&gt;
''' &lt;param name="returnValue"&gt;
'''  A JSON object; "true" if validation passed, otherwise, information as to why validation failed.
''' &lt;/param&gt;
Private Function WizardValidate(parametersJson As String,
                                ByRef returnValue As String) As Boolean
                           
  Dim ConfirmList As List(Of String)                                
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim Message As String
  Dim PageId As String
  Dim PhoneNumber As String
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Initialise
  ConfirmList = New List(Of String)

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "TestCredentials"
      ' Validate phone number
      PhoneNumber = mCombinedParameters.GetString("PhoneNumber")
      
      If Len(PhoneNumber) &lt;&gt; 0 Then
        With finBL.Runtime.CreatePhoneNumberDetails2()
          If Not .ParsePhoneNumber(PhoneNumber, Message)
            ConfirmList.Add(Message)
          End If
        End With
      End If
      
      If ConfirmList.Count &lt;&gt; 0 Then
        Data = ConfirmList
      End If
      
  End Select

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
''' &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 RequestUrlProduction As String
  Public RequestUrlProductionTooltip As String
  
  Public AccountIdProduction As String
  Public AuthenticationTokenProduction As String
  
  Public CallbackUrlProduction As String
  Public CallbackUrlProductionTooltip As String
  
  ' Test Credentials
  Public RequestUrlTest As String
  Public RequestUrlTestTooltip As String
  
  Public AccountIdTest As String
  Public AuthenticationTokenTest As String
  
  Public CallbackUrlTest As String
  Public CallbackUrlTestTooltip As String
  
  Public ReturnMockedResponseTest As Boolean
  Public SendToPhoneNumberTest As String  
  
  ' Options
  Public EnableSms As Boolean
  Public EnableSmsFeeCharging As Boolean
  Public UseConnectWizard As Boolean
  
  Public DedicatedNumber As Boolean
  Public DedicatedNumberText As String
  Public SenderId As Boolean
  Public SenderIdText As String
  Public FromName As String
  
  ' Permissions

  ' Lists
  Public ListSendToPhoneNumberTest As String

  ' Configuration
  Public PromptOnSave As Boolean
  Public chkDedicatedNumberCaption As String
  Public txtDedicatedNumberCaption As String
  Public txtDedicatedNumberMaxLength As Integer

End Class

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

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

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

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

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to edit the "Twilio" 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 Twilio 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 User Credentials&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountIdProduction"&gt;Account Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountIdProduction" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAuthenticationTokenProduction"&gt;Authentication&amp;nbsp;Token:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAuthenticationTokenProduction"/&gt;&lt;/td&gt;
        &lt;/tr&gt;  
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCallbackUrlProduction"&gt;Production&amp;nbsp;Status&amp;nbsp;Callback&amp;nbsp;URL&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCallbackUrlProduction"&gt;Status&amp;nbsp;Callback&amp;nbsp;URL:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCallbackUrlProduction"/&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 User Credentials&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountIdTest"&gt;Account Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountIdTest" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAuthenticationTokenTest"&gt;Authentication&amp;nbsp;Token:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAuthenticationTokenTest"/&gt;&lt;/td&gt;
        &lt;/tr&gt;  
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCallbackUrlTest"&gt;Test&amp;nbsp;Status&amp;nbsp;Callback&amp;nbsp;URL&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCallbackUrlTest"&gt;Status Callback URL:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCallbackUrlTest"/&gt;&lt;/td&gt;
        &lt;/tr&gt;     
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblTestModeOptions"&gt;Test Mode options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkReturnMockResponsesTest" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="cboSendToPhoneNumberTest"&gt;Send&amp;nbsp;to&amp;nbsp;Mobile:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSendToPhoneNumberTest" /&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="lblSmsOptions"&gt;SMS options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkEnableSms" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkEnableSmsFeeCharging" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUseConnectWizard" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSmsSendOptions"&gt;SMS Send options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkDedicatedNumber" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtDedicatedNumber"&gt;Number:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDedicatedNumber" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkSenderId" type="checkbox"/&gt; &lt;span id="spanSenderIdWarning" class="is-info-text warning small"&gt;WARNING: Sender IDs do not support replies.&lt;/span&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtSenderId"&gt;Sender Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtSenderId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFromName"&gt;From Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFromName" /&gt;&lt;/td&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;

// Orignal Values for validate
var mSendToPhoneNumberTestOriginal;

// Controls
var C = {
  //   Service
  lblService: null,
  chkUseService: null,
  
  //   Credentials
  lblRequestUrlProduction: null,
  txtRequestUrlProduction: null,
  
  lblCredentialsProduction: null,
  txtAccountIdProduction: null,
  txtAuthenticationTokenProduction: null,
  
  lblCallbackUrlProduction: null,
  txtCallbackUrlProduction: null,
  
  // Test Credentials
  lblRequestUrlTest: null,
  txtRequestUrlTest: null,
  
  lblCredentialsTest: null,
  txtAccountIdTest: null,
  txtAuthenticationTokenTest: null,
  
  lblCallbackUrlTest: null,
  txtCallbackUrlTest: null,
  
  lblTestModeOptions: null,
  chkReturnMockResponsesTest: null,
  cboSendToPhoneNumberTest: null,
  
  // Options
  lblSmsOptions: null,
  chkEnableSms: null,
  chkEnableSmsFeeCharging: null,
  chkUseConnectWizard: null,
  
  lblSmsSendOptions: null,
  chkDedicatedNumber: null,
  txtDedicatedNumber: null,
  chkSenderId: null,
  txtSenderId: null,
  txtFromName: 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.lblCredentialsProduction = widget.UI.Label("lblCredentialsProduction", {});
  C.txtRequestUrlProduction = widget.UI.TextBox("txtRequestUrlProduction", {
    maxLength: 200
  });
  
  C.lblCredentialsProduction = widget.UI.Label("lblCredentialsProduction", {});
  C.txtAccountIdProduction = widget.UI.TextBox("txtAccountIdProduction", {
    maxLength: 50
  });
  C.txtAuthenticationTokenProduction = widget.UI.TextBox("txtAuthenticationTokenProduction", {
    maxLength: 50,
    password: true,
    passwordRevealOnFocus: true,
  });
  
  C.lblCallbackUrlProduction = widget.UI.Label("lblCallbackUrlProduction", {
    tooltipHtml: "To receive Delivery Status updates you must define a Callback URL.",
  });
  C.txtCallbackUrlProduction = widget.UI.TextBox("txtCallbackUrlProduction", {
    maxLength: 200,
  });
  
  // Test Credentials
  C.lblCredentialsTest = widget.UI.Label("lblCredentialsTest", {});
  C.txtRequestUrlTest = widget.UI.TextBox("txtRequestUrlTest", {
    maxLength: 200
  });
  
  C.lblCredentialsTest = widget.UI.Label("lblCredentialsTest", {});
  C.txtAccountIdTest = widget.UI.TextBox("txtAccountIdTest", {
    maxLength: 50
  });
  C.txtAuthenticationTokenTest = widget.UI.TextBox("txtAuthenticationTokenTest", {
    maxLength: 50,
    password: true,
    passwordRevealOnFocus: true,
  });
  
  C.lblCallbackUrlTest = widget.UI.Label("lblCallbackUrlTest", {
    tooltipHtml: "To receive Delivery Status updates you must define a Callback URL.",
  });
  C.txtCallbackUrlTest = widget.UI.TextBox("txtCallbackUrlTest", {
    maxLength: 200,
  });
  
  C.lblTestModeOptions = widget.UI.Label("lblTestModeOptions", {
    tooltipHtml: "Entering a Phone Number here will send all SMS's to this Phone Number.&lt;br/&gt;Test Numbers are listed in the dropdown, they do not send a message, your account won't be charged and a success response will be returned."
  });
  C.chkReturnMockResponsesTest = widget.UI.CheckBox("chkReturnMockResponsesTest", {
    caption: "Return mocked responses for requests where available?",
    
    onChange: chkReturnMockResponsesTest_Change
  });
  C.cboSendToPhoneNumberTest = widget.UI.ComboBox("cboSendToPhoneNumberTest", {
    maxLength: 200,
    width: widget.UI.FIELD_WIDTH_CODE_20
  });
  
  // Options
  C.lblSmsOptions = widget.UI.Label("lblSmsOptions", {
   tooltipHtml: "&lt;b&gt;Use \"Retrieve SMS Delivery Updates and Replies\" finPOWER Connect Wizard&lt;/b&gt;: If using Callbacks this is not required, so should not be used."
  });
  C.chkEnableSms = widget.UI.CheckBox("chkEnableSms", {
    caption: "Enable SMS?",
    
    onChange: chkEnableSms_Change,
  });
  C.chkEnableSmsFeeCharging = widget.UI.CheckBox("chkEnableSmsFeeCharging", {
    caption: "Enable SMS Fee Charging?"
  });
  C.chkUseConnectWizard = widget.UI.CheckBox("chkUseConnectWizard", {
    caption: 'Use "Retrieve SMS Delivery Updates and Replies" finPOWER Connect Wizard?',
    tooltipHtml: "If using Callbacks this is not required, so should not be used."
  });
  
  C.lblSmsSendOptions = widget.UI.Label("lblSmsSendOptions", {
    tooltipHtml: "&lt;b&gt;From Name&lt;/b&gt;: The Name to include at the start of the Message text to help identify who the message is from."
  });
  C.chkDedicatedNumber = widget.UI.RadioButton("chkDedicatedNumber", {
    caption: "Dedicated Number?",
    
    onChange: chkSmsSendOptions_Change
  });
  C.txtDedicatedNumber = widget.UI.TextBox("txtDedicatedNumber", {
    maxLength: 50
  });
  C.chkSenderId = widget.UI.RadioButton("chkSenderId", {
    caption: "Sender Id?",
    
    onChange: chkSmsSendOptions_Change
  });
  C.txtSenderId = widget.UI.TextBox("txtSenderId", {
    maxLength: 11
  });
  C.txtFromName = widget.UI.TextBox("txtFromName", {
    maxLength: 50,
    tooltipHtml: "The Name to include at the start of the Message text to help identify who the message is from."
  });

  // 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);
  
  // Store original values for validation
  mSendToPhoneNumberTestOriginal = mRecord.SendToPhoneNumberTest;  
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // Service
    C.chkUseService.Value(mRecord.UseService);
    
    // Credentials
    C.txtRequestUrlProduction.Text(mRecord.RequestUrlProduction);
    
    C.txtAccountIdProduction.Text(mRecord.AccountIdProduction);
    C.txtAuthenticationTokenProduction.Text(mRecord.AuthenticationTokenProduction);
    
    C.txtCallbackUrlProduction.Text(mRecord.CallbackUrlProduction);
    
    // Test Credentials
    C.txtRequestUrlTest.Text(mRecord.RequestUrlTest);
    
    C.txtAccountIdTest.Text(mRecord.AccountIdTest);
    C.txtAuthenticationTokenTest.Text(mRecord.AuthenticationTokenTest);
    
    C.txtCallbackUrlTest.Text(mRecord.CallbackUrlTest);
    
    C.chkReturnMockResponsesTest.Value(mRecord.ReturnMockedResponseTest);
    C.cboSendToPhoneNumberTest.Text(mRecord.SendToPhoneNumberTest);
    
    // Options
    C.chkEnableSms.Value(mRecord.EnableSms);
    C.chkEnableSmsFeeCharging.Value(mRecord.EnableSmsFeeCharging);
    C.chkUseConnectWizard.Value(mRecord.UseConnectWizard);
    
    C.chkDedicatedNumber.Value(mRecord.DedicatedNumber);
    C.txtDedicatedNumber.Text(mRecord.DedicatedNumberText);
    C.chkSenderId.Value(mRecord.SenderId);
    C.txtSenderId.Text(mRecord.SenderIdText);
    C.txtFromName.Text(mRecord.FromName);
  }

  // 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.RequestUrlProduction = C.txtRequestUrlProduction.Text();
  
  mRecord.AccountIdProduction = C.txtAccountIdProduction.Text();
  mRecord.AuthenticationTokenProduction = C.txtAuthenticationTokenProduction.Text();
  
  mRecord.CallbackUrlProduction = C.txtCallbackUrlProduction.Text();
  
  // Test Credentials
  mRecord.RequestUrlTest = C.txtRequestUrlTest.Text();
  
  mRecord.AccountIdTest = C.txtAccountIdTest.Text();
  mRecord.AuthenticationTokenTest = C.txtAuthenticationTokenTest.Text();
  
  mRecord.CallbackUrlTest = C.txtCallbackUrlTest.Text();
  
  mRecord.ReturnMockedResponseTest = C.chkReturnMockResponsesTest.Value();
  mRecord.SendToPhoneNumberTest = C.cboSendToPhoneNumberTest.Text();
  
  // Options
  mRecord.EnableSms = C.chkEnableSms.Value();
  mRecord.EnableSmsFeeCharging = C.chkEnableSmsFeeCharging.Value();
  mRecord.UseConnectWizard = C.chkUseConnectWizard.Value();
  
  mRecord.DedicatedNumber = C.chkDedicatedNumber.Value();
  mRecord.DedicatedNumberText = C.txtDedicatedNumber.Text();
  mRecord.SenderId = C.chkSenderId.Value();
  mRecord.SenderIdText = C.txtSenderId.Text();
  mRecord.FromName = C.txtFromName.Text();
}

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

  // Information Lists
  if (mRecord) {
  }

  // Lists
  if (mRecord) {
    C.cboSendToPhoneNumberTest.ListFromCsvString(mRecord.ListSendToPhoneNumberTest);
  }

  // Controls
  if (mRecord) {
    // Production Credentials
    C.txtRequestUrlProduction.BlankTip(mRecord.RequestUrlProductionTooltip);
    
    C.txtCallbackUrlProduction.BlankTip(mRecord.CallbackUrlProductionTooltip);

    // Test Credentials
    C.txtRequestUrlTest.BlankTip(mRecord.RequestUrlTestTooltip);
    
    C.txtCallbackUrlTest.BlankTip(mRecord.CallbackUrlTestTooltip);
    
    // Options
    C.chkDedicatedNumber.Caption(mRecord.chkDedicatedNumberCaption);
    C.txtDedicatedNumber.Caption(mRecord.txtDedicatedNumberCaption);
    if (mRecord.txtDedicatedNumberMaxLength) {
      C.txtDedicatedNumber.MaxLength(mRecord.txtDedicatedNumberMaxLength);
    }
    
    // Change events
    chkUseService_Change();
    chkReturnMockResponsesTest_Change();
    chkEnableSms_Change();
    if (C.chkEnableSms.Value()) {
      chkSmsSendOptions_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.txtAccountIdProduction.WidthResizeFromParent();
      C.txtAuthenticationTokenProduction.WidthResizeFromParent();
      
      C.txtCallbackUrlProduction.WidthResizeFromParent();
      break;
      
    case "TestCredentials":
      // Test Credentials
      C.txtRequestUrlTest.WidthResizeFromParent();
      
      C.txtAccountIdTest.WidthResizeFromParent();
      C.txtAuthenticationTokenTest.WidthResizeFromParent();
      
      C.txtCallbackUrlTest.WidthResizeFromParent();
      
      //C.cboSendToPhoneNumberTest.WidthResizeFromParent();
      break;
      
    case "Options":
      // Options
      C.txtDedicatedNumber.WidthResizeFromParent();
      C.txtSenderId.WidthResizeFromParent();
      C.txtFromName.WidthResizeFromParent();
      break;

  }
}

// ===============
// Validate Wizard
// ===============
function tabDetails_Validate(validCallback) {
  // Validate
  var Ok = tabDetails.Validate(true);

  // NOTE: NOT APPLICABLE HERE, ALWAYS VALIDATE
//  // Other client-side validation
//  if (Ok) {
//    switch (tabDetails.SelectedTabId()) {
//      default:
//        // No validation
//        validCallback();
//        return;
//    }
//  }

  // Server-side validation
  if (Ok) {
    var params;
    
    // In this case, validation is done on finish.
    
    // Only validate if changes have been made
    if (C.cboSendToPhoneNumberTest.Text() &amp;&amp; C.cboSendToPhoneNumberTest.Text() !== mSendToPhoneNumberTestOriginal) {
      params = {
        PhoneNumber: C.cboSendToPhoneNumberTest.Text()
      }
    }

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

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

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

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

function tabDetails_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 tabDetails_Refresh
    // NOT APPLICABLE IN THIS INSTANCE
//    switch (tabDetails.SelectedTabId()) {
//      case "General":
//        break;
//    }
    if (o.Data &amp;&amp; o.Data.length != 0) {
      // Confirm warnings
      widget.UI.MsgBoxConfirmList("To continue, please approve the following:",
                                  o.Data,
                                  {
                                    heading: "Additional Confirmation",
                                    icon: "Warning",
                                  },
                                  function () { validCallback(); },
                                  null);
    }
    else {
      // Callback
      validCallback();
    }
    return;

    // Callback
//    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// ===========
// 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
  tabDetails_Validate(function() {
    // Prompt
    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 = JSON.parse(JSON.stringify(mRecord));
  
  //params.GendersList = null;

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      if (data) {
        widget.UI.Unblock();
        widget.UI.MsgBoxAlert(data, { messageIsHtml: true }, Form_ExecuteAction_FinishPost_Done);
      }
      else {
        Form_ExecuteAction_FinishPost_Done();
      }
    },

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

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

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

// ====================
// 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 chkReturnMockResponsesTest_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  C.cboSendToPhoneNumberTest.ReadOnly(C.chkReturnMockResponsesTest.Value());
}

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

  C.chkEnableSmsFeeCharging.ReadOnly(! C.chkEnableSms.Value());
  C.chkUseConnectWizard.ReadOnly(! C.chkEnableSms.Value());
  
  C.chkDedicatedNumber.ReadOnly(! C.chkEnableSms.Value());
  C.txtDedicatedNumber.ReadOnly(! C.chkEnableSms.Value());
  C.chkSenderId.ReadOnly(! C.chkEnableSms.Value());
  C.txtSenderId.ReadOnly(! C.chkEnableSms.Value());
  C.txtFromName.ReadOnly(! C.chkEnableSms.Value());
  
  if (C.chkEnableSms.Value() &amp;&amp; sender) {
    // Trigger change events. Only do this if trigger by a control (don't do it if done manually via code)
    // This prevents these change events from being called multiple times
    chkSmsSendOptions_Change();
  }
}

function chkSmsSendOptions_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Handle Radio Buttons
  if (sender) {
    C.chkDedicatedNumber.Value(sender === C.chkDedicatedNumber);
    C.chkSenderId.Value(sender === C.chkSenderId);
  }
  
  // Enable/ Disable TextBoxes
  C.txtDedicatedNumber.ReadOnly(! C.chkDedicatedNumber.Value());
  C.txtDedicatedNumber.AllowBlank(! C.chkDedicatedNumber.Value());
  C.txtSenderId.ReadOnly(! C.chkSenderId.Value());
  C.txtSenderId.AllowBlank(! C.chkSenderId.Value());
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>sURHmXe3mUKpGs+TJ+axcQ</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>