<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-30T20:43:41.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-08-16T02:15:36.3780000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-30T20:42:19.0870000</UpdatedUtcDate>
    <ScriptId>HWCCSMSF</ScriptId>
    <Description>Cost Centre Edit (SMS Fusion)</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_CostCentreEdit_SmsFusion
Option Explicit On
Option Strict On

' #################################################################
' Cost Centre Edit (SMS Fusion) 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      J034093   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("SMSFusion") 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.SMSFusion.UseService
      
      ' Credentials
      .RequestUrlProduction = CostCentre.SMSFusion.CredentialsProduction.RequestUrl
      .RequestUrlProductionTooltip = ISMessaging_SmsFusion.DefaultRequestUrl
      
      .ApiKeyProduction = CostCentre.SMSFusion.CredentialsProduction.ApiKey
      .DeliveryReportsURIProduction = CostCentre.SMSFusion.CredentialsProduction.DeliveryReportCallbackUrl
      .DeliveryReportsURIProductionTooltip = finBL.Messaging.Service_SmsFusion.SuggestedDeliveryReportCallbackUrl
      .RepliesURIProduction = CostCentre.SMSFusion.CredentialsProduction.ReplyCallbackUrl
      .RepliesURIProductionTooltip = finBL.Messaging.Service_SmsFusion.SuggestedReplyCallbackUrl
      
      ' Credentials Test
      .RequestUrlTest = CostCentre.SMSFusion.CredentialsTest.RequestUrl
      .RequestUrlTestTooltip = ISMessaging_SmsFusion.DefaultRequestUrl
      
      .ApiKeyTest = CostCentre.SMSFusion.CredentialsTest.ApiKey
      
      .DeliveryReportsURITest = CostCentre.SMSFusion.CredentialsTest.DeliveryReportCallbackUrl
      .DeliveryReportsURITestTooltip = finBL.Messaging.Service_SmsFusion.SuggestedDeliveryReportCallbackUrl
      .RepliesURITest = CostCentre.SMSFusion.CredentialsTest.ReplyCallbackUrl
      .RepliesURITestTooltip = finBL.Messaging.Service_SmsFusion.SuggestedReplyCallbackUrl
      
      .ReturnMockedResponseTest = CostCentre.SMSFusion.CredentialsTest.TestModeMocked
      .SendToPhoneNumberTest = CostCentre.SMSFusion.CredentialsTest.TestModeSendPhoneNumberSms
      
      ' Other
      .EnableSms = CostCentre.SMSFusion.OptionsMessaging.EnableSms
      .EnableSmsFeeCharging = CostCentre.SMSFusion.OptionsMessaging.SmsEnableFeeCharging
      
      Select Case CostCentre.SMSFusion.OptionsMessaging.SmsFromNumberType
        Case iseMessaging_SmsFusion_FromNumberType.SharedNumber
          .SharedNumber = True
          
        Case iseMessaging_SMSFusion_FromNumberType.DedicatedNumber
          .DedicatedNumber = True
          
        Case iseMessaging_SMSFusion_FromNumberType.SenderId
          .SenderId = True
          
      End Select
      .DedicatedNumberText = CostCentre.SMSFusion.OptionsMessaging.SmsFromNumber
      .SenderIdText = CostCentre.SMSFusion.OptionsMessaging.SmsFromSenderId
      .FromName = CostCentre.SMSFusion.OptionsMessaging.SmsFromName
      
      .ReplyEmail = CostCentre.SMSFusion.OptionsMessaging.SmsReplyEmail
      
      ' Permissions

      ' Lists
      .ListSendToPhoneNumberTest = ""
      
      ' 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;
'''  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;
'''  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.SMSFusion
        ' Service
        .UseService = Record.UseService
        
        ' Credentials
        With .CredentialsProduction
          .RequestUrl = Record.RequestUrlProduction
          
          .ApiKey = Record.ApiKeyProduction
          
          .DeliveryReportCallbackUrl = Record.DeliveryReportsURIProduction
          .ReplyCallbackUrl = Record.RepliesURIProduction
        End With
          
        ' Test Credentials
        With .CredentialsTest
          .RequestUrl = Record.RequestUrlTest
          
          .ApiKey = Record.ApiKeyTest
          
          .DeliveryReportCallbackUrl = Record.DeliveryReportsURITest
          .ReplyCallbackUrl = Record.RepliesURITest
          
          .TestModeMocked = Record.ReturnMockedResponseTest
          .TestModeSendPhoneNumberSms = SendToPhonenumberTest
        End With
        
        ' Options
        With .OptionsMessaging
          .EnableSms = Record.EnableSms
          .SmsEnableFeeCharging = Record.EnableSmsFeeCharging
          
          If Record.SenderId Then
            .SmsFromNumberType = iseMessaging_SmsFusion_FromNumberType.SenderId
          Else If Record.DedicatedNumber Then
            .SmsFromNumberType = iseMessaging_SmsFusion_FromNumberType.DedicatedNumber
          Else
            .SmsFromNumberType = iseMessaging_SmsFusion_FromNumberType.SharedNumber
          End If
          .SmsFromNumber = Record.DedicatedNumberText
          .SmsFromSenderId = Record.SenderIdText
          .SmsFromName = Record.FromName
          
          .SmsReplyEmail = Record.ReplyEmail
        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 RequestUrlProduction As String
  Public RequestUrlProductionTooltip As String
  
  Public ApiKeyProduction As String
  
  Public DeliveryReportsURIProduction As String
  Public DeliveryReportsURIProductionTooltip As String
  Public RepliesURIProduction As String
  Public RepliesURIProductionTooltip As String
  
  ' Test Credentials
  Public RequestUrlTest As String
  Public RequestUrlTestTooltip As String
  
  Public ApiKeyTest As String
  
  Public DeliveryReportsURITest As String
  Public DeliveryReportsURITestTooltip As String
  Public RepliesURITest As String
  Public RepliesURITestTooltip As String
  
  Public ReturnMockedResponseTest As Boolean
  Public SendToPhoneNumberTest As String
  
  ' Options
  Public EnableSms As Boolean
  Public EnableSmsFeeCharging As Boolean
  
  Public SharedNumber As Boolean
  Public DedicatedNumber As Boolean
  Public DedicatedNumberText As String
  Public SenderId As Boolean
  Public SenderIdText As String
  Public FromName As String
  
  Public ReplyEmail 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 "SMS Fusion" 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 SMS Fusion 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 Key&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 colspan="2"&gt;&lt;label id="lblCallbackURIsProduction"&gt;Production Callback URIs&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDeliveryReportsProduction"&gt;Delivery&amp;nbsp;Reports:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDeliveryReportsProduction"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRepliesProduction"&gt;Replies:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRepliesProduction"/&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 Key&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 colspan="2"&gt;&lt;label id="lblCallbackURIsTest"&gt;Test Callback URIs&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDeliveryReportsTest"&gt;Delivery&amp;nbsp;Reports:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDeliveryReportsTest"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRepliesTest"&gt;Replies:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRepliesTest"/&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;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="chkSharedNumber" type="checkbox"/&gt; &lt;span id="spanSharedNumberWarning" class="is-info-text warning small"&gt;WARNING: Using a shared number is not recommended.&lt;/span&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;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSmsReplyOptions"&gt;SMS Reply options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReplyEmail"&gt;Reply Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReplyEmail"/&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,
  txtApiKeyProduction: null,
  
  lblCallbackURIsProduction: null,
  txtDeliveryReportsProduction: null,
  txtRepliesProduction: null,
  
  // Test Credentials
  lblRequestUrlTest: null,
  txtRequestUrlTest: null,
  
  lblCredentialsTest: null,
  txtApiKeyTest: null,
  
  lblCallbackURIsTest: null,
  txtDeliveryReportsTest: null,
  txtRepliesTest: null,
  
  lblTestModeOptions: null,
  chkReturnMockResponsesTest: null,
  cboSendToPhoneNumberTest: null,
  
  // Options
  lblSmsOptions: null,
  chkEnableSms: null,
  chkEnableSmsFeeCharging: null,
  
  lblSmsSendOptions: null,
  chkSharedNumber: null,
  chkDedicatedNumber: null,
  txtDedicatedNumber: null,
  chkSenderId: null,
  txtSenderId: null,
  txtFromName: null,
  
  lblSmsReplyOptions: null,
  txtReplyEmail: 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("lblRequestUrlProduction", {});
  C.txtRequestUrlProduction = widget.UI.TextBox("txtRequestUrlProduction", {
    maxLength: 200
  });
  
  C.lblCredentialsProduction = widget.UI.Label("lblCredentialsProduction", {});
  C.txtApiKeyProduction = widget.UI.TextBox("txtApiKeyProduction", {
    maxLength: 100,
    password: true,
    passwordRevealOnFocus: true,
  });
  
  C.lblCallbackURIsProduction = widget.UI.Label("lblCallbackURIsProduction", {
    tooltipHtml: "If defined here, messages sent will have Delivery Reports and/ or Replies sent to these URLs instead of your normal SMS Fusion API Key settings."
  });
  C.txtDeliveryReportsProduction = widget.UI.TextBox("txtDeliveryReportsProduction", {
    maxLength: 200
  });
  C.txtRepliesProduction = widget.UI.TextBox("txtRepliesProduction", {
    maxLength: 200
  });
  
  // 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: 100,
    password: true,
    passwordRevealOnFocus: true,
  });
  
  C.lblCallbackURIsTest = widget.UI.Label("lblCallbackURIsTest", {
    tooltipHtml: "If defined here, messages sent will have Delivery Reports and/ or Replies sent to these URLs instead of your normal SMS Fusion API Key settings."
  });
  C.txtDeliveryReportsTest = widget.UI.TextBox("txtDeliveryReportsTest", {
    maxLength: 200
  });
  C.txtRepliesTest = widget.UI.TextBox("txtRepliesTest", {
    maxLength: 200
  });
  
  C.lblTestModeOptions = widget.UI.Label("lblTestModeOptions", {
    tooltipHtml: "Entering a Phone Number here will send all SMS's to this Phone Number."
  });
  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,
    
    // SMS Fusion does not currently have any test phonenumbers. So hide the dropdown
    allowDropdown: false,
  });
  
  // Options
  C.lblSmsOptions = widget.UI.Label("lblSmsOptions", {});
  C.chkEnableSms = widget.UI.CheckBox("chkEnableSms", {
    caption: "Enable SMS?",
    
    onChange: chkEnableSms_Change,
  });
  C.chkEnableSmsFeeCharging = widget.UI.CheckBox("chkEnableSmsFeeCharging", {
    caption: "Enable SMS Fee Charging?"
  });
  
  C.lblSmsSendOptions = widget.UI.Label("lblSmsSendOptions", {
    tooltipHtml: "&lt;b&gt;Shared Number&lt;/b&gt;: This may mean your competitors may share the same number and replies cannot be directed back to you.&lt;br/&gt;&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.chkSharedNumber = widget.UI.RadioButton("chkSharedNumber", {
    caption: "Shared Number?",
    
    onChange: chkSmsSendOptions_Change
  });
  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
  });
  
  C.lblSmsReplyOptions = widget.UI.Label("lblSmsReplyOptions", {
    tooltipHtml: "The Email address to forward any replies to."
  });
  C.txtReplyEmail = widget.UI.TextBox("txtReplyEmail", {
    maxLength: 200
  });

  // 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.txtApiKeyProduction.Text(mRecord.ApiKeyProduction);
    
    C.txtDeliveryReportsProduction.Text(mRecord.DeliveryReportsURIProduction);
    C.txtRepliesProduction.Text(mRecord.RepliesURIProduction);
    
    // Test Credentials
    C.txtRequestUrlTest.Text(mRecord.RequestUrlTest);
    
    C.txtApiKeyTest.Text(mRecord.ApiKeyTest);
    
    C.txtDeliveryReportsTest.Text(mRecord.DeliveryReportsURITest);
    C.txtRepliesTest.Text(mRecord.RepliesURITest);
    
    C.chkReturnMockResponsesTest.Value(mRecord.ReturnMockedResponseTest);
    C.cboSendToPhoneNumberTest.Text(mRecord.SendToPhoneNumberTest);
    
    // Options
    C.chkEnableSms.Value(mRecord.EnableSms);
    C.chkEnableSmsFeeCharging.Value(mRecord.EnableSmsFeeCharging);
    
    C.chkSharedNumber.Value(mRecord.SharedNumber);
    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);
    
    C.txtReplyEmail.Text(mRecord.ReplyEmail);
  }

  // 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.ApiKeyProduction = C.txtApiKeyProduction.Text();
  
  mRecord.DeliveryReportsURIProduction = C.txtDeliveryReportsProduction.Text();
  mRecord.RepliesURIProduction = C.txtRepliesProduction.Text();
  
  // Test Credentials
  mRecord.RequestUrlTest = C.txtRequestUrlTest.Text();
  
  mRecord.ApiKeyTest = C.txtApiKeyTest.Text();
  
  mRecord.DeliveryReportsURITest = C.txtDeliveryReportsTest.Text();
  mRecord.RepliesURITest = C.txtRepliesTest.Text();
  
  mRecord.ReturnMockedResponseTest = C.chkReturnMockResponsesTest.Value();
  mRecord.SendToPhoneNumberTest = C.cboSendToPhoneNumberTest.Text();
  
  // Options
  mRecord.EnableSms = C.chkEnableSms.Value();
  mRecord.EnableSmsFeeCharging = C.chkEnableSmsFeeCharging.Value();
  
  mRecord.SharedNumber = C.chkSharedNumber.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();
  
  mRecord.ReplyEmail = C.txtReplyEmail.Text();
}

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

  // Information Lists
  if (mRecord) {
  }

  // Lists
  if (mRecord) {
    // SMS Fusion does not currently have any test phone numbers
    // C.cboSendToPhoneNumberTest.ListFromCsvString(mRecord.ListSendToPhoneNumberTest);
  }

  // Controls
  if (mRecord) {
    // Production Credentials
    C.txtRequestUrlProduction.BlankTip(mRecord.RequestUrlProductionTooltip);
    
    C.txtDeliveryReportsProduction.BlankTip(mRecord.DeliveryReportsURIProductionTooltip);
    C.txtRepliesProduction.BlankTip(mRecord.RepliesURIProductionTooltip);

    // Test Credentials
    C.txtRequestUrlTest.BlankTip(mRecord.RequestUrlTestTooltip);
    
    C.txtDeliveryReportsTest.BlankTip(mRecord.DeliveryReportsURITestTooltip);
    C.txtRepliesTest.BlankTip(mRecord.RepliesURITestTooltip);    
    
    // 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.txtApiKeyProduction.WidthResizeFromParent();
      
      C.txtDeliveryReportsProduction.WidthResizeFromParent();
      C.txtRepliesProduction.WidthResizeFromParent();
      break;
      
    case "TestCredentials":
      // Test Credentials
      C.txtRequestUrlTest.WidthResizeFromParent();

      C.txtApiKeyTest.WidthResizeFromParent();
      
      C.txtDeliveryReportsTest.WidthResizeFromParent();
      C.txtRepliesTest.WidthResizeFromParent();
      break;
      
    case "Options":
      // Options
      C.txtDedicatedNumber.WidthResizeFromParent();
      C.txtSenderId.WidthResizeFromParent();
      C.txtFromName.WidthResizeFromParent();
      C.txtReplyEmail.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.chkSharedNumber.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());
  C.txtReplyEmail.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.chkSharedNumber.Value(sender === C.chkSharedNumber);
    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>gMeqv1qUCUqI-FZWgcGjLQ</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>