Repository navigation
Expand file tree
/
Copy pathbtnscript.js
More file actions
676 lines (595 loc) · 26.1 KB
/
Copy pathbtnscript.js
File metadata and controls
676 lines (595 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/*!
* Prenotazione Laboratorio Multimediale — Liceo di Follonica
* © 2026 Nicola Cantalupo — https://github.com/nicovoni/nicovoni.github.io
* Licenza MIT: puoi riutilizzare e modificare questo file mantenendo
* questo avviso di copyright. Vedi il file LICENSE.
*/
(function () {
// ---------------------------------------------------------------------------
// Dialog inline — sostituisce il confirm() nativo del browser,
// che può essere bloccato silenziosamente da policy di dominio o iframe.
// Iniettato una volta sola nel DOM al primo utilizzo.
// ---------------------------------------------------------------------------
var dialogIniettato = false;
function iniettatDialog() {
if (dialogIniettato) return;
dialogIniettato = true;
// Overlay + dialog
var overlay = document.createElement('div');
overlay.id = 'prenota-overlay';
overlay.innerHTML = [
'<div id="prenota-dialog" role="dialog" aria-modal="true" aria-labelledby="prenota-titolo">',
' <div id="prenota-icon">📅</div>',
' <div id="prenota-titolo">Conferma prenotazione</div>',
' <div id="prenota-dettagli"></div>',
' <div id="prenota-avviso" hidden></div>',
' <div id="prenota-azioni">',
' <button id="prenota-btn-annulla" type="button">Annulla</button>',
' <button id="prenota-btn-conferma" type="button">Prenota</button>',
' </div>',
'</div>'
].join('');
document.body.appendChild(overlay);
// Stili iniettati inline così non dipendono dall'ordine di caricamento del CSS
var style = document.createElement('style');
style.textContent = [
'#prenota-overlay {',
' position: fixed; inset: 0;',
' background: rgba(0,0,0,0.45);',
' display: flex; align-items: center; justify-content: center;',
' z-index: 9999;',
' opacity: 0; visibility: hidden;',
' transition: opacity 0.2s ease, visibility 0s linear 0.2s;',
' padding: 16px;',
'}',
'#prenota-overlay.aperto {',
' opacity: 1; visibility: visible;',
' transition: opacity 0.2s ease;',
'}',
'#prenota-dialog {',
' background: var(--bg-alt, #fff);',
' border: 1px solid var(--border, #e5e7eb);',
' border-radius: var(--radius, 12px);',
' box-shadow: var(--shadow-lg, 0 8px 32px rgba(0,0,0,0.15));',
' padding: 28px 28px 24px;',
' width: 100%; max-width: 340px;',
' text-align: center;',
' transform: translateY(8px);',
' transition: transform 0.2s ease;',
'}',
'#prenota-overlay.aperto #prenota-dialog {',
' transform: translateY(0);',
'}',
'#prenota-icon {',
' font-size: 32px; margin-bottom: 10px;',
'}',
'#prenota-titolo {',
' font-family: var(--font, inherit);',
' font-size: 16px; font-weight: 700;',
' color: var(--text, #111827);',
' margin-bottom: 8px;',
'}',
'#prenota-dettagli {',
' font-size: 14px;',
' color: var(--text-muted, #6b7280);',
' line-height: 1.6;',
' margin-bottom: 22px;',
'}',
'#prenota-avviso {',
' font-size: 13px; line-height: 1.5;',
' color: var(--ambra, #d97706);',
' background: rgba(217,119,6,0.12);',
' border: 1px solid rgba(217,119,6,0.35);',
' border-radius: var(--radius-sm, 8px);',
' padding: 8px 10px; margin: -8px 0 18px;',
'}',
'#prenota-avviso[hidden] { display: none; }',
'#prenota-dettagli strong {',
' color: var(--text, #111827);',
' font-weight: 600;',
'}',
'#prenota-azioni {',
' display: flex; gap: 10px;',
'}',
'#prenota-btn-annulla {',
' flex: 1; padding: 10px;',
' background: var(--bg, #f3f4f6);',
' border: 1px solid var(--border, #e5e7eb);',
' border-radius: var(--radius-sm, 8px);',
' font-size: 14px; font-weight: 600;',
' color: var(--text-muted, #6b7280);',
' cursor: pointer;',
' font-family: inherit;',
'}',
'#prenota-btn-conferma {',
' flex: 1; padding: 10px;',
' background: var(--primary, #1a56db);',
' border: none;',
' border-radius: var(--radius-sm, 8px);',
' font-size: 14px; font-weight: 600;',
' color: #fff;',
' cursor: pointer;',
' font-family: inherit;',
'}',
].join('\n');
document.head.appendChild(style);
// Chiudi cliccando l'overlay fuori dal dialog
overlay.addEventListener('click', function (e) {
if (e.target === overlay) chiudiDialog();
});
// Chiudi con Escape
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') chiudiDialog();
});
}
function apriDialog(slotOra, slotData, provvisoria, onConferma) {
iniettatDialog();
var avviso = document.getElementById('prenota-avviso');
avviso.hidden = !provvisoria;
avviso.textContent = provvisoria
? 'Attenzione: l\u2019orario di questa settimana non è definitivo e potrebbe cambiare. Verifica la prenotazione quando esce il nuovo orario.'
: '';
document.getElementById('prenota-dettagli').innerHTML =
'<strong>' + sanitizeInput(slotOra) + 'ª ora</strong> del <strong>' + sanitizeInput(slotData) + '</strong>';
var overlay = document.getElementById('prenota-overlay');
var btnConf = document.getElementById('prenota-btn-conferma');
var btnAnn = document.getElementById('prenota-btn-annulla');
// Rimuovi listener precedenti clonando i bottoni
var nuovoBtnConf = btnConf.cloneNode(true);
var nuovoBtnAnn = btnAnn.cloneNode(true);
btnConf.parentNode.replaceChild(nuovoBtnConf, btnConf);
btnAnn.parentNode.replaceChild(nuovoBtnAnn, btnAnn);
nuovoBtnConf.addEventListener('click', function () {
chiudiDialog();
onConferma();
});
nuovoBtnAnn.addEventListener('click', chiudiDialog);
overlay.classList.add('aperto');
nuovoBtnConf.focus();
}
function chiudiDialog() {
var overlay = document.getElementById('prenota-overlay');
if (overlay) overlay.classList.remove('aperto');
}
// ---------------------------------------------------------------------------
// btnprenota — chiamata dal onclick="btnprenota(this)" nelle celle
// ---------------------------------------------------------------------------
function btnprenota(button) {
try {
if (!button || !button.parentNode) {
throw new Error("Elemento pulsante non valido o mancante.");
}
var cella = button.parentNode;
var slotOra = cella.getAttribute("slotora");
var slotData = cella.getAttribute("slotdata");
if (!slotOra || !slotData) {
throw new Error("Dati mancanti per la prenotazione.");
}
var msgBlocco = verificaPrenotabile(slotData);
if (msgBlocco) {
alert(msgBlocco);
return;
}
var wrapper = cella.closest('.settimana-wrapper');
var provvisoria = !!(wrapper && wrapper.classList.contains('provvisoria'));
apriDialog(slotOra, slotData, provvisoria, function () {
var baseURL = "https://script.google.com/a/macros/isufol.it/s/AKfycbzN1P6AhCc0j47KShHcBnYooPegm2fA0zNbeSXUQymm_7Gv6Kc_blcoh5AZEJf6uO8M/exec";
var url = buildSafeURL(baseURL, { slotOra: slotOra, slotData: slotData });
window.location.href = url;
});
} catch (error) {
console.error("Errore durante la prenotazione:", error);
alert("Si è verificato un errore durante la prenotazione. Riprova più tardi.");
}
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
function buildSafeURL(baseURL, params) {
var url = new URL(baseURL);
for (var key in params) {
if (params.hasOwnProperty(key)) {
url.searchParams.append(key, params[key]);
}
}
return url.toString();
}
function sanitizeInput(input) {
return String(input).replace(/</g, "<").replace(/>/g, ">").trim();
}
// ---------------------------------------------------------------------------
// Regole di prenotazione lato pagina (solo usabilità: il controllo vero è sul server)
// ---------------------------------------------------------------------------
var ANTICIPO_MIN_GIORNI = 1;
// Fascia oraria: nessun orario è scritto in questo file. Arriva dal foglio "impostazioni" tramite
// gli attributi data-fascia-dalle / data-fascia-fino di <body>, scritti da generaPaginaOrario().
// Se mancano o non sono validi la fascia è null e le prenotazioni restano bloccate
// (il server rifiuta comunque quelle fuori orario).
function oraInMinuti(testo) {
var m = /^(\d{1,2}):(\d{2})$/.exec(String(testo || '').trim());
if (!m || +m[1] > 23 || +m[2] > 59) return null;
return +m[1] * 60 + +m[2];
}
function leggiFascia() {
var dalle = document.body.getAttribute('data-fascia-dalle');
var fino = document.body.getAttribute('data-fascia-fino');
var a = oraInMinuti(dalle), b = oraInMinuti(fino);
if (a === null || b === null || a >= b) return null;
return { dalle: dalle, fino: fino, dalMin: a, alMin: b };
}
var FASCIA = leggiFascia();
function pad2(n) { return String(n).padStart(2, '0'); }
function giorniDaIso(iso) {
var p = iso.split('-');
return Date.UTC(+p[0], +p[1] - 1, +p[2]) / 86400000;
}
// Ora di Roma (non quella del browser): stesso fuso usato dal server
function fasciaAperta() {
if (!FASCIA) return false;
var a = adessoRoma(); // "YYYY-MM-DDTHH:MM"
var m = +a.slice(11, 13) * 60 + +a.slice(14, 16);
return m >= FASCIA.dalMin && m <= FASCIA.alMin;
}
// Restituisce '' se prenotabile, altrimenti il motivo del blocco
function verificaPrenotabile(slotData) {
var p = slotData.split('/');
var oggi = adessoRoma().slice(0, 10); // data di oggi a Roma
var anticipo = giorniDaIso(p[2] + '-' + p[1] + '-' + p[0]) - giorniDaIso(oggi);
if (anticipo < ANTICIPO_MIN_GIORNI) {
return 'Non è possibile prenotare per oggi o per giorni passati: serve almeno un giorno di anticipo.';
}
if (!fasciaAperta()) {
if (!FASCIA) return 'Orario di prenotazione non disponibile: ricarica la pagina.';
return 'Le prenotazioni sono aperte dalle ' + FASCIA.dalle + ' alle ' + FASCIA.fino + '.';
}
return '';
}
// ---------------------------------------------------------------------------
// SETTIMANE: stato in base all'orologio di Roma
// corrente : dalle 08:00 del lunedì alla fine della 6ª ora del venerdì (13:40)
// passata : dalla fine della 6ª ora del venerdì alle 08:00 del lunedì successivo, poi sparisce
// prossima : la settimana subito dopo la corrente; con la passata ancora visibile (da venerdì 13:40
// a lunedì 08:00) la stessa settimana è etichettata "Settimana in arrivo"
// Si mostrano la passata (se c'è) e 3 settimane prenotabili.
// ---------------------------------------------------------------------------
var INIZIO_SETTIMANA = '08:00';
var FINE_SETTIMANA = '13:40';
var SETTIMANE_PRENOTABILI = 3;
var fmtRoma = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Rome', year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', hourCycle: 'h23'
});
// "2026-11-15T10:20" (ora di Roma): si confronta come testo
function adessoRoma() {
var o = {};
fmtRoma.formatToParts(new Date()).forEach(function (p) { o[p.type] = p.value; });
return o.year + '-' + o.month + '-' + o.day + 'T' + o.hour + ':' + o.minute;
}
function isoPiuGiorni(iso, n) {
var p = iso.split('-');
var d = new Date(Date.UTC(+p[0], +p[1] - 1, +p[2] + n));
return d.getUTCFullYear() + '-' + pad2(d.getUTCMonth() + 1) + '-' + pad2(d.getUTCDate());
}
function statoSettimana(w, adesso) {
var lun = w.getAttribute('data-lunedi');
var ven = w.getAttribute('data-venerdi');
if (!lun || !ven) return 'futura';
if (adesso >= isoPiuGiorni(lun, 7) + 'T' + INIZIO_SETTIMANA) return 'nascosta';
if (adesso >= ven + 'T' + FINE_SETTIMANA) return 'passata';
if (adesso >= lun + 'T' + INIZIO_SETTIMANA) return 'corrente';
return 'futura';
}
function creaBadge(classe, testo) {
var b = document.createElement('span');
b.className = classe;
b.textContent = testo;
return b;
}
// Solo mobile, solo all'apertura: la pagina parte dalla card del giorno corrente (le card dei giorni
// precedenti restano più in alto, raggiungibili scorrendo). Si usa la data di Roma, come il resto del file.
var scrollIniziale = false;
var scrollImpostato = null;
function scorriAlGiornoCorrente() {
if (!window.matchMedia('(max-width: 768px)').matches) return;
var attiva = document.querySelector('.settimana-wrapper.tab-attiva');
if (!attiva) return;
var p = adessoRoma().slice(0, 10).split('-');
var cella = attiva.querySelector('td[slotdata="' + p[2] + '/' + p[1] + '/' + p[0] + '"]');
var riga = cella && cella.closest('tr');
if (!riga) return; // oggi non è nella settimana mostrata (weekend, settimana futura)
var prima = attiva.querySelector('tbody tr');
if (prima === riga) return; // lunedì: si resta in cima (titolo e legenda visibili)
scrollImpostato = Math.max(0, Math.round(riga.getBoundingClientRect().top + window.pageYOffset - altezzaBarreFisse()));
window.scrollTo(0, scrollImpostato);
}
function aggiornaSettimane() {
var adesso = adessoRoma();
var validoFino = document.body.getAttribute('data-valido-fino') || '';
var prenotabiliViste = 0;
var prossimaAssegnata = false;
var passataVista = false; // dal venerdì (13:40) al lunedì (08:00) la prima settimana dopo la passata è "in arrivo"
var daMostrareDiDefault = null;
document.querySelectorAll('.settimana-wrapper').forEach(function (w) {
var num = w.id.replace('settimana-', '');
var tab = document.getElementById('tab-' + num);
var stato = statoSettimana(w, adesso);
var mostra = stato !== 'nascosta';
if (mostra && stato !== 'passata') {
if (prenotabiliViste >= SETTIMANE_PRENOTABILI) mostra = false;
else prenotabiliViste++;
}
if (mostra && stato === 'passata') passataVista = true;
var inArrivo = false;
if (mostra && stato === 'futura' && !prossimaAssegnata) {
stato = 'prossima';
prossimaAssegnata = true;
inArrivo = passataVista;
}
// Se manca la data di validità, le settimane non passate risultano non definitive (caso sicuro)
var ven = w.getAttribute('data-venerdi') || '';
var prov = mostra && stato !== 'passata' && (!validoFino || ven > validoFino);
w.classList.toggle('nascosta', !mostra);
w.classList.toggle('passata', stato === 'passata');
w.classList.toggle('provvisoria', prov);
var tabella = w.querySelector('table.container');
if (tabella) tabella.classList.toggle('settimana-corrente', stato === 'corrente');
if (tab) {
tab.classList.toggle('nascosta', !mostra);
tab.classList.toggle('passata', stato === 'passata');
tab.classList.toggle('corrente', stato === 'corrente');
tab.classList.toggle('provvisoria', prov);
}
// Badge: si ricostruiscono solo se lo stato è cambiato
var chiave = stato + '|' + prov + '|' + mostra + '|' + inArrivo;
if (w.getAttribute('data-chiave') !== chiave) {
w.setAttribute('data-chiave', chiave);
var label = w.querySelector('.settimana-label');
if (label) {
label.textContent = '';
label.classList.toggle('corrente', stato === 'corrente');
if (stato === 'corrente') label.appendChild(creaBadge('badge-corrente', 'Settimana corrente'));
if (stato === 'prossima') label.appendChild(creaBadge('badge-prossima', inArrivo ? 'Settimana in arrivo' : 'Prossima settimana'));
if (stato === 'passata') label.appendChild(creaBadge('badge-passata', 'Settimana passata'));
if (prov) label.appendChild(creaBadge('badge-provvisoria', 'Orario non definitivo'));
}
}
// Scheda mobile iniziale: la corrente, altrimenti la prossima
if (mostra && (stato === 'corrente' || (stato === 'prossima' && daMostrareDiDefault === null))) {
daMostrareDiDefault = num;
}
});
// Su mobile: se nessuna scheda è attiva (primo caricamento) o la scheda attiva è sparita, si sceglie quella giusta
var attiva = document.querySelector('.settimana-wrapper.tab-attiva');
if ((!attiva || attiva.classList.contains('nascosta')) && daMostrareDiDefault !== null) {
mostraTab(daMostrareDiDefault);
}
document.body.classList.add('pronta');
if (!scrollIniziale) {
scrollIniziale = true;
scorriAlGiornoCorrente();
// A caricamento completo font e immagini possono spostare di poco il layout: si riallinea
// solo se l'utente non ha ancora scrollato (né il browser ha ripristinato un'altra posizione).
window.addEventListener('load', function () {
if (scrollImpostato !== null && Math.abs(window.pageYOffset - scrollImpostato) <= 2) scorriAlGiornoCorrente();
});
}
}
// Pulsanti attivi/disattivi, avviso fascia
function aggiornaStato() {
aggiornaSettimane();
document.querySelectorAll('.btn-aggiungi').forEach(function (b) {
var data = b.parentNode ? b.parentNode.getAttribute('slotdata') : null;
var msg = data ? verificaPrenotabile(data) : '';
b.disabled = !!msg;
b.title = msg;
});
var av = document.getElementById('avviso-fascia');
if (av) av.classList.toggle('chiuso', !fasciaAperta());
}
aggiornaStato();
setInterval(aggiornaStato, 30000);
// Esporta globalmente
window.btnprenota = btnprenota;
})();
// ---------------------------------------------------------------------------
// Gestione tab mobile per navigazione tra settimane
// ---------------------------------------------------------------------------
// Spazio occupato in alto dalle barre fisse (header del sito + barra delle settimane) più un po' d'aria
function altezzaBarreFisse() {
var header = document.querySelector('.site-header');
var tabs = document.getElementById('tabs');
return (header ? header.offsetHeight : 0) + (tabs ? tabs.offsetHeight : 0) + 8;
}
function mostraTab(numero) {
document.querySelectorAll('.settimana-wrapper').forEach(function (w) { w.classList.remove('tab-attiva'); });
document.querySelectorAll('.tab-btn').forEach(function (t) { t.classList.remove('attiva'); });
var target = document.getElementById('settimana-' + numero);
var tabAttiva = document.getElementById('tab-' + numero);
if (target) target.classList.add('tab-attiva');
if (tabAttiva) tabAttiva.classList.add('attiva');
// Su schermi stretti la barra scorre in orizzontale: la scheda attiva viene portata al centro
if (tabAttiva && tabAttiva.parentNode) {
var barra = tabAttiva.parentNode;
var rt = tabAttiva.getBoundingClientRect(), rb = barra.getBoundingClientRect();
barra.scrollLeft += (rt.left - rb.left) - (barra.clientWidth - rt.width) / 2;
}
}
// ---------------------------------------------------------------------------
// BARRA DI PROGRESSO ORARIA
// Colora le celle del giorno corrente in base all'ora attuale.
//
// Scansione oraria:
// 1ª 08:00 – 08:50 (50 min)
// 2ª 08:50 – 09:45 (55 min)
// --- ricreazione 09:45 – 09:55 ---
// 3ª 09:55 – 10:50 (55 min)
// 4ª 10:50 – 11:45 (55 min)
// --- ricreazione 11:45 – 11:55 ---
// 5ª 11:55 – 12:50 (55 min)
// 6ª 12:50 – 13:40 (50 min)
//
// Logica:
// - Prima delle 08:00: nessun effetto
// - Ora passata: cella colorata al 100%
// - Ora in corso: cella colorata proporzionalmente ai minuti trascorsi
// - Ora futura: nessun effetto
// - Dopo le 13:40: tutte le celle al 100%
//
// Tecnica: background-image con linear-gradient sovrapposto al colore
// esistente della cella, così spazioprenotato/dada/orario-fisso restano
// leggibili. L'attributo slotdata sulla cella viene confrontato con la
// data odierna per agire solo sulla riga del giorno corrente.
// ---------------------------------------------------------------------------
(function () {
// Slot orari: [oraInizio, minutoInizio, oraFine, minutoFine]
var SLOT = [
[8, 0, 8, 50], // 1ª ora
[8, 50, 9, 45], // 2ª ora
[9, 55, 10, 50], // 3ª ora (dopo ricreazione)
[10, 50, 11, 45], // 4ª ora
[11, 55, 12, 50], // 5ª ora (dopo ricreazione)
[12, 50, 13, 40], // 6ª ora
[13, 40, 14, 30], // 7ª ora
];
// Colori della striscia sul fondo della cella
var COLORE_PASSATO = '#94a3b8'; // grigio-blu, ora completamente passata
var COLORE_INCORSO = '#1a56db'; // blu primario, ora in corso
var COLORE_SETTIMA = '#ff1a1a'; // rosso acceso, 7ª ora
/**
* Restituisce la data odierna formattata "dd/MM/yyyy"
*/
function oggiFormattato() {
var d = new Date();
var dd = String(d.getDate()).padStart(2, '0');
var mm = String(d.getMonth() + 1).padStart(2, '0');
var yyyy = d.getFullYear();
return dd + '/' + mm + '/' + yyyy;
}
/**
* Calcola i minuti dall'inizio della giornata per un orario hh:mm
*/
function toMinuti(h, m) { return h * 60 + m; }
/**
* Applica la striscia di avanzamento sul fondo della cella.
* Usa un <div> assoluto largo pct% — completamente indipendente
* dal background della cella, visibile su qualsiasi colore di sfondo.
*/
// Id univoco della barra: la 7ª ora ha due versioni (mobile e desktop)
function idBarra(cella) {
return 'barra-ora-' + cella.getAttribute('slotora') + '-' +
cella.getAttribute('slotdata').replace(/\//g, '') +
(cella.classList.contains('settima-desktop') ? '-d' : '');
}
function applicaStriscia(cella, pct, incorso) {
// Non sovrascrivere position:absolute della 7ª ora desktop
if (window.getComputedStyle(cella).position === 'static') {
cella.style.position = 'relative';
}
var id = idBarra(cella);
var barra = document.getElementById(id);
if (!barra) {
barra = document.createElement('div');
barra.id = id;
barra.style.cssText = [
'position:absolute',
'bottom:0',
'left:0',
'height:3px',
'border-radius:0 2px 2px 0',
'transition:width 0.6s ease, background-color 0.3s ease',
'pointer-events:none',
'z-index:1',
].join(';');
cella.appendChild(barra);
}
barra.style.width = Math.min(pct, 100) + '%';
var oraCella = parseInt(cella.getAttribute('slotora'), 10);
barra.style.backgroundColor = (oraCella === 7)
? COLORE_SETTIMA
: (incorso ? COLORE_INCORSO : COLORE_PASSATO);
cella.style.backgroundImage = '';
}
function rimuoviStriscia(cella) {
cella.style.backgroundImage = '';
var barra = document.getElementById(idBarra(cella));
if (barra) barra.style.width = '0';
}
/**
* Aggiorna tutte le celle della tabella per il giorno corrente.
* Viene chiamata subito al caricamento e poi ogni 60 secondi.
*/
function aggiorna() {
var oggi = oggiFormattato();
var adesso = new Date();
var minutiAdesso = toMinuti(adesso.getHours(), adesso.getMinutes());
// Seleziona tutte le celle con attributo slotdata uguale a oggi
var celle = document.querySelectorAll(
'td[slotdata="' + oggi + '"], div.settima-desktop[slotdata="' + oggi + '"]'
);
if (celle.length === 0) return; // giorno non presente nella pagina (weekend, fuori range)
celle.forEach(function (cella) {
var ora = parseInt(cella.getAttribute('slotora'), 10);
if (!ora || ora < 1 || ora > 7) return;
var slot = SLOT[ora - 1];
var inizioMin = toMinuti(slot[0], slot[1]);
var fineMin = toMinuti(slot[2], slot[3]);
var durataMin = fineMin - inizioMin;
if (minutiAdesso < inizioMin) {
// Ora futura: nessun effetto
rimuoviStriscia(cella);
} else if (minutiAdesso >= fineMin) {
// Ora completamente passata: 100%
applicaStriscia(cella, 100, false);
} else {
// Ora in corso: percentuale proporzionale ai minuti trascorsi
var trascorsi = minutiAdesso - inizioMin;
var pct = Math.round((trascorsi / durataMin) * 100);
applicaStriscia(cella, pct, true);
}
});
}
// Piccolo delay per garantire che il DOM sia completamente renderizzato
// prima della prima esecuzione, poi aggiornamento ogni 60 secondi.
setTimeout(function() {
aggiorna();
setInterval(aggiorna, 60000);
}, 300);
})();
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// 7ª ORA A COMPARSA (solo desktop)
// ---------------------------------------------------------------------------
function toggleSettima(btn) {
var cella = document.getElementById(btn.getAttribute('aria-controls'));
if (!cella) return;
var aprire = !cella.classList.contains('aperta');
cella.classList.toggle('aperta', aprire);
var testo = aprire ? 'Nascondi la 7ª ora' : 'Mostra la 7ª ora';
btn.setAttribute('aria-expanded', aprire ? 'true' : 'false');
btn.setAttribute('aria-label', testo);
btn.title = testo;
posizionaSettima(cella);
}
// La cella è assoluta nel wrapper: allineo top e altezza alla riga del giorno.
function posizionaSettima(cella) {
if (!window.matchMedia('(min-width: 769px)').matches || !cella.classList.contains('aperta')) {
cella.style.top = '';
cella.style.height = '';
cella.style.width = '';
return;
}
var btn = document.querySelector('[aria-controls="' + cella.id + '"]');
var riga = btn ? btn.closest('tr') : null;
var wrapper = cella.closest('.settimana-wrapper');
if (!riga || !wrapper) return;
var r = riga.getBoundingClientRect();
var w = wrapper.getBoundingClientRect();
// Stessa larghezza e altezza delle altre celle della riga (la cella della 6ª ora fa da modello)
var cellaOra = btn.closest('td');
cella.style.top = (r.top - w.top) + 'px';
cella.style.height = r.height + 'px';
if (cellaOra) cella.style.width = cellaOra.getBoundingClientRect().width + 'px';
}
window.addEventListener('resize', function () {
document.querySelectorAll('.settima-desktop').forEach(posizionaSettima);
});