/**
* Script per creare un blocco HTML personalizzato per privacy e consensi
* da inserire in un form esistente
*/
(function () {
'use strict';
// Funzione per creare il blocco HTML
function createPrivacyConsentBlock(uniqueId) {
// Creazione del contenitore principale
const mainContainer = document.createElement('div');
mainContainer.className = 'privacy-consent-block';
if (uniqueId) {
mainContainer.id = 'privacy-consent-block-' + uniqueId;
}
// Sezione Privacy
const privacySection = createPrivacySection();
mainContainer.appendChild(privacySection);
// Separatore
const separator = document.createElement('hr');
separator.className = 'privacy-consent-separator';
mainContainer.appendChild(separator);
// Sezione Consensi
const consentiSection = createConsentiSection();
mainContainer.appendChild(consentiSection);
// Label di validazione per campi obbligatori
const validationLabel = document.createElement('div');
validationLabel.id = 'required-fields-validation';
validationLabel.className = 'validation-message';
validationLabel.textContent = '* Seleziona tutti i campi obbligatori';
mainContainer.appendChild(validationLabel);
return mainContainer;
}
// Funzione per creare la sezione Privacy
function createPrivacySection() {
const section = document.createElement('div');
section.className = 'privacy-section';
// Intestazione
const header = document.createElement('h3');
header.textContent = 'Condizioni di utilizzo, Informative Privacy';
section.appendChild(header);
// Checkbox principale "confirm_all"
const confirmAllDiv = createCheckbox(
'confirm_all',
'Dichiaro di aver letto e compreso l’informativa privacy. [LINK] per visualizzarli e selezionarli singolarmente',
'',
'Clicca qui',
'privacy'
);
section.appendChild(confirmAllDiv);
// Container per le 3 checkbox sottostanti (inizialmente nascosto)
const subCheckboxesContainer = document.createElement('div');
subCheckboxesContainer.id = 'privacy_sub_checkboxes';
subCheckboxesContainer.className = 'sub-checkboxes-container';
// 3 checkbox secondarie
const subCheckboxes = [
{ id: 'custom_con_terms_and_conditions', label: 'Termini e condizioni generali', linkUrl: 'https://www.quotidianosanitaclub.it/condizioni-uso' },
{ id: 'custom_con_privacy_terms', label: 'Informativa privacy Consulcesi SA', linkUrl: 'https://info.quotidianosanitaclub.it/privacy-policy' },
{ id: 'custom_con_privacy_terms_homnya', label: 'Informativa privacy Homnya', linkUrl: 'https://www.homnya.com/privacy-policy/' }
];
subCheckboxes.forEach(item => {
const checkboxDiv = createCheckbox(item.id, '',item.linkUrl, item.label);
subCheckboxesContainer.appendChild(checkboxDiv);
});
section.appendChild(subCheckboxesContainer);
// Gestione del click su confirm_all
const confirmAllCheckbox = section.querySelector('#confirm_all');
confirmAllCheckbox.addEventListener('click', function () {
const isChecked = this.checked;
const value = isChecked ;
subCheckboxes.forEach(item => {
const checkbox = document.getElementById(item.id);
if (checkbox) {
checkbox.checked = isChecked;
// Rimuovi il prefisso custom_ per ottenere il nome del campo HubSpot
const fieldName = item.id.replace('custom_', '');
// Imposta il valore per il campo
try {
console.log('Setting field for:', fieldName, 'Value:', value);
HubSpotFormsV4.getForms()[0].setFieldValue(`0-1/${fieldName}`, value.toString());
} catch (error) {
console.error('Error setting field value:', error);
}
}
});
// Verifica lo stato del pulsante submit dopo aver selezionato/deselezionato tutto
const allChecked = subCheckboxes.every(item => {
const checkbox = document.getElementById(item.id);
return checkbox && checkbox.checked;
});
const submitButtons = document.querySelectorAll('form.hsfc-Form button[type="submit"], form.hsfc-Form input[type="submit"]');
submitButtons.forEach(submitButton => {
if (submitButton) {
submitButton.disabled = !allChecked;
console.log('Submit button ' + (allChecked ? 'enabled' : 'disabled') + ' after confirm_all click');
}
});
// Mostra/nascondi la label di validazione
const validationLabel = document.getElementById('required-fields-validation');
if (validationLabel) {
validationLabel.classList.toggle('hidden', allChecked);
}
});
return section;
}
// Funzione per creare la sezione Consensi
function createConsentiSection() {
const section = document.createElement('div');
section.className = 'consensi-section';
// Intestazione Consensi
const header = document.createElement('h3');
header.textContent = 'Consensi';
section.appendChild(header);
// Checkbox principale "confirm_all_consensi"
const confirmAllConsentiDiv = createCheckbox(
'confirm_all_consensi',
'Accetto tutti i consensi Consulcesi SA e Homnya. [LINK] per visualizzarli e selezionarli singolarmente',
'',
'Clicca qui',
'consensi'
);
section.appendChild(confirmAllConsentiDiv);
// Container per le 5 checkbox sottostanti (inizialmente nascosto)
const subCheckboxesContainer = document.createElement('div');
subCheckboxesContainer.id = 'consensi_sub_checkboxes';
subCheckboxesContainer.className = 'sub-checkboxes-container';
// 5 checkbox con espansione
const consensi = [
{ id: 'custom_con_service_communications', label: 'Comunicazioni sui servizi Consulcesi SA e Homnya',description:'Con il tuo consenso, potrai ricevere newsletter, sondaggi, promozioni esclusive, comunicazioni su novità e nuovi prodotti e servizi, anche di partner terzi selezionati, attraverso i tuoi canali preferiti: e-mail, sms, whatsapp, telefono.' },
{ id: 'custom_con_sharing_with_third_parties', label: 'Condivisione con altre società Consulcesi SA e Homnya', description: 'Con il tuo consenso, i tuoi dati potranno essere comunicati a partner terzi, da cui riceverai informazioni su prodotti e servizi, richiesta di partecipare a sondaggi e ricevere inviti a eventi e iniziative dedicate.' },
{ id: 'custom_con_personalized_offers', label: 'Offerte personalizzate Consulcesi SA e Homnya', description: 'Con il tuo consenso, potremo personalizzare i contenuti e i servizi in base alle tue preferenze e ai tuoi interessi, nonché le nostre comunicazioni.' },
{ id: 'custom_con_medicalscientific_information', label: 'Informazione medico-scientifica Consulcesi SA e Homnya', description: 'Con il tuo consenso, e solo se operatore sanitario o professionista del settore, i tuoi dati potranno essere comunicati a società sanitarie, medicali o farmaceutiche convenzionate con il Titolare, per attività di informazione medico-scientifica.' }
];
consensi.forEach(item => {
const consensoDiv = createExpandableConsenso(item.id, item.label, item.description );
subCheckboxesContainer.appendChild(consensoDiv);
});
section.appendChild(subCheckboxesContainer);
// Gestione del click su confirm_all_consensi
const confirmAllConsentiCheckbox = section.querySelector('#confirm_all_consensi');
confirmAllConsentiCheckbox.addEventListener('click', function () {
const isChecked = this.checked;
const value = isChecked ;
consensi.forEach(item => {
// Seleziona/deseleziona la checkbox principale
const checkbox = document.getElementById(item.id);
if (checkbox) {
checkbox.checked = isChecked;
// Rimuovi il prefisso custom_ per ottenere il nome del campo HubSpot
const fieldName = item.id.replace('custom_', '');
// Imposta il valore per il campo base
try {
console.log('1. Setting fields for:', fieldName, 'Value:', value);
HubSpotFormsV4.getForms()[0].setFieldValue(`0-1/${fieldName}`, value.toString());
} catch (error) {
console.error('Error setting field values:', error);
}
}
});
});
return section;
}
// Funzione per creare una checkbox semplice
function createCheckbox(id, labelText, linkUrl = null, linkText = null, sectionType = null) {
console.log('createCheckbox called with - ID:', id);
const container = document.createElement('div');
container.className = 'checkbox-container';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = id;
checkbox.name = id;
const label = document.createElement('label');
label.htmlFor = id;
// Se c'è un link, cerca il placeholder [LINK] nel testo
if (linkText) {
const placeholder = '[LINK]';
if (labelText.includes(placeholder)) {
// Dividi il testo in parti prima e dopo il placeholder
const parts = labelText.split(placeholder);
// Aggiungi la prima parte del testo
if (parts[0]) {
label.appendChild(document.createTextNode(parts[0]));
}
// Crea e aggiungi il link
const link = document.createElement('a');
link.href = linkUrl || '#';
link.textContent = linkText;
link.target = '_blank';
link.className = 'privacy-link';
// Gestione del click sul link
link.addEventListener('click', function (e) {
// Se c'è sectionType, il link è un toggle (non naviga)
if (sectionType) {
e.preventDefault(); // Previene la navigazione
e.stopPropagation(); // Impedisce la propagazione dell'evento
if (sectionType === 'privacy') {
const subContainer = document.getElementById('privacy_sub_checkboxes');
if (subContainer) {
subContainer.classList.toggle('visible');
}
} else if (sectionType === 'consensi') {
const subContainer = document.getElementById('consensi_sub_checkboxes');
if (subContainer) {
subContainer.classList.toggle('visible');
}
}
}
// Altrimenti è un link normale che apre la pagina (nessun preventDefault)
});
label.appendChild(link);
// Aggiungi la parte rimanente del testo
if (parts[1]) {
label.appendChild(document.createTextNode(parts[1]));
}
} else {
// Se non c'è il placeholder, comportamento vecchio: testo + link alla fine
label.appendChild(document.createTextNode(labelText));
const link = document.createElement('a');
link.href = linkUrl;
link.textContent = linkText;
link.target = '_blank';
link.className = 'privacy-link';
link.addEventListener('click', function (e) {
// Se c'è sectionType, il link è un toggle (non naviga)
if (sectionType) {
e.preventDefault();
e.stopPropagation(); // Impedisce la propagazione dell'evento
if (sectionType === 'privacy') {
const subContainer = document.getElementById('privacy_sub_checkboxes');
if (subContainer) {
subContainer.classList.toggle('visible');
}
} else if (sectionType === 'consensi') {
const subContainer = document.getElementById('consensi_sub_checkboxes');
if (subContainer) {
subContainer.classList.toggle('visible');
}
}
}
// Altrimenti è un link normale che apre la pagina (nessun preventDefault)
});
label.appendChild(link);
}
} else {
// Nessun link: aggiungi solo il testo
label.appendChild(document.createTextNode(labelText));
}
// Aggiungi asterisco per le checkbox obbligatorie (confirm_all e le 3 figlie)
const requiredCheckboxes = [
'confirm_all',
'custom_con_terms_and_conditions',
'custom_con_privacy_terms',
'custom_con_privacy_terms_homnya'
];
if (requiredCheckboxes.includes(id)) {
const asterisk = document.createElement('span');
asterisk.className = 'required-asterisk';
asterisk.textContent = ' *';
label.appendChild(asterisk);
}
container.appendChild(checkbox);
container.appendChild(label);
// Aggiungi listener per il log in console
checkbox.addEventListener('click', function () {
console.log(`2. Checkbox cliccata - ID: ${this.id} - Checked: ${this.checked}`);
if (this.id.startsWith('confirm_all')) {
// Non mappare un campo specifico per la checkbox principale "confirm_all"
return;
}
//var fieldName = this.id.endsWith('_consulcesi') ? this.id.replace('_consulcesi', '') : this.id;
var fieldName = this.id.startsWith('custom_') ? this.id.replace('custom_', '') : this.id;
console.log('Field name derived from ID:', fieldName);
const value = this.checked;
try {
console.log('2. Setting fields for:', fieldName, 'Value:', value);
HubSpotFormsV4.getForms()[0].setFieldValue(`0-1/${fieldName}`, value.toString());
} catch (error) {
console.error('Error setting field value:', error);
}
// Controlla se questa è una delle 3 checkbox obbligatorie della sezione Privacy
const requiredCheckboxes = [
'custom_con_terms_and_conditions',
'custom_con_privacy_terms',
'custom_con_privacy_terms_homnya'
];
if (requiredCheckboxes.includes(this.id)) {
// Verifica se tutte e 3 le checkbox obbligatorie sono selezionate
const allChecked = requiredCheckboxes.every(cbId => {
const cb = document.getElementById(cbId);
return cb && cb.checked;
});
// Abilita/disabilita il pulsante submit
const submitButtons = document.querySelectorAll('form.hsfc-Form button[type="submit"], form.hsfc-Form input[type="submit"]');
submitButtons.forEach(submitButton => {
if (submitButton) {
submitButton.disabled = !allChecked;
console.log('Submit button ' + (allChecked ? 'enabled' : 'disabled') + ' - All required checkboxes: ' + allChecked);
}
});
// Mostra/nascondi la label di validazione
const validationLabel = document.getElementById('required-fields-validation');
if (validationLabel) {
validationLabel.classList.toggle('hidden', allChecked);
}
}
});
return container;
}
// Funzione per creare una checkbox espandibile con descrizione
function createExpandableConsenso(id, labelText, labelDescription) {
const container = document.createElement('div');
container.className = 'expandable-checkbox-container';
// Container per checkbox principale e freccia
const mainRow = document.createElement('div');
mainRow.className = 'expandable-main-row';
// Checkbox principale
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = id;
checkbox.name = id;
const label = document.createElement('label');
label.htmlFor = id;
label.textContent = labelText;
// Icona freccia per espandere/comprimere
const arrow = document.createElement('span');
arrow.className = 'toggle-arrow';
arrow.innerHTML = '▶'; // Freccia destra
mainRow.appendChild(checkbox);
mainRow.appendChild(label);
mainRow.appendChild(arrow);
// Sezione espandibile con descrizione
const expandableSection = document.createElement('div');
expandableSection.className = 'expandable-section';
// Label descrittiva
const description = document.createElement('p');
description.className = 'consent-description';
description.textContent = labelDescription;
expandableSection.appendChild(description);
container.appendChild(mainRow);
container.appendChild(expandableSection);
// Gestione del click sulla freccia
arrow.addEventListener('click', function () {
expandableSection.classList.toggle('visible');
arrow.classList.toggle('expanded');
});
// Aggiungi listener per il log in console sulla checkbox principale
checkbox.addEventListener('click', function () {
console.log(`3. Checkbox cliccata - ID: ${this.id} - Checked: ${this.checked}`);
const value = this.checked ;
// Rimuovi il prefisso custom_ per ottenere il nome del campo HubSpot
const fieldName = id.replace('custom_', '');
// Imposta il valore per il campo base (senza suffisso)
try {
console.log('3. Setting fields for:', fieldName, 'Value:', value);
HubSpotFormsV4.getForms()[0].setFieldValue(`0-1/${fieldName}`, value.toString());
} catch (error) {
console.error('Error setting base field value:', error);
}
});
return container;
}
// Funzione per inserire il blocco nel form
function insertBlockIntoForm(targetElement, uniqueId) {
if (targetElement) {
const block = createPrivacyConsentBlock(uniqueId);
targetElement.appendChild(block);
console.log('Blocco privacy e consensi inserito con successo');
} else {
console.error('Elemento target non trovato');
}
}
// Esponi le funzioni globalmente per l'uso esterno
window.PrivacyConsentBlock = {
create: createPrivacyConsentBlock,
insertInto: insertBlockIntoForm
};
// Auto-inizializzazione per form HubSpot
window.addEventListener('hs-form-event:on-ready', function () {
if (window.__hubspotPrivacyContentInitDone) {
return;
}
window.__hubspotPrivacyContentInitDone = true;
console.log('Evento hs-form-event:on-ready ricevuto');
// Cerca tutti gli elementi con classe 'privacy-consent-target'
const autoTargets = document.querySelectorAll('.privacy-consent-target');
if (autoTargets.length > 0) {
// Itera su tutti gli elementi trovati
autoTargets.forEach((target, index) => {
console.log('Inserimento blocco privacy per target ' + index);
insertBlockIntoForm(target, index);
});
return;
}
// Altrimenti, cerca i pulsanti con type="submit" all'interno di form con classe hsfc-Form
const submitButtons = document.querySelectorAll('form.hsfc-Form button[type="submit"], form.hsfc-Form input[type="submit"]');
if (submitButtons.length > 0) {
// Per ogni pulsante submit trovato, disabilita e inserisci il blocco privacy
submitButtons.forEach((submitButton, index) => {
// Disabilita il pulsante submit all'avvio
submitButton.disabled = true;
console.log('Submit button ' + index + ' disabled - waiting for required checkboxes');
// Crea un blocco privacy con ID univoco
const block = createPrivacyConsentBlock(index);
// Cerca il container NavigationRow__Buttons che è il parent del pulsante
const buttonsContainer = submitButton.closest('.hsfc-NavigationRow__Buttons');
if (buttonsContainer) {
// Inserisce il blocco PRIMA del container dei pulsanti, non dentro
buttonsContainer.parentNode.insertBefore(block, buttonsContainer);
console.log('Blocco privacy ' + index + ' inserito prima del container NavigationRow__Buttons');
} else {
// Fallback: inserisce prima del pulsante stesso
submitButton.parentNode.insertBefore(block, submitButton);
console.log('Blocco privacy ' + index + ' inserito prima del pulsante (fallback)');
}
});
} else {
console.warn('Pulsante submit non trovato. Il blocco privacy non è stato inserito automaticamente.');
}
});
})();