Differenze

Queste sono le differenze tra la revisione selezionata e la versione attuale della pagina.

Link a questa pagina di confronto

Entrambe le parti precedenti la revisioneRevisione precedente
Prossima revisione
Revisione precedente
docuneo:programma_npt [2025/07/31 22:11] neoadmindocuneo:programma_npt [2025/08/11 15:34] (versione attuale) neoadmin
Linea 3: Linea 3:
     <meta charset="UTF-8">     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>Programma NPT Neonatale v2.0 con BUN</title>+    <title>Programma NPT Neonatale v3.0 - Versione Unificata</title> 
 +    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script> 
 +    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script> 
 +     
 +    <script> 
 +    // Simple Barcode Generator - CODE128 - Versione Embedded 
 +    window.SimpleBarcode = (function() { 
 +         
 +    // Patterns per CODE128 
 +    const patterns = { 
 +        '0': '11011001100', '1': '11001101100', '2': '11001100110', '3': '10010011000', '4': '10010001100', 
 +        '5': '10001001100', '6': '10011001000', '7': '10011000100', '8': '10001100100', '9': '11001001000', 
 +        '10': '11001000100', '11': '11000100100', '12': '10110011100', '13': '10011011100', '14': '10011001110', 
 +        '15': '10111001100', '16': '10011101100', '17': '10011100110', '18': '11001110010', '19': '11001011100', 
 +        '20': '11001001110', '21': '11011100100', '22': '11001110100', '23': '11101010000', '24': '11101000100', 
 +        '25': '11100010100', '26': '11100000110', '27': '11101100000', '28': '11100110000', '29': '11100001100', 
 +        '30': '11010011000', '31': '11010000110', '32': '11000110100', '33': '10100011000', '34': '10001011000', 
 +        '35': '10001000110', '36': '10110001000', '37': '10001101000', '38': '10001100010', '39': '11010001100', 
 +        '40': '11000101100', '41': '11000100110', '42': '10110111000', '43': '10110001110', '44': '10001101110', 
 +        '45': '10111011000', '46': '10111000110', '47': '10001110110', '48': '11101110110', '49': '11010001110', 
 +        '50': '11000101110', '51': '11011101000', '52': '11011100010', '53': '11011101110', '54': '11101011000', 
 +        '55': '11101000010', '56': '11100010010', '57': '11101101000', '58': '11101100010', '59': '11100011010', 
 +        '60': '11101111010', '61': '11001000010', '62': '11110001010', '63': '10100110000', '64': '10100001100', 
 +        '65': '10010110000', '66': '10010000110', '67': '10000101100', '68': '10000100110', '69': '10110010000', 
 +        '70': '10110000100', '71': '10011010000', '72': '10011000010', '73': '10000110100', '74': '10000110010', 
 +        '75': '11000010010', '76': '11001010000', '77': '11110111010', '78': '11000010100', '79': '10001111010', 
 +        '80': '10100111100', '81': '10010111100', '82': '10010011110', '83': '10111100100', '84': '10011110100', 
 +        '85': '10011110010', '86': '11110100100', '87': '11110010100', '88': '11110010010', '89': '11011011110', 
 +        '90': '11011110110', '91': '11110110110', '92': '10101111000', '93': '10100011110', '94': '10001011110', 
 +        '95': '10111101000', '96': '10111100010', '97': '11110101000', '98': '11110100010', '99': '10111011110', 
 +        '100': '10111101110', '101': '11101011110', '102': '11110101110', '103': '11010000100', '104': '11010010000',  
 +        '105': '11010011100', 'STOP': '1100011101011' 
 +    }; 
 +     
 +    function generateCode128(text) { 
 +        // START B (per caratteri ASCII normali) 
 +        let result = patterns['104']; 
 +        let checksum = 104; 
 +         
 +        // Aggiungi ogni carattere 
 +        for (let i = 0; i < text.length; i++) { 
 +            const charCode = text.charCodeAt(i) - 32; // ASCII offset 
 +            if (patterns[charCode.toString()]) { 
 +                result += patterns[charCode.toString()]; 
 +                checksum += charCode * (i + 1); 
 +            } 
 +        } 
 +         
 +        // Calcola e aggiungi checksum 
 +        checksum = checksum % 103; 
 +        result += patterns[checksum.toString()]; 
 +         
 +        // Aggiungi STOP 
 +        result += patterns['STOP']; 
 +         
 +        return result; 
 +    } 
 +     
 +    function drawBarcode(canvas, text, options = {}) { 
 +        const ctx = canvas.getContext('2d'); 
 +        const data = generateCode128(text); 
 +         
 +        // Opzioni default 
 +        const opts = { 
 +            width: options.width || 2, 
 +            height: options.height || 60, 
 +            margin: options.margin || 5, 
 +            background: options.background || '#ffffff', 
 +            lineColor: options.lineColor || '#000000' 
 +        }; 
 +         
 +        // Calcola dimensioni 
 +        const barWidth = opts.width; 
 +        const totalWidth = data.length * barWidth + (opts.margin * 2); 
 +        const totalHeight = opts.height + (opts.margin * 2); 
 +         
 +        // Imposta dimensioni canvas 
 +        canvas.width = totalWidth; 
 +        canvas.height = totalHeight; 
 +         
 +        // Pulisci canvas 
 +        ctx.clearRect(0, 0, totalWidth, totalHeight); 
 +         
 +        // Background 
 +        ctx.fillStyle = opts.background; 
 +        ctx.fillRect(0, 0, totalWidth, totalHeight); 
 +         
 +        // Disegna le barre 
 +        ctx.fillStyle = opts.lineColor; 
 +        let x = opts.margin; 
 +         
 +        for (let i = 0; i < data.length; i++) { 
 +            if (data[i] === '1') { 
 +                ctx.fillRect(x, opts.margin, barWidth, opts.height); 
 +            } 
 +            x += barWidth; 
 +        } 
 +         
 +        console.log('Codice a barre generato:', text); 
 +    } 
 +     
 +    return { 
 +        generate: drawBarcode 
 +    }; 
 +})(); 
 +</script> 
 +    
     <style>     <style>
 +        * {
 +            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
 +}
         body {         body {
-            font-family: Arial, sans-serif; +        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
-            margin: 0; +        margin: 0; 
-            padding: 20px; +        padding: 20px; 
-            background-color: #f5f5f5; +        background-color: #f5f5f5; 
-        }+}
  
         .container {         .container {
Linea 22: Linea 131:
  
         h1 {         h1 {
 +           
 +    text-align: center;
 +    color: white;
 +    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 50%, #16a085 100%);
 +    border: none;
 +    padding: 20px;
 +    border-radius: 10px;
 +    margin-bottom: 20px;
 +    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
 +    position: relative;
 +    overflow: hidden;
 +}
 +
 +h1::before {
 +    content: "👶";
 +    font-size: 30px;
 +    position: absolute;
 +    left: 20px;
 +    top: 50%;
 +    transform: translateY(-50%);
 +}
 +        }
 +
 +        .version-info {
             text-align: center;             text-align: center;
-            color#2c3e50+            font-size12px
-            border-bottom3px solid #3498db+            color: #7f8c8d
-            padding-bottom: 10px;+            margin-bottom: 20px;
         }         }
  
Linea 210: Linea 343:
  
         .hidden {         .hidden {
-            display: none !important;+            display: none;
         }         }
  
-        .visible { +        /* CSS TAB ORIZZONTALI CORRETTI */
-            display: block !important; +
-        } +
- +
-        /* CSS TAB ORIZZONTALI */+
         .tabs {         .tabs {
             display: flex;             display: flex;
Linea 226: Linea 355:
  
         .tab {         .tab {
-            padding: 10px 20px;+            padding: 8px 15px;
             background-color: #ecf0f1;             background-color: #ecf0f1;
             border: 1px solid #ddd;             border: 1px solid #ddd;
Linea 234: Linea 363:
             transition: all 0.3s ease;             transition: all 0.3s ease;
             text-align: center;             text-align: center;
-            min-width: 120px;+            min-width: 100px;
             flex: 1;             flex: 1;
-            max-width: 200px;+            max-width: 160px; 
 +            font-size: 14px; 
 +            font-weight: bold; 
 +        } 
 +        .config-tab { 
 +        min-width: 50px !important; 
 +        max-width: 50px !important; 
 +        width: 50px !important; 
 +        flex: 0 0 50px !important; 
 +        font-size: 24px !important; 
 +        padding: 12px 8px !important; 
 +        transform: none !important; 
 +        } 
 + 
 +        .config-tab:hover { 
 +            background-color: #d5dbdb; 
 +            transform: none !important; 
 +        } 
 + 
 +        .config-tab.active { 
 +            background-color: #3498db; 
 +            color: white; 
 +            transform: none !important;
         }         }
  
Linea 311: Linea 462:
         }         }
  
-        /* STILI PER IL REPORT NPT */ +        .config-table 
-        .npt-report +            width100%
-            backgroundwhite+            border-collapsecollapse
-            padding20px+            margin15px 0;
-            font-familyArial, sans-serif;+
             font-size: 12px;             font-size: 12px;
-            line-height: 1.4; 
-            max-width: 800px; 
-            margin: 0 auto; 
-            border: 1px solid #ddd; 
         }         }
  
-        .report-header { +        .config-table th, .config-table td 
-            display: flex; +            border: 1px solid #ddd
-            justify-content: space-between; +            padding: 6px
-            align-items: center; +            text-aligncenter;
-            border-bottom2px solid #333+
-            padding-bottom10px+
-            margin-bottom20px;+
         }         }
  
-        .report-header-left +        .config-table th 
-            flex1;+            background-color: #34495e; 
 +            colorwhite;
         }         }
  
-        .report-header-right +        .config-table input 
-            width: 100px; +            width: 60px; 
-            height: 60px; +            padding3px
-            background-color#e8f4f8+            border: 1px solid #ddd
-            border: 1px solid #ccc+            border-radius3px;
-            display: flex; +
-            align-itemscenter; +
-            justify-content: center; +
-            font-size: 10px; +
-            color: #666;+
         }         }
  
-        .report-title { +        .component-name {
-            font-size: 14px;+
             font-weight: bold;             font-weight: bold;
-            margin-bottom5px;+            background-color#f8f9fa; 
 +            text-align: left !important;
         }         }
  
-        .report-subtitle +        /* SEZIONE NUOVA PER TAB 5 CONFIGURAZIONE AVANZATA */ 
-            font-size11px+        .config-advanced 
-            color: #666+            background-color#f8f9fa
-            margin-bottom15px;+            border2px solid #17a2b8
 +            border-radius: 10px; 
 +            padding: 20px; 
 +            margin20px 0;
         }         }
  
-        .report-section +        .config-advanced h3 { 
-            margin-bottom: 20px;+            color: #0c5460; 
 +            margin-top: 0; 
 +            border-bottom: 2px solid #17a2b8; 
 +            padding-bottom: 10px;
         }         }
  
-        .report-section-title { +        .monitoring-table {
-            background-color: #333; +
-            color: white; +
-            padding: 5px 10px; +
-            font-weight: bold; +
-            font-size: 12px; +
-            margin-bottom: 0; +
-        } +
- +
-        .report-table {+
             width: 100%;             width: 100%;
             border-collapse: collapse;             border-collapse: collapse;
-            font-size: 11px;+            margin: 15px 0; 
 +            font-size: 12px;
         }         }
  
-        .report-table td { +        .monitoring-table th, .monitoring-table td { 
-            padding: 3px 8px; +            border: 1px solid #17a2b8; 
-            border-bottom: 1px solid #ddd+            padding: 8px
-            vertical-align: top;+            text-align: left;
         }         }
  
-        .report-table .label-col +        .monitoring-table th 
-            width200px+            background-color#17a2b8
-            font-weightnormal;+            colorwhite;
         }         }
  
-        .report-table .value-col +        .alert-critical 
-            text-alignright;+            background-color: #721c24; 
 +            color: white; 
 +            padding: 15px; 
 +            border-radius: 5px; 
 +            margin15px 0;
             font-weight: bold;             font-weight: bold;
         }         }
  
-        .composition-table +        /* REPORT SECTION */ 
-            width100%+        .report-output 
-            border-collapsecollapse+            border2px solid #3498db
-            font-size11px+            border-radius10px
-            margin-top: 0;+            padding30px
 +            margin-top: 30px; 
 +            background-color: white; 
 +            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
 +            line-height: 1.6;
         }         }
  
-        .composition-table th { +        .medical-header {
-            background-color: #f0f0f0; +
-            padding: 5px 8px;+
             text-align: center;             text-align: center;
-            font-weightbold+            border-bottom3px solid #2c3e50
-            border1px solid #ddd;+            padding-bottom15px; 
 +            margin-bottom: 25px;
         }         }
  
-        .composition-table td +        .medical-header h1 
-            padding3px 8px+            font-size24px
-            border1px solid #ddd+            color: #2c3e50
-            text-alignright;+            margin5px 0;
         }         }
  
-        .composition-table .component-name-col +        .medical-header h2 
-            text-alignleft !important+            font-size: 18px; 
-            width60%;+            color#34495e
 +            margin3px 0;
         }         }
  
-        .composition-total +        .medical-header p 
-            background-color: #f8f8f8+            font-size: 14px; 
-            font-weightbold;+            color: #7f8c8d
 +            margin2px 0;
         }         }
  
-        .elements-table +        .no-print {  
-            width100%; +            displayblock
-            border-collapse: collapse; +
-            font-size: 11px; +
-            margin-top: 0;+
         }         }
  
-        .elements-table td +        @media print { 
-            padding3px 8px+            .no-print  
-            border-bottom1px solid #ddd;+                display: none !important;  
 +            
 +            body {  
 +                backgroundwhite;  
 +            
 +            .container {  
 +                box-shadownone 
 +            } 
 +         
 +            
         }         }
  
-        .elements-table .element-name +         /* NUOVA INTESTAZIONE MEDICA ASST LECCO */ 
-            width: 200px+        .medical-header-table 
-        }+    width: 100%; 
 +    border-collapse: collapse; 
 +    border: 2px solid #2c3e50; 
 +    margin-bottom: 25px
 +        }       
  
-        .elements-table .element-value +.medical-header-table td 
-            text-alignright+    border1px solid #2c3e50
-            font-weightbold+    padding10px
-            width80px+    vertical-aligntop
-        }+}
  
-        .elements-table .element-unit +.medical-header-left 
-            text-align: left; +    width: 45%
-            width: 40px+    background-color#f8f9fa
-            font-size10px+}
-        }+
  
-        .report-footer +.medical-header-center 
-            margin-top30px+    width: 30%; 
-            padding-top10px+    text-align: center; 
-            border-top: 1px solid #ddd+    background-color: #f8f9fa; 
-            font-size: 10px; +
-            color: #666+ 
-            text-align: center; +.medical-header-right { 
-        }+    width: 25%; 
 +    text-align: center; 
 +    background-color: #f8f9fa; 
 +
 + 
 +.medical-header-left h2 { 
 +    font-size: 14px; 
 +    font-weight: bold; 
 +    color: #2c3e50; 
 +    margin: 0 0 5px 0; 
 +
 + 
 +.medical-header-left h3 { 
 +    font-size12px
 +    color: #34495e; 
 +    margin: 0 0 5px 0; 
 +
 + 
 +.medical-header-left p { 
 +    font-size11px; 
 +    color: #7f8c8d; 
 +    margin: 0; 
 +}           
 + 
 +/* NUOVA INTESTAZIONE MEDICA ASST LECCO */ 
 +.medical-header-table { 
 +    width: 100%
 +    border-collapse: collapse; 
 +    border: 2px solid #2c3e50; 
 +    margin-bottom: 25px; 
 +
 + 
 +.medical-header-table td { 
 +    border: 1px solid #2c3e50
 +    padding: 10px; 
 +    vertical-align: top; 
 +
 + 
 +.medical-header-left { 
 +    width: 45%; 
 +    background-color: #f8f9fa; 
 +
 + 
 +.medical-header-center { 
 +    width: 30%; 
 +    text-align: center; 
 +    background-color: #f8f9fa; 
 +
 + 
 +.medical-header-right { 
 +    width: 25%; 
 +    text-align: center; 
 +    background-color: #f8f9fa; 
 +
 + 
 +.medical-header-left h2 { 
 +    font-size: 14px; 
 +    font-weight: bold; 
 +    color: #2c3e50; 
 +    margin: 0 0 5px 0; 
 +
 + 
 +.medical-header-left h3 { 
 +    font-size: 12px; 
 +    color: #34495e; 
 +    margin: 0 0 5px 0; 
 +
 + 
 +.medical-header-left p { 
 +    font-size: 11px; 
 +    color: #7f8c8d; 
 +    margin: 0; 
 +
 + 
 +/* STILI KNOWLEDGE BASE */ 
 +.knowledge-section { 
 +    display: none; 
 +
 + 
 +.knowledge-section.active { 
 +    display: block; 
 +
 + 
 +.knowledge-tooltip { 
 +    position: absolute; 
 +    background-color: #2c3e50; 
 +    color: white; 
 +    padding: 10px; 
 +    border-radius: 5px; 
 +    font-size: 12px; 
 +    max-width: 300px; 
 +    z-index: 1000; 
 +    box-shadow: 0 2px 10px rgba(0,0,0,0.3); 
 +    animation: fadeIn 0.3s ease-in-out; 
 +
 + 
 +@keyframes fadeIn { 
 +    from { opacity: 0; transform: translateY(-10px);
 +    to { opacity: 1; transform: translateY(0);
 +
 + 
 +.knowledge-section h3 { 
 +    color: #2c3e50
 +    border-bottom: 2px solid #3498db; 
 +    padding-bottom: 8px; 
 +    margin-bottom: 15px; 
 +
 + 
 +.knowledge-section h4 { 
 +    color: #34495e; 
 +    margin-top: 20px; 
 +    margin-bottom: 10px; 
 +
 + 
 +/* STILI SPECIFICI PER ETICHETTA SACCA */ 
 +.label-section { 
 +    border: 3px solid #2c3e50; 
 +    background-color: #f8f9fa; 
 +    padding: 15px; 
 +    margin: 15px 0; 
 +    border-radius: 8px; 
 +
 + 
 +.label-patient-id { 
 +    border: 4px solid #d32f2f; 
 +    background-color: #ffebee; 
 +    padding: 15px; 
 +    margin: 15px 0; 
 +    text-align: center; 
 +    border-radius: 8px; 
 +
 + 
 +.label-content { 
 +    border: 3px solid #388e3c; 
 +    background-color: #e8f5e8; 
 +    padding: 15px; 
 +    margin: 15px 0; 
 +    border-radius: 8px; 
 +
 + 
 +.label-header { 
 +    text-align: center; 
 +    border-bottom: 3px solid #000; 
 +    padding-bottom: 10px; 
 +    margin-bottom: 15px; 
 +
 + 
 +.label-volume-total { 
 +    background-color: #4caf50; 
 +    color: white; 
 +    font-weight: bold; 
 +    font-size: 16px; 
 +}
  
-        @media print { 
-            .npt-report { 
-                box-shadow: none; 
-                border: none; 
-                margin: 0; 
-                padding: 15px; 
-            } 
-             
-            .button { 
-                display: none; 
-            } 
-             
-            .tabs, .tab-content:not(.active) { 
-                display: none !important; 
-            } 
-        } 
     </style>     </style>
-    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script> 
-    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script> 
 </head> </head>
 <body> <body>
  
 <div class="container"> <div class="container">
-    <h1>Programma NPT Neonatale v2.0</h1>+    <h1>Gestione della Nutrizione del Neonato (GNN v3.0)</h1
 +   <div class="version-info"> 
 +    <strong>Sistema:</strong> GNN (Gestione Nutrizione Neonato) v3.0 | <strong>Data creazione:</strong> 02 Agosto 2025 | <strong>Ora:</strong> 20:00 | <strong>Modulo:</strong> Calcolo NPT Integrato 
 +</div>
          
-    <!-- TAB ORIZZONTALI -->+    <!-- TAB ORIZZONTALI CORRETTI -->
     <div class="tabs">     <div class="tabs">
-        <div class="tab active" onclick="showTab('patient-data')"> +    <div class="tab active" onclick="showTab('patient-data')"> 
-            <span style="font-size: 18px;">1</span><br>Dati Paziente +        <span style="font-size: 20px; font-weight: bold;">1</span><br>Dati Paziente 
-        </div> +    </div> 
-        <div class="tab" onclick="showTab('enteral')"> +     
-            <span style="font-size: 18px;">2</span><br>Nutrizione Enterale +    <!-- SEZIONE CONFIGURAZIONE COMPONENTI (DA VERSIONE 17) --> 
-        </div> +    <div class="tab" onclick="showTab('enteral')"> 
-        <div class="tab" onclick="showTab('nutrition-calc')"> +        <span style="font-size: 20px; font-weight: bold;">2</span><br>Nutrizione Enterale 
-            <span style="font-size: 18px;">3</span><br>Calcolo Fabbisogni +    </div> 
-        </div> +    <div class="tab" onclick="showTab('nutrition-calc')"> 
-        <div class="tab" onclick="showTab('parenteral')"> +        <span style="font-size: 20px; font-weight: bold;">3</span><br>Calcolo Fabbisogni 
-            <span style="font-size: 18px;">4</span><br>Nutrizione Parenterale +    </div> 
-        </div> +    <div class="tab" onclick="showTab('parenteral')"> 
-        <div class="tab" onclick="showTab('config')"> +        <span style="font-size: 20px; font-weight: bold;">4</span><br>Nutrizione Parenterale 
-            <span style="font-size: 18px;">5</span><br>Configurazione +    </div> 
-        </div>+    <div class="tab" onclick="showTab('report')"> 
 +        <span style="font-size: 20px; font-weight: bold;">5</span><br>Report Finale 
 +    </div> 
 +    <div class="tab" onclick="showTab('knowledge-base')"> 
 +        <span style="font-size: 20px; font-weight: bold;">📚</span><br>Knowledge Base 
 +    </div> 
 +    <div class="tab" onclick="showTab('config')" style="max-width: 60px; min-width: 60px;"> 
 +        <span style="font-size: 24px;">⚙️</span> 
 +    </div>
     </div>     </div>
  
-    <!-- TAB 1: DATI PAZIENTE -->+    <!-- TAB 1: DATI PAZIENTE (VERSIONE 17 ORIGINALE) -->
     <div id="patient-data" class="tab-content active">     <div id="patient-data" class="tab-content active">
-        <div class="info"> +       <div class="info"> 
-            <strong>PASSO 1 - DATI PAZIENTE</strong><br> +    <strong>PASSO 1 - DATI PAZIENTE</strong><br> 
-            <strong>Obiettivo:</strong> Inserire i dati antropometrici ed ematochimici del neonato +    <strong>Sistema GNN:</strong> Gestione integrata della nutrizione neonatale con calcolo automatico dei fabbisogni<br> 
-        </div>+    <strong>Obiettivo:</strong> Inserire i dati antropometrici ed ematochimici del neonato per determinare la strategia nutrizionale ottimale 
 +</div>
         <div class="section">         <div class="section">
             <h2>Dati Prescrizione</h2>             <h2>Dati Prescrizione</h2>
Linea 524: Linea 825:
                         <label for="prescribingDoctor">Medico prescrittore:</label>                         <label for="prescribingDoctor">Medico prescrittore:</label>
                         <select id="prescribingDoctor" style="width: 200px;">                         <select id="prescribingDoctor" style="width: 200px;">
-                            <option value="">Seleziona medico</option> +                            <!-- Popolato dinamicamente -->
-                            <option value="dr_bellu">Dr. Roberto Bellù</option> +
-                            <option value="dr_condo">Dr.ssa Manuela Condò</option> +
-                            <option value="dr_maccioni">Dr.ssa Carla Maccioni</option> +
-                            <option value="dr_meroni">Dr.ssa Federica Meroni</option> +
-                            <option value="dr_calzatini">Dr. Francesco Calzatini</option> +
-                            <option value="dr_ferrari">Dr.ssa Elisabetta Ferrari</option>+
                         </select>                         </select>
                     </div>                     </div>
Linea 559: Linea 854:
                     <div class="input-group">                     <div class="input-group">
                         <label for="currentWeight">Peso attuale (g):</label>                         <label for="currentWeight">Peso attuale (g):</label>
-                        <input type="number" id="currentWeight" min="400" max="5000" value="3550">+                        <input type="number" id="currentWeight" min="400" max="5000" value="1000">
                     </div>                     </div>
                     <div class="input-group">                     <div class="input-group">
Linea 565: Linea 860:
                         <input type="number" id="daysOfLife" min="1" max="365" value="9">                         <input type="number" id="daysOfLife" min="1" max="365" value="9">
                     </div>                     </div>
 +
 +                    <div class="input-group">
 +                <label for="gestationalAge">Età gestazionale:</label>
 +                <div style="display: flex; align-items: center; gap: 5px;">
 +                    <input type="number" id="gestationalWeeks" min="22" max="45" placeholder="36" style="width: 60px;">
 +                    <span>sett.</span>
 +                    <input type="number" id="gestationalDays" min="0" max="6" placeholder="3" style="width: 50px;">
 +                    <span>gg.</span>
 +                    <span style="margin-left: 10px; font-size: 12px; color: #666;">(es: 36+3)</span>
 +                </div>
 +            </div>
 +
 +            <div class="input-group">
 +            <label for="postConceptionalAge">Età post-concezionale:</label>
 +            <div style="display: flex; align-items: center; gap: 5px;">
 +                <input type="text" id="postConceptionalAge" readonly style="width: 120px; background-color: #f0f0f0; font-weight: bold;" placeholder="Calcolata automaticamente">
 +                <span style="font-size: 12px; color: #666;">(età gest. + giorni di vita)</span>
 +            </div>
 +</div>
 +
 +
 +
 +
 +
                 </div>                 </div>
                 <div class="form-col">                 <div class="form-col">
Linea 612: Linea 931:
     </div>     </div>
  
-    <!-- TAB 2: NUTRIZIONE ENTERALE -->+    <!-- TAB 2: NUTRIZIONE ENTERALE (VERSIONE 17 ORIGINALE) -->
     <div id="enteral" class="tab-content">     <div id="enteral" class="tab-content">
         <div class="info">         <div class="info">
Linea 711: Linea 1030:
     </div>     </div>
  
-    <!-- TAB 3: CALCOLO FABBISOGNI -->+    <!-- TAB 3: CALCOLO FABBISOGNI (VERSIONE 17 ORIGINALE COMPLETA) -->
     <div id="nutrition-calc" class="tab-content">     <div id="nutrition-calc" class="tab-content">
         <div class="info">         <div class="info">
Linea 841: Linea 1160:
     </div>     </div>
  
-    <!-- TAB 4: NUTRIZIONE PARENTERALE -->+    <!-- TAB 4: NUTRIZIONE PARENTERALE (VERSIONE 17 ORIGINALE) -->
     <div id="parenteral" class="tab-content">     <div id="parenteral" class="tab-content">
         <div class="info">         <div class="info">
Linea 883: Linea 1202:
             <div id="preparationTable"></div>             <div id="preparationTable"></div>
                          
-            <div style="margin-top: 30px; padding: 15px; background-color: #f0f8ff; border-left: 4px solid #3498db; border-radius: 5px;"> + 
-                <h3 style="color: #2c3e50; margin-top0;">📋 Report Professionali</h3+            <div style="margin-top: 20px;"> 
-                <style="margin-bottom15px;">Genera report in formato ospedaliero per stampa archiviazione:</p+                <button class="button" onclick="generatePDF('foglio_lavoro')">📄 Genera PDF - FOGLIO DI LAVORO</button> 
-                <div style="display: flex; gap: 10px; flex-wrap: wrap;"> +                <button class="button" onclick="generatePDF('report_parenterale')" style="margin-left10px;">📄 Genera PDF - REPORT PARENTERALE</button
-                    <button id="generateWorkReportBtn" class="button" onclick="generateAndShowWorkReport()" style="background-color: #27ae60;">Genera Foglio di Lavoro</button> +                <button class="button" onclick="generatePDF('etichetta_sacca')" style="margin-left10px;">🏷️ Genera PDF - ETICHETTA SACCA</button> 
-                    <button id="generateFinalReportBtn" class="button" onclick="generateAndShowFinalReport()" style="background-color#3498db;">Genera Report Parenterale</button+            </div> 
-                    <button id="printReportBtn" class="button secondary hiddenonclick="printCurrentReport()" style="margin-left10px;">Stampa Report Attivo</button+        </div> 
-                    <button id="savePdfBtn" class="button hidden" onclick="saveReportAsPDF()" style="background-color#e74c3c; margin-left10px;">💾 Salva PDF</button+    </div> 
-                </div>+ 
 + 
 +    <!-- TAB 5: REPORT FINALE (SPOSTATO DA TAB 6) --> 
 +    <div id="report" class="tab-content"> 
 +        <div class="info"> 
 +            <strong>PASSO 5 - REPORT FINALE</strong><br> 
 +            <strong>Obiettivo:</strong> Generare la documentazione completa per prescrizione preparazione 
 +        </div
 + 
 +    <!-- Banner stato prescrizione --> 
 +    <div id="prescriptionStatusBanner" style="display: none;"> 
 +    <!-- Popolato dinamicamente --> 
 +    </div>     
 +    <div class="section no-print"
 +        <h2>Genera Documentazione</h2> 
 +        <button class="button" onclick="generatePrescription()">Genera Prescrizione Medica</button> 
 +        <button class="button" onclick="generateWorksheet()">Genera Ricetta Preparazione</button> 
 +        <button class="buttononclick="generateLabel()">Genera Etichetta Sacca</button> 
 +        <button class="button secondary" onclick="window.print()">Stampa Pagina</button> 
 +                <!-- Report appare subito qui sotto i pulsanti --> 
 +                <div id="reportOutput"></div> 
 +            </div> 
 + 
 +        <!-- SEZIONE 2A: VALIDAZIONE FARMACISTA --> 
 +<div class="section"> 
 +    <h2>💊 Fase 1 - Validazione Farmacista</h2> 
 +    <div class="info" style="margin-bottom15px;"> 
 +        <strong>📋 VALIDAZIONE PRESCRIZIONE NPT</strong><br
 +        Il farmacista deve validare la prescrizione medica prima dell'allestimento. 
 +    </div> 
 +     
 +    <div class="form-row"
 +        <div class="form-col"
 +            <div class="input-group"> 
 +                <label for="validatingPharmacist">Farmacista Validatore:</label> 
 +                <select id="validatingPharmacist" style="width: 300px;"> 
 +                    <option value="">Seleziona farmacista responsabile</option> 
 +                    <!-- Popolato dinamicamente da pharmacistsData --> 
 +                </select> 
 +            </div> 
 +            <div class="info" style="margin-top5px; font-size: 12px;"> 
 +                <strong>Responsabile della validazione clinica e farmacologica della prescrizione NPT</strong
 +            </div> 
 +        </div> 
 +         
 +        <div class="form-col"
 +            <button class="button" onclick="validatePrescription()" id="validatePrescriptionBtn"> 
 +                📝 VALIDA PRESCRIZIONE 
 +            </button> 
 +            <div id="validationStatus" style="margin-top15pxdisplay: none;"> 
 +                <!-- Status validazione --> 
 +            </div> 
 +        </div> 
 +    </div> 
 +</div> 
 + 
 +<!-- SEZIONE 2B: ALLESTIMENTO TECNICI --> 
 +<div class="section"> 
 +    <h2>🔬 Fase 2 - Allestimento Galenico</h2> 
 +    <div class="info" style="margin-bottom15px;"> 
 +        <strong>⚗️ PREPARAZIONE FISICA NPT</strong><br
 +        Due tecnici qualificati preparano la sacca NPT secondo protocolli GMP con controllo incrociato. 
 +    </div
 +     
 +    <div class="form-row"> 
 +        <div class="form-col"> 
 +            <div class="input-group"> 
 +                <label for="preparingTechnician1">Primo Tecnico Preparatore:</label> 
 +                <select id="preparingTechnician1" style="width: 300px;" disabled> 
 +                    <option value="">Prima completare validazione farmacista</option> 
 +                    <!-- Popolato dinamicamente da technicianData --> 
 +                </select>
             </div>             </div>
                          
-            <div id="nptWorkReport" class="hidden" style="margin-top: 20px;"></div+            <div class="input-group"> 
-            <div id="nptFinalReport" class="hidden" style="margin-top: 20px;"></div>+                <label for="preparingTechnician2">Secondo Tecnico Preparatore:</label> 
 +                <select id="preparingTechnician2style="width: 300px;" disabled> 
 +                    <option value="">Prima completare validazione farmacist</option> 
 +                    <!-- Popolato dinamicamente da technicianData --> 
 +                </select> 
 +            </div> 
 +            <div class="info" style="margin-top: 5px; font-size: 12px;"> 
 +                <strong>Due tecnici diversi per controllo incrociato secondo protocolli GMP</strong
 +            </div
 +        </div> 
 +         
 +        <div class="form-col"> 
 +            <button class="button" onclick="confirmPreparation()" id="confirmPreparationBtndisabled> 
 +                🧪 CONFERMA ALLESTIMENTO 
 +            </button> 
 +           <button class="button secondaryonclick="downloadPreparationJSON()" id="downloadBtn" disabled style="margin-top: 10px;"> 
 +                💾 ARCHIVIA PREPARAZIONE (JSON) 
 +            </button> 
 +            <button class="button" onclick="lockPrescription()" id="lockPrescriptionBtn" disabled style="margin-top: 10px; background-color: #e74c3c;"> 
 +                🔒 BLOCCA PRESCRIZIONE 
 +            </button> 
 +            <div id="preparationStatus" style="margin-top: 15px; display: none;"> 
 +                <!-- Status preparazione --> 
 +            </div>
         </div>         </div>
 +    </div>
 +</div>
 +
 +        <!-- SEZIONE ARCHIVIAZIONE MENSILE -->
 +
 +     <div class="section">
 +    <h2>📊 Archiviazione Mensile Excel</h2>
 +    <div class="info" style="margin-bottom: 15px;">
 +        <strong>📈 CONSOLIDAMENTO PREPARAZIONI NPT</strong><br>
 +        Genera report Excel mensile con tutte le preparazioni NPT archiviate come JSON.
 +    </div>
 +    
 +    <div class="form-row">
 +        <div class="form-col">
 +            <div class="input-group">
 +                <label for="selectedMonth">Mese da consolidare:</label>
 +                <input type="month" id="selectedMonth" style="width: 150px;">
 +            </div>
 +            <div class="input-group">
 +                <label for="jsonFilesInput">File JSON da includere:</label>
 +                <input type="file" id="jsonFilesInput" multiple accept=".json" style="width: 300px;">
 +            </div>
 +            <div class="info" style="margin-top: 5px; font-size: 12px;">
 +                <strong>Seleziona tutti i file NPT_*.json del mese da consolidare</strong>
 +            </div>
 +        </div>
 +        
 +        <div class="form-col">
 +            <button class="button" onclick="generateMonthlyExcel()" id="generateExcelBtn">
 +                📊 GENERA EXCEL MENSILE
 +            </button>
 +            <button class="button secondary" onclick="previewMonthlyData()" id="previewBtn" style="margin-top: 10px;">
 +                👁️ ANTEPRIMA DATI
 +            </button>
 +            
 +            <div id="monthlyStats" style="margin-top: 15px; display: none;">
 +                <!-- Statistiche mensili popolate dinamicamente -->
 +            </div>
 +        </div>
 +    </div>
 +</div>
 +   
 +        
 +    </div>
 +
 +
 +<!-- TAB 6: KNOWLEDGE BASE -->
 +    <div id="knowledge-base" class="tab-content">
 +        <div class="info">
 +            <strong>🧠 KNOWLEDGE BASE NPT v3.0</strong><br>
 +            <strong>Sistema:</strong> Base di conoscenza integrata per decision support clinico<br>
 +            <strong>Obiettivo:</strong> Spiegare regole di calcolo, linee guida e supportare le decisioni cliniche
 +        </div>
 +
 +        <!-- NAVIGAZIONE INTERNA KNOWLEDGE BASE -->
 +        <div class="tabs" style="margin-bottom: 15px;">
 +            <div class="tab active" onclick="showKnowledgeSection('calculation-rules')" style="font-size: 12px; padding: 6px 12px;">
 +                🧮 Regole Calcolo
 +            </div>
 +            <div class="tab" onclick="showKnowledgeSection('clinical-guidelines')" style="font-size: 12px; padding: 6px 12px;">
 +                👩‍⚕️ Linee Guida
 +            </div>
 +            <div class="tab" onclick="showKnowledgeSection('alert-system')" style="font-size: 12px; padding: 6px 12px;">
 +                🚨 Sistema Alert
 +            </div>
 +            <div class="tab" onclick="showKnowledgeSection('evidence-base')" style="font-size: 12px; padding: 6px 12px;">
 +                📖 Evidenze
 +            </div>
 +            <div class="tab" onclick="showKnowledgeSection('decision-support')" style="font-size: 12px; padding: 6px 12px;">
 +                🎯 Decision Support
 +            </div>
 +        </div>
 +
 +        <!-- SEZIONE 1: REGOLE DI CALCOLO -->
 +        <div id="calculation-rules" class="knowledge-section active">
 +            <div class="section">
 +                <h2>🧮 REGOLE DI CALCOLO NPT</h2>
 +                
 +                <div class="config-advanced">
 +                    <h3>Algoritmi Automatici</h3>
 +                    
 +                    <div class="form-row">
 +                        <div class="form-col">
 +                            <h4>📊 Calcolo GIR (Glucose Infusion Rate)</h4>
 +                            <div class="info" style="font-size: 13px;">
 +                                <strong>Formula:</strong> GIR = (Glucidi g/kg/die × 1000) ÷ 1440 minuti<br>
 +                                <strong>Range sicurezza:</strong> < 12 mg/kg/min (configurabile)<br>
 +                                <strong>Fonte glucosio:</strong> Glucosio 50% + Acqua bidistillata<br>
 +                                <strong>Alert automatico:</strong> GIR > 12 mg/kg/min
 +                            </div>
 +                            
 +                            <h4>🧪 Calcolo Osmolarità</h4>
 +                            <div class="info" style="font-size: 13px;">
 +                                <strong>Formula:</strong> Σ(Volume componente × Osmolarità componente) ÷ Volume totale<br>
 +                                <strong>Soglie:</strong><br>
 +                                • < 600 mOsm/L: Accesso periferico possibile<br>
 +                                • 600-900 mOsm/L: CVC raccomandato<br>
 +                                • > 900 mOsm/L: Solo CVC (soluzione ipertonica)
 +                            </div>
 +                        </div>
 +                        
 +                        <div class="form-col">
 +                            <h4>⚖️ Gestione Automatica BUN</h4>
 +                            <div class="info" style="font-size: 13px;">
 +                                <strong>Range normale:</strong> 9-14 mg/dL<br>
 +                                <strong>BUN < 9:</strong> Aumenta proteine +1 g/kg/die<br>
 +                                <strong>BUN > 14:</strong> Riduce proteine -1 g/kg/die<br>
 +                                <strong>Applicazione:</strong> Automatica nel caricamento defaults
 +                            </div>
 +                            
 +                            <h4>🧂 Selezione Sodio Intelligente</h4>
 +                            <div class="info" style="font-size: 13px;">
 +                                <strong>NaCl standard:</strong> pH > 7.30 e BE > -4<br>
 +                                <strong>Sodio Acetato:</strong> pH < 7.30 o BE < -4<br>
 +                                <strong>Effetto:</strong> Sodio Acetato ha azione alcalinizzante<br>
 +                                <strong>Suggerimento:</strong> Automatico basato su parametri clinici
 +                            </div>
 +                        </div>
 +                    </div>
 +                </div>
 +                
 +                <div class="section">
 +                    <h3>📐 Formule Matematiche Principali</h3>
 +                    <div style="overflow-x: auto;">
 +                        <table class="config-table">
 +                            <thead>
 +                                <tr>
 +                                    <th style="min-width: 200px;">Parametro</th>
 +                                    <th>Formula</th>
 +                                    <th>Unità</th>
 +                                    <th>Range Normale</th>
 +                                    <th>Note</th>
 +                                </tr>
 +                            </thead>
 +                            <tbody>
 +                                <tr>
 +                                    <td><strong>GIR</strong></td>
 +                                    <td>(Glucidi g/kg/die × 1000) ÷ 1440</td>
 +                                    <td>mg/kg/min</td>
 +                                    <td>4-12</td>
 +                                    <td>Alert se > 12</td>
 +                                </tr>
 +                                <tr>
 +                                    <td><strong>Energia Totale</strong></td>
 +                                    <td>(Proteine×4) + (Glucidi×4) + (Lipidi×9)</td>
 +                                    <td>kcal/kg/die</td>
 +                                    <td>80-120</td>
 +                                    <td>Dipende da età</td>
 +                                </tr>
 +                                <tr>
 +                                    <td><strong>Osmolarità</strong></td>
 +                                    <td>Σ(Vol.comp × Osm.comp) ÷ Vol.tot</td>
 +                                    <td>mOsm/L</td>
 +                                    <td>&lt; 900</td>
 +                                    <td>CVC se > 600</td>
 +                                </tr>
 +                                <tr>
 +                                    <td><strong>Rapporto Ca:P</strong></td>
 +                                    <td>mg Ca elementare : mg P</td>
 +                                    <td>ratio</td>
 +                                    <td>1.3:1 - 2:1</td>
 +                                    <td>Evita precipitazioni</td>
 +                                </tr>
 +                                <tr>
 +                                    <td><strong>Velocità Infusione</strong></td>
 +                                    <td>Volume totale NPT ÷ 24</td>
 +                                    <td>ml/h</td>
 +                                    <td>Variabile</td>
 +                                    <td>Infusione continua</td>
 +                                </tr>
 +                            </tbody>
 +                        </table>
 +                    </div>
 +                </div>
 +            </div>
 +        </div>
 +
 +        <!-- SEZIONE 2: LINEE GUIDA CLINICHE (placeholder per ora) -->
 +        <div id="clinical-guidelines" class="knowledge-section hidden">
 +            <div class="section">
 +                <h2>👩‍⚕️ LINEE GUIDA CLINICHE</h2>
 +                <div class="info">
 +                    <strong>🚧 In sviluppo...</strong><br>
 +                    Questa sezione conterrà protocolli per età, patologie e tempistiche.
 +                </div>
 +            </div>
 +        </div>
 +
 +        <!-- SEZIONE 3: SISTEMA ALERT (placeholder per ora) -->
 +        <div id="alert-system" class="knowledge-section hidden">
 +            <div class="section">
 +                <h2>🚨 SISTEMA ALERT</h2>
 +                <div class="info">
 +                    <strong>🚧 In sviluppo...</strong><br>
 +                    Questa sezione spiegherà soglie di allarme e azioni consigliate.
 +                </div>
 +            </div>
 +        </div>
 +
 +        <!-- SEZIONE 4: EVIDENZE (placeholder per ora) -->
 +        <div id="evidence-base" class="knowledge-section hidden">
 +            <div class="section">
 +                <h2>📖 EVIDENZE SCIENTIFICHE</h2>
 +                <div class="info">
 +                    <strong>🚧 In sviluppo...</strong><br>
 +                    Questa sezione conterrà bibliografia e riferimenti scientifici.
 +                </div>
 +            </div>
 +        </div>
 +
 +        <!-- SEZIONE 5: DECISION SUPPORT (placeholder per ora) -->
 +        <div id="decision-support" class="knowledge-section hidden">
 +            <div class="section">
 +                <h2>🎯 DECISION SUPPORT</h2>
 +                <div class="info">
 +                    <strong>🚧 In sviluppo...</strong><br>
 +                    Questa sezione conterrà configurazione regole e simulatore.
 +                </div>
 +            </div>
 +        </div>
 +
     </div>     </div>
  
-    <!-- TAB 5: CONFIGURAZIONE -->+    <!-- TAB 6: CONFIGURAZIONE (SPOSTATO DA TAB 5) -->
     <div id="config" class="tab-content">     <div id="config" class="tab-content">
         <div class="info">         <div class="info">
-            <strong>CONFIGURAZIONE COMPONENTI</strong><br> +            <strong>CONFIGURAZIONE COMPLETA</strong><br> 
-            <strong>Sistema:</strong> NPT Calculator v2.0 - Database completo componenti nutrizionali+            <strong>Sistema:</strong> NPT Calculator v3.0 - Database completo componenti + configurazione clinica avanzata
         </div>         </div>
-         
         <div class="section">         <div class="section">
             <h2>Parametri Sistema</h2>             <h2>Parametri Sistema</h2>
Linea 912: Linea 1545:
                     <div class="input-group">                     <div class="input-group">
                         <label for="deflectorVolume">Volume deflussore (ml):</label>                         <label for="deflectorVolume">Volume deflussore (ml):</label>
-                        <input type="number" id="deflectorVolume" min="0" max="100" step="5" value="30">+                        <input type="number" id="deflectorVolume" min="0" max="100" step="5" value="30" oninput="markConfigChanged('system')">
                     </div>                     </div>
                     <div class="info" style="margin-top: 10px; font-size: 12px;">                     <div class="info" style="margin-top: 10px; font-size: 12px;">
Linea 926: Linea 1559:
             </div>             </div>
         </div>         </div>
 +        
         <div class="section">         <div class="section">
             <h2>Formule Enterali (Valori per 100ml)</h2>             <h2>Formule Enterali (Valori per 100ml)</h2>
             <div style="overflow-x: auto;">             <div style="overflow-x: auto;">
-                <table class="results-table" style="font-size: 12px;">+                <table class="config-table">
                     <thead>                     <thead>
                         <tr>                         <tr>
Linea 943: Linea 1576:
                             <th>Magnesio<br>(mg)</th>                             <th>Magnesio<br>(mg)</th>
                             <th>Energia<br>(kcal)</th>                             <th>Energia<br>(kcal)</th>
 +                            <th>Azioni</th>
                         </tr>                         </tr>
                     </thead>                     </thead>
-                    <tbody> +                    <tbody id="enteralConfigTable"
-                        <tr> +                        <!-- Popolato dinamicamente -->
-                            <td><strong>Latte Materno</strong></td> +
-                            <td>1.2</td> +
-                            <td>7.0</td> +
-                            <td>4.0</td> +
-                            <td>0.007</td> +
-                            <td>0.035</td> +
-                            <td>28.0</td> +
-                            <td>15.0</td> +
-                            <td>3.0</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Latte Materno + Prenidina FM85</strong></td> +
-                            <td>2.6</td> +
-                            <td>7.4</td> +
-                            <td>4.25</td> +
-                            <td>0.009</td> +
-                            <td>0.050</td> +
-                            <td>63.0</td> +
-                            <td>35.0</td> +
-                            <td>4.5</td> +
-                            <td>87</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Nestle NAN Supreme Pro 1</strong></td> +
-                            <td>1.3</td> +
-                            <td>7.6</td> +
-                            <td>3.5</td> +
-                            <td>0.024</td> +
-                            <td>0.075</td> +
-                            <td>44.1</td> +
-                            <td>24.4</td> +
-                            <td>6.56</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Humana 1</strong></td> +
-                            <td>1.4</td> +
-                            <td>7.6</td> +
-                            <td>3.2</td> +
-                            <td>0.020</td> +
-                            <td>0.070</td> +
-                            <td>59.0</td> +
-                            <td>33.0</td> +
-                            <td>5.0</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>BBmilk Zero</strong></td> +
-                            <td>1.8</td> +
-                            <td>7.8</td> +
-                            <td>3.6</td> +
-                            <td>0.022</td> +
-                            <td>0.075</td> +
-                            <td>65.0</td> +
-                            <td>36.0</td> +
-                            <td>6.0</td> +
-                            <td>70</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>BBmilk PDF</strong></td> +
-                            <td>1.7</td> +
-                            <td>7.9</td> +
-                            <td>3.7</td> +
-                            <td>0.025</td> +
-                            <td>0.078</td> +
-                            <td>68.0</td> +
-                            <td>38.0</td> +
-                            <td>6.5</td> +
-                            <td>71</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Nestle PreNan POST</strong></td> +
-                            <td>2.0</td> +
-                            <td>8.2</td> +
-                            <td>4.0</td> +
-                            <td>0.030</td> +
-                            <td>0.085</td> +
-                            <td>75.0</td> +
-                            <td>42.0</td> +
-                            <td>7.5</td> +
-                            <td>73</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Alfare</strong></td> +
-                            <td>1.9</td> +
-                            <td>7.1</td> +
-                            <td>3.4</td> +
-                            <td>0.015</td> +
-                            <td>0.050</td> +
-                            <td>52.0</td> +
-                            <td>35.0</td> +
-                            <td>5.5</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Infatrini</strong></td> +
-                            <td>2.6</td> +
-                            <td>10.8</td> +
-                            <td>5.4</td> +
-                            <td>0.028</td> +
-                            <td>0.082</td> +
-                            <td>85.0</td> +
-                            <td>58.0</td> +
-                            <td>9.2</td> +
-                            <td>101</td> +
-                        </tr>+
                     </tbody>                     </tbody>
                 </table>                 </table>
             </div>             </div>
-            <div class="infostyle="margin-top: 15px;"> +            <div class="form-row"
-                <strong>ℹ️ Informazioni:</strongQuesti valori sono configurati nel database e vengono utilizzati per i calcoli nutrizionali. Sono basati su letteratura e schede tecniche ufficiali.+                <div class="form-col"
 +                    <button id="updateEnteralBtn" class="button" onclick="updateEnteralConfig()">Aggiorna Formule Enterali</button
 +                </div> 
 +                <div class="form-col"> 
 +                    <button class="button secondary" onclick="showAddEnteralForm()">Aggiungi Nuova Formula</button> 
 +                </div>
             </div>             </div>
         </div>         </div>
  
         <div class="section">         <div class="section">
-            <h2>Componenti Parenterali (Valori per 100ml)</h2>+            <h2>Fortificanti in Polvere (Valori per 100g)</h2>
             <div style="overflow-x: auto;">             <div style="overflow-x: auto;">
-                <table class="results-table" style="font-size: 12px;">+                <table class="config-table">
                     <thead>                     <thead>
                         <tr>                         <tr>
-                            <th style="min-width: 200px;">Componente</th> +                            <th style="min-width: 180px;">Fortificante</th> 
-                            <th>Calcio<br>(mg)</th> +                            <th>Proteine<br>(g)</th> 
-                            <th>Fosforo<br>(mg)</th> +                            <th>Carboidrati<br>(g)</th> 
-                            <th>Magnesio<br>(mEq)</th>+                            <th>Lipidi<br>(g)</th>
                             <th>Sodio<br>(mEq)</th>                             <th>Sodio<br>(mEq)</th>
                             <th>Potassio<br>(mEq)</th>                             <th>Potassio<br>(mEq)</th>
-                            <th style="min-width: 250px;">Descrizione</th>+                            <th>Calcio<br>(mg)</th> 
 +                            <th>Fosforo<br>(mg)</th> 
 +                            <th>Magnesio<br>(mg)</th> 
 +                            <th>Energia<br>(kcal)</th> 
 +                            <th style="min-width: 200px;">Note</th> 
 +                            <th>Azioni</th>
                         </tr>                         </tr>
                     </thead>                     </thead>
-                    <tbody>+                    <tbody id="fortifierConfigTable">
                         <tr>                         <tr>
-                            <td><strong>Calcio Gluconato 10%</strong></td> +                            <td class="component-name">Prenidina FM85</td> 
-                            <td>840</td> +                            <td><input type="number" id="fortifier_prenidina_fm85_protein" value="14" step="0.1" oninput="markConfigChanged('fortifier')"></td> 
-                            <td>0</td> +                            <td><input type="number" id="fortifier_prenidina_fm85_carbs" value="4" step="0.1" oninput="markConfigChanged('fortifier')"></td> 
-                            <td>0</td> +                            <td><input type="number" id="fortifier_prenidina_fm85_lipids" value="2.5" step="0.1" oninput="markConfigChanged('fortifier')"></td> 
-                            <td>0</td> +                            <td><input type="number" id="fortifier_prenidina_fm85_sodium" value="2" step="0.1" oninput="markConfigChanged('fortifier')"></td> 
-                            <td>0</td> +                            <td><input type="number" id="fortifier_prenidina_fm85_potassium" value="15" step="0.1" oninput="markConfigChanged('fortifier')"></td> 
-                            <td>1g/10mL, 0.44 mEq/mL Sale di calcio organico</td>+                            <td><input type="number" id="fortifier_prenidina_fm85_calcium" value="3500" step="1" oninput="markConfigChanged('fortifier')"></td> 
 +                            <td><input type="number" id="fortifier_prenidina_fm85_phosphorus" value="2000" step="1" oninput="markConfigChanged('fortifier')"></td> 
 +                            <td><input type="number" id="fortifier_prenidina_fm85_magnesium" value="150" step="1" oninput="markConfigChanged('fortifier')"></td> 
 +                            <td><input type="number" id="fortifier_prenidina_fm85_energy" value="400" step="1" oninput="markConfigChanged('fortifier')"></td> 
 +                            <td style="font-size: 11px; color: #7f8c8d;">Fortificante latte materno<br><em>Dose: 1-4g/100ml</em></td> 
 +                            <td><button class="button secondary" onclick="removeFortifier('prenidina_fm85')" style="padding: 5px 10px; font-size: 12px;">Rimuovi</button></td>
                         </tr>                         </tr>
 +                    </tbody>
 +                </table>
 +            </div>
 +            <div class="form-row">
 +                <div class="form-col">
 +                    <button id="updateFortifierBtn" class="button" onclick="updateFortifierConfig()">Aggiorna Fortificanti</button>
 +                </div>
 +                <div class="form-col">
 +                    <button class="button secondary" onclick="showAddFortifierForm()">Aggiungi Nuovo Fortificante</button>
 +                </div>
 +            </div>
 +        </div>
 +
 +        <div class="section">
 +            <h2>Componenti Parenterali (Valori per 100ml)</h2>
 +            <div style="overflow-x: auto;">
 +                <table class="config-table">
 +                    <thead>
 +    <tr>
 +        <th style="min-width: 180px;">Componente</th>
 +        <th>Proteine<br>(g)</th>
 +        <th>Carboidrati<br>(g)</th>
 +        <th>Lipidi<br>(g)</th>
 +        <th>Sodio<br>(mEq)</th>
 +        <th>Potassio<br>(mEq)</th>
 +        <th>Calcio<br>(mg)</th>
 +        <th>Fosforo<br>(mg)</th>
 +        <th>Magnesio<br>(mEq)</th>
 +        <th>Energia<br>(kcal)</th>
 +        <th>Acqua<br>(ml)</th>
 +        <th>Osmolarità<br>(mOsm/L)</th>
 +        <th style="min-width: 200px;">Descrizione e Note</th>
 +        <th>Azioni</th>
 +    </tr>
 +</thead>
 +                    <tbody id="parenteralConfigTable">
 +                        <!-- Popolato dinamicamente -->
 +                    </tbody>
 +                </table>
 +            </div>
 +            <div class="form-row">
 +                <div class="form-col">
 +                    <button id="updateParenteralBtn" class="button" onclick="updateParenteralConfig()">Aggiorna Componenti Parenterali</button>
 +                </div>
 +                <div class="form-col">
 +                    <button class="button secondary" onclick="showAddParenteralForm()">Aggiungi Nuovo Componente</button>
 +                </div>
 +            </div>
 +        </div>
 +
 +        <div class="section">
 +            <h2>Lista Medici Prescrittori</h2>
 +            <div class="info" style="margin-bottom: 15px;">
 +                <strong>🩺 CONFIGURAZIONE MEDICI</strong><br>
 +                Gestisci la lista dei medici prescrittori. Le modifiche si applicano automaticamente alla dropdown del TAB 1.
 +            </div>
 +            <div style="overflow-x: auto;">
 +                <table class="config-table">
 +                    <thead>
                         <tr>                         <tr>
-                            <td><strong>Esafosfina</strong></td+                            <th style="min-width: 120px;">Nome</th
-                            <td>0</td+                            <th style="min-width: 120px;">Cognome</th
-                            <td>1600</td+                            <th style="min-width: 80px;">Titolo</th
-                            <td>0</td+                            <th style="min-width: 250px;">Nome Completo (Visualizzato)</th
-                            <td>130</td> +                            <th>Azioni</th>
-                            <td>0</td> +
-                            <td>5g/50mL - Glicerofosfato di sodio</td>+
                         </tr>                         </tr>
 +                    </thead>
 +                    <tbody id="doctorsConfigTable">
 +                        <!-- Popolato dinamicamente -->
 +                    </tbody>
 +                </table>
 +            </div>
 +            <div class="form-row">
 +                <div class="form-col">
 +                    <button id="updateDoctorsBtn" class="button" onclick="updateDoctorsConfig()">Aggiorna Lista Medici</button>
 +                </div>
 +                <div class="form-col">
 +                    <button class="button secondary" onclick="showAddDoctorForm()">Aggiungi Nuovo Medico</button>
 +                </div>
 +            </div>
 +            <div class="section">
 +            <h2>Lista Infermiere</h2>
 +            <div class="info" style="margin-bottom: 15px;">
 +                <strong>👩‍⚕️ CONFIGURAZIONE INFERMIERE</strong><br>
 +                Gestisci la lista delle infermiere del reparto. Le modifiche si applicano automaticamente.
 +            </div>
 +            <div style="overflow-x: auto;">
 +                <table class="config-table">
 +                    <thead>
                         <tr>                         <tr>
-                            <td><strong>Magnesio Solfato</strong></td+                            <th style="min-width: 120px;">Nome</th
-                            <td>0</td+                            <th style="min-width: 120px;">Cognome</th
-                            <td>0</td+                            <th style="min-width: 80px;">Titolo</th
-                            <td>800</td+                            <th style="min-width: 250px;">Nome Completo (Visualizzato)</th
-                            <td>0</td> +                            <th>Azioni</th>
-                            <td>0</td> +
-                            <td>2g/10mL, 1.6 mEq/mL - Elettrolita essenziale</td>+
                         </tr>                         </tr>
 +                    </thead>
 +                    <tbody id="nursesConfigTable">
 +                        <!-- Popolato dinamicamente -->
 +                    </tbody>
 +                </table>
 +            </div>
 +            <div class="form-row">
 +                <div class="form-col">
 +                    <button id="updateNursesBtn" class="button" onclick="updateNursesConfig()">Aggiorna Lista Infermiere</button>
 +                </div>
 +                <div class="form-col">
 +                    <button class="button secondary" onclick="showAddNurseForm()">Aggiungi Nuova Infermiera</button>
 +                </div>
 +            </div>
 +        </div>
 +
 +        <div class="section">
 +            <h2>Lista Farmacisti</h2>
 +            <div class="info" style="margin-bottom: 15px;">
 +                <strong>💊 CONFIGURAZIONE FARMACISTI</strong><br>
 +                Gestisci la lista dei farmacisti ospedalieri. Le modifiche si applicano automaticamente.
 +            </div>
 +            <div style="overflow-x: auto;">
 +                <table class="config-table">
 +                    <thead>
                         <tr>                         <tr>
-                            <td><strong>Sodio Cloruro</strong></td> +                            <th style="min-width: 120px;">Nome</th
-                            <td>0</td> +                            <th style="min-width: 120px;">Cognome</th
-                            <td>0</td> +                            <th style="min-width: 80px;">Titolo</th
-                            <td>0</td> +                            <th style="min-width: 250px;">Nome Completo (Visualizzato)</th
-                            <td>1000</td> +                            <th>Azioni</th>
-                            <td>0</td> +
-                            <td>3mEq/mL Prima scelta per sodio</td> +
-                        </tr> +
-                        <tr+
-                            <td><strong>Sodio Acetato</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>667</td> +
-                            <td>0</td> +
-                            <td>2 mEq/mL Alcalinizzante per acidosi</td> +
-                        </tr> +
-                        <tr+
-                            <td><strong>Potassio Cloruro</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>1000</td> +
-                            <td>2 mEq/mL Max vel. 0.5 mEq/kg/h</td> +
-                        </tr> +
-                        <tr+
-                            <td><strong>Trophamine 6%</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>Aminoacidi pediatrici 6g/100mL</td> +
-                        </tr> +
-                        <tr+
-                            <td><strong>Intralipid 20%</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>Emulsione lipidica - 20g/100mL</td>+
                         </tr>                         </tr>
 +                    </thead>
 +                    <tbody id="pharmacistsConfigTable">
 +                        <!-- Popolato dinamicamente -->
                     </tbody>                     </tbody>
                 </table>                 </table>
             </div>             </div>
-            <div class="infostyle="margin-top: 15px;"> +            <div class="form-row"
-                <strong>ℹ️ Informazioni:</strongConcentrazioni standard utilizzate per i calcoli elettrolitici. I valori sono basati su preparazioni farmaceutiche standard.+                <div class="form-col"
 +                    <button id="updatePharmacistsBtn" class="button" onclick="updatePharmacistsConfig()">Aggiorna Lista Farmacisti</button
 +                </div> 
 +                <div class="form-col"> 
 +                    <button class="button secondary" onclick="showAddPharmacistForm()">Aggiungi Nuovo Farmacista</button> 
 +                </div>
             </div>             </div>
         </div>         </div>
  
         <div class="section">         <div class="section">
-            <h2>Lista Medici Prescrittori</h2>+            <h2>Lista Tecnici di Farmacia</h2>
             <div class="info" style="margin-bottom: 15px;">             <div class="info" style="margin-bottom: 15px;">
-                <strong>🩺 Database Medici:</strong> Lista dei medici autorizzati alla prescrizione NPTQuesti nomi appaiono nella dropdown del TAB 1.+                <strong>🔬 CONFIGURAZIONE TECNICI</strong><br> 
 +                Gestisci la lista dei tecnici di farmaciaLe modifiche si applicano automaticamente.
             </div>             </div>
             <div style="overflow-x: auto;">             <div style="overflow-x: auto;">
-                <table class="results-table" style="font-size: 12px;">+                <table class="config-table">
                     <thead>                     <thead>
                         <tr>                         <tr>
-                            <th>Nome</th> +                            <th style="min-width: 120px;">Nome</th> 
-                            <th>Cognome</th> +                            <th style="min-width: 120px;">Cognome</th> 
-                            <th>Titolo</th> +                            <th style="min-width: 80px;">Titolo</th> 
-                            <th>Nome Completo (Visualizzato)</th>+                            <th style="min-width: 250px;">Nome Completo (Visualizzato)</th> 
 +                            <th>Azioni</th>
                         </tr>                         </tr>
                     </thead>                     </thead>
-                    <tbody> +                    <tbody id="techniciansConfigTable"
-                        <tr><td>Roberto</td><td>Bellù</td><td>Dr.</td><td><strong>Dr. Roberto Bellù</strong></td></tr> +                        <!-- Popolato dinamicamente -->
-                        <tr><td>Manuela</td><td>Condò</td><td>Dr.ssa</td><td><strong>Dr.ssa Manuela Condò</strong></td></tr> +
-                        <tr><td>Carla</td><td>Maccioni</td><td>Dr.ssa</td><td><strong>Dr.ssa Carla Maccioni</strong></td></tr> +
-                        <tr><td>Federica</td><td>Meroni</td><td>Dr.ssa</td><td><strong>Dr.ssa Federica Meroni</strong></td></tr> +
-                        <tr><td>Francesco</td><td>Calzatini</td><td>Dr.</td><td><strong>Dr. Francesco Calzatini</strong></td></tr> +
-                        <tr><td>Elisabetta</td><td>Ferrari</td><td>Dr.ssa</td><td><strong>Dr.ssa Elisabetta Ferrari</strong></td></tr>+
                     </tbody>                     </tbody>
                 </table>                 </table>
 +            </div>
 +            <div class="form-row">
 +                <div class="form-col">
 +                    <button id="updateTechniciansBtn" class="button" onclick="updateTechniciansConfig()">Aggiorna Lista Tecnici</button>
 +                </div>
 +                <div class="form-col">
 +                    <button class="button secondary" onclick="showAddTechnicianForm()">Aggiungi Nuovo Tecnico</button>
 +                </div>
             </div>             </div>
 +        </div>
         </div>         </div>
  
-        <div class="section"> +        <!-- SEZIONE CONFIGURAZIONE CLINICA AVANZATA (NOVITÀ) --> 
-            <h2>Informazioni Sistema</h2+        <div class="config-advanced"> 
-            <div class="info"> +            <h3>🔬 CONFIGURAZIONE CLINICA AVANZATA</h3> 
-                <strong>📊 NPT Calculator v2.0 - Stato Sistema</strong><br+             
-                <strong>• Database Formule:</strong9 formule enterali configurate<br+            <div class="section"> 
-                <strong>• Database Componenti:</strong8 componenti parenterali configurati<br+                <h2>Parametri Elettroliti e Controlli</h2> 
-                <strong>• Medici Prescrittori:</strong> 6 medici autorizzati<br+                <div class="form-row"> 
-                <strong>• Algoritmi:</strongCalcoli BUN, fasi nutrizionali, elettroliti automatici<br+                    <div class="form-col"> 
-                <strong>• Report:</strongFoglio di lavoro + Report parenterale completo<br+                        <div class="input-group"> 
-                <strong>• Ultimo Aggiornamento:</strongLuglio 2025+                            <label for="calciumReq">Calcio standard (mg/kg/die):</label> 
 +                            <input type="number" id="calciumReq" min="0" max="200" value="160"> 
 +                            <span style="margin-left: 10px; font-size: 12px; color: #666;">Range: 120-200</span> 
 +                        </div
 +                        <div class="input-group"> 
 +                            <label for="phosphorusReq">Fosforo standard (mg/kg/die):</label> 
 +                            <input type="number" id="phosphorusReq" min="0" max="100" value="84"
 +                            <span style="margin-left: 10px; font-size: 12px; color: #666;">Range60-120</span> 
 +                        </div
 +                        <div class="input-group"> 
 +                            <label for="magnesiumReq">Magnesio standard (mEq/kg/die):</label> 
 +                            <input type="number" id="magnesiumReq" min="0" max="2" step="0.1" value="0.6"> 
 +                            <span style="margin-left: 10px; font-size: 12px; color: #666;">Range: 0.3-1.0</span
 +                        </div> 
 +                    </div> 
 +                    <div class="form-col"> 
 +                        <div class="input-group"> 
 +                            <label for="maxGIR">GIR massimo (mg/kg/min):</label> 
 +                            <input type="number" id="maxGIR" min="5" max="20" step="0.1" value="12.0"
 +                            <span style="margin-left: 10px; font-size: 12px; color: #666;">Limite sicurezza</span> 
 +                        </div> 
 +                        <div class="input-group"> 
 +                            <label for="maxLipids">Lipidi massimi (g/kg/die):</label> 
 +                            <input type="number" id="maxLipids" min="1" max="4" step="0.1" value="3.0"
 +                            <span style="margin-left: 10px; font-size: 12px; color: #666;">Limite sicurezza</span> 
 +                        </div> 
 +                        <div class="input-group"> 
 +                            <label for="maxProtein">Proteine massime (g/kg/die):</label> 
 +                            <input type="number" id="maxProtein" min="3" max="6" step="0.1" value="4.5"> 
 +                            <span style="margin-left: 10px; font-size: 12px; color: #666;">Limite sicurezza</span> 
 +                        </div> 
 +                    </div> 
 +                </div> 
 +                <button class="button" onclick="updateClinicalConfig()">AGGIORNA PARAMETRI CLINICI</button>
             </div>             </div>
 +
 +            <div class="section">
 +                <h2>Piano di Monitoraggio Automatico</h2>
 +                <table class="monitoring-table">
 +                    <thead>
 +                        <tr>
 +                            <th>Controllo</th>
 +                            <th>Frequenza</th>
 +                            <th>Range Normale</th>
 +                            <th>Azione se Fuori Range</th>
 +                        </tr>
 +                    </thead>
 +                    <tbody>
 +                        <tr>
 +                            <td><strong>Glicemia</strong></td>
 +                            <td>Ogni 6-8h</td>
 +                            <td>70-110 mg/dL</td>
 +                            <td>Aggiustare velocità glucosio</td>
 +                        </tr>
 +                        <tr>
 +                            <td><strong>Elettroliti</strong></td>
 +                            <td>Ogni 24-48h</td>
 +                            <td>Na: 135-145, K: 3.5-5.0</td>
 +                            <td>Modificare apporti NPT</td>
 +                        </tr>
 +                        <tr>
 +                            <td><strong>BUN/Creatinina</strong></td>
 +                            <td>Ogni 48h</td>
 +                            <td>BUN: 9-14 mg/dL</td>
 +                            <td>Aggiustare proteine</td>
 +                        </tr>
 +                        <tr>
 +                            <td><strong>Trigliceridi</strong></td>
 +                            <td>2 volte/settimana</td>
 +                            <td>&lt; 150 mg/dL</td>
 +                            <td>Ridurre lipidi se &gt; 200</td>
 +                        </tr>
 +                        <tr>
 +                            <td><strong>Funzione epatica</strong></td>
 +                            <td>Settimanale</td>
 +                            <td>AST/ALT normali</td>
 +                            <td>Valutare sospensione NPT</td>
 +                        </tr>
 +                    </tbody>
 +                </table>
 +            </div>
 +
 +            <div class="section">
 +                <h2>⚠️ ALERT AUTOMATICI</h2>
 +                <div class="alert-critical">
 +                    <strong>INTERRUZIONE IMMEDIATA NPT SE:</strong><br>
 +                    • Glicemia > 250 mg/dL o < 40 mg/dL<br>
 +                    • Trigliceridi > 400 mg/dL<br>
 +                    • AST/ALT > 3x valore normale<br>
 +                    • Segni di sepsi cateter-correlata<br>
 +                    • Edema importante con bilancio positivo > 20 ml/kg/die
 +                </div>
 +                
 +                <div class="warning">
 +                    <strong>AGGIUSTAMENTI NECESSARI SE:</strong><br>
 +                    • GIR > 12 mg/kg/min → Ridurre glucosio<br>
 +                    • BUN > 20 mg/dL → Ridurre proteine<br>
 +                    • BUN < 5 mg/dL → Aumentare proteine<br>
 +                    • Trigliceridi 200-400 mg/dL → Ridurre/sospendere lipidi<br>
 +                    • Ipernatremia → Ridurre sodio, aumentare liquidi liberi
 +                </div>
 +            </div>
 +
 +            <div class="section">
 +                <h2>Impostazioni Ospedale</h2>
 +                <div class="form-row">
 +                    <div class="form-col">
 +                        <div class="input-group">
 +                            <label for="hospitalName">Nome Ospedale:</label>
 +                            <input type="text" id="hospitalName" value="ASST LECCO" style="width: 250px;">
 +                        </div>
 +                        <div class="input-group">
 +                            <label for="departmentName">Dipartimento:</label>
 +                            <input type="text" id="departmentName" value="S.C. Neonatologia e TIN" style="width: 250px;">
 +                        </div>
 +                        <div class="input-group">
 +                            <label for="directorName">Direttore:</label>
 +                            <input type="text" id="directorName" value="Dott. Roberto Bellù" style="width: 250px;">
 +                        </div>
 +                    </div>
 +                    <div class="form-col">
 +                        <div class="input-group">
 +                            <label for="autoSave">Salvataggio automatico:</label>
 +                            <select id="autoSave">
 +                                <option value="true">Attivo</option>
 +                                <option value="false">Disattivo</option>
 +                            </select>
 +                        </div>
 +                        <div class="input-group">
 +                            <label for="decimalPlaces">Cifre decimali:</label>
 +                            <select id="decimalPlaces">
 +                                <option value="1">1 cifra</option>
 +                                <option value="2" selected>2 cifre</option>
 +                                <option value="3">3 cifre</option>
 +                            </select>
 +                        </div>
 +                    </div>
 +                </div>
 +                <button class="button secondary" onclick="resetConfiguration()">RESET CONFIGURAZIONE</button>
 +                <button class="button" onclick="saveConfiguration()">SALVA CONFIGURAZIONE</button>
 +            </div>
 +        </div>
 +
 +        <div id="configResults" class="results hidden">
 +            <h3>Stato Configurazione v3.0</h3>
 +            <div id="configInfo"></div>
         </div>         </div>
     </div>     </div>
Linea 1201: Linea 1966:
  
 <script> <script>
-// DATI NUTRIZIONALI COMPLETI+// DATI NUTRIZIONALI COMPLETI (DA VERSIONE 17)
 const formulaData = { const formulaData = {
     maternal: { name: "Latte Materno", protein: 1.2, carbs: 7.0, lipids: 4.0, sodium: 0.007, potassium: 0.035, calcium: 28.0, phosphorus: 15.0, magnesium: 3.0, energy: 67 },     maternal: { name: "Latte Materno", protein: 1.2, carbs: 7.0, lipids: 4.0, sodium: 0.007, potassium: 0.035, calcium: 28.0, phosphorus: 15.0, magnesium: 3.0, energy: 67 },
Linea 1214: Linea 1979:
 }; };
  
-// CONFIGURAZIONI PARENTERALI COMPLETE+// CONFIGURAZIONI PARENTERALI COMPLETE (DA VERSIONE 17)
 const parenteralConfig = { const parenteralConfig = {
 +    trophamine: {
 +        name: "Trophamine 6%",
 +        protein: 6.0, carbs: 0, lipids: 0, sodium: 0, potassium: 0,
 +        calcium: 0, phosphorus: 0, magnesium: 0, energy: 24, water: 94,
 +        osmolarity: 360, // mOsm/L
 +        description: "Soluzione di aminoacidi pediatrica",
 +        notes: "Soluzione sterile per uso endovenoso. Osmolarità: ~360 mOsm/L"
 +    },
 +    intralipid: {
 +        name: "Intralipid 20%",
 +        protein: 0, carbs: 0, lipids: 20.0, sodium: 0, potassium: 0,
 +        calcium: 0, phosphorus: 0, magnesium: 0, energy: 200, water: 80,
 +        osmolarity: 280, // mOsm/L
 +        description: "Emulsione lipidica endovenosa",
 +        notes: "Fornisce acidi grassi essenziali. Max 4g/kg/die. Osmolarità: ~280 mOsm/L"
 +    },
 +    glucose50: {
 +        name: "Glucosio 50%",
 +        protein: 0, carbs: 50.0, lipids: 0, sodium: 0, potassium: 0,
 +        calcium: 0, phosphorus: 0, magnesium: 0, energy: 200, water: 50,
 +        osmolarity: 2780, // mOsm/L
 +        description: "Soluzione glucosata molto ipertonica",
 +        notes: "Osmolarità: ~2780 mOsm/L. Solo per alte concentrazioni"
 +    },
     ca_gluconato: {     ca_gluconato: {
-        name: "Calcio Gluconato 10%", +        name: "Calcio Gluconato 10% (1g/10mL, 0.44 mEq/mL)", 
-        calcium840phosphorus: 0, magnesium: 0, sodium: 0, potassium: 0, +        protein0carbs: 0, lipids: 0, sodium: 0, potassium: 0, 
-        protein0carbs: 0, lipids: 0, energy: 0, water: 90+        calcium840phosphorus: 0, magnesium: 0, energy: 0, water: 90
 +        osmolarity: 320, // mOsm/L 
 +        description: "Sale di calcio organico", 
 +        notes: "8.4 mg Ca/ml. Non precipita con fosfati. Osmolarità: ~320 mOsm/L"
     },     },
     esafosfina: {     esafosfina: {
-        name: "Esafosfina", +        name: "Esafosfina (5g/50mL)", 
-        calcium: 0, phosphorus1600magnesium: 0, sodium: 130, potassium: 0, +        protein: 0, carbs0lipids: 0, sodium: 130, potassium: 0, 
-        protein: 0, carbs0lipids: 0, energy: 0, water: 98+        calcium: 0, phosphorus1600magnesium: 0, energy: 0, water: 98
 +        osmolarity: 450, // mOsm/L 
 +        description: "Glicerofosfato di sodio", 
 +        notes: "16 mg P/ml + 1.3 mEq Na/ml. Fosforo organico. Osmolarità: ~450 mOsm/L"
     },     },
     mg_sulfate: {     mg_sulfate: {
-        name: "Magnesio Solfato", +        name: "Magnesio Solfato (2g/10ml, 1.6 mEq/mL)", 
-        calcium: 0, phosphorus: 0, magnesium800, sodium: 0, potassium: 0, +        protein: 0, carbs: 0, lipids0, sodium: 0, potassium: 0, 
-        protein: 0, carbs: 0, lipids0, energy: 0, water: 99+        calcium: 0, phosphorus: 0, magnesium800, energy: 0, water: 99
 +        osmolarity: 1620, // mOsm/L 
 +        description: "Elettrolita essenziale", 
 +        notes: "8 mEq Mg/ml. Cofattore enzimatico. Osmolarità: ~1620 mOsm/L"
     },     },
     nacl: {     nacl: {
-        name: "Sodio Cloruro", +        name: "Sodio Cloruro (3mEq/mL)", 
-        calcium: 0, phosphorus: 0, magnesium: 0, sodium: 1000, potassium: 0, +        protein: 0, carbs: 0, lipids: 0, sodium: 1000, potassium: 0, 
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 99+        calcium: 0, phosphorus: 0, magnesium: 0, energy: 0, water: 99
 +        osmolarity: 2050, // mOsm/L 
 +        description: "Elettrolita essenziale", 
 +        notes: "10 mEq Na/ml. Prima scelta per supplementazione sodio. Osmolarità: ~2050 mOsm/L"
     },     },
     sodium_acetate: {     sodium_acetate: {
-        name: "Sodio Acetato", +        name: "Sodio Acetato (3 mEq/mL)", 
-        calcium: 0, phosphorus: 0, magnesium: 0, sodium: 667, potassium: 0, +        protein: 0, carbs: 0, lipids: 0, sodium: 667, potassium: 0, 
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 99+        calcium: 0, phosphorus: 0, magnesium: 0, energy: 0, water: 99
 +        osmolarity: 1340, // mOsm/L 
 +        description: "Elettrolita alcalinizzante", 
 +        notes: "6.67 mEq Na/ml. Per acidosi: pH < 7.25 o BE < -4. Osmolarità: ~1340 mOsm/L"
     },     },
     kcl: {     kcl: {
-        name: "Potassio Cloruro", +        name: "Potassio Cloruro (2 mEq/mL)", 
-        calcium: 0, phosphorus: 0, magnesium: 0, sodium: 0, potassium: 1000, +        protein: 0, carbs: 0, lipids: 0, sodium: 0, potassium: 1000
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 99+        calcium: 0, phosphorus: 0, magnesium: 0, energy: 0, water: 99, 
 +        osmolarity: 2050, // mOsm/L 
 +        description: "Elettrolita essenziale", 
 +        notes: "10 mEq K/ml. Max velocità infusione: 0.5 mEq/kg/h. Osmolarità: ~2050 mOsm/L" 
 +    }, 
 +    carnitene: { 
 +        name: "Carnitene (100 mg/ml)"
 +        protein: 0, carbs: 0, lipids: 0, sodium: 0, potassium: 0, 
 +        calcium: 0, phosphorus: 0, magnesium: 0, energy: 0, water: 99
 +        osmolarity: 280, // mOsm/L 
 +        carnitine: 10000, // 100 mg/ml = 10000 mg/100ml 
 +        description: "L-Carnitina per NPT prolungata", 
 +        notes: "100 mg/ml. Indicata per NPT > 1 mese. Dose: 5 mg/kg/die. Osmolarità: ~280 mOsm/L"
     }     }
 }; };
  
-// Database medici +// Database fortificanti dinamico 
-const doctorsData = {+let fortifierData = { 
 +    prenidina_fm85:
 +        name: "Prenidina FM85", 
 +        protein: 14, carbs: 4, lipids: 2.5, sodium: 2, potassium: 15, 
 +        calcium: 3500, phosphorus: 2000, magnesium: 150, energy: 400, 
 +        dose: "1-4g/100ml" 
 +    } 
 +}; 
 + 
 +// Database medici dinamico 
 +let doctorsData = {
     dr_bellu: { name: "Roberto", surname: "Bellù", title: "Dr.", fullName: "Dr. Roberto Bellù" },     dr_bellu: { name: "Roberto", surname: "Bellù", title: "Dr.", fullName: "Dr. Roberto Bellù" },
     dr_condo: { name: "Manuela", surname: "Condò", title: "Dr.ssa", fullName: "Dr.ssa Manuela Condò" },     dr_condo: { name: "Manuela", surname: "Condò", title: "Dr.ssa", fullName: "Dr.ssa Manuela Condò" },
Linea 1255: Linea 2081:
     dr_meroni: { name: "Federica", surname: "Meroni", title: "Dr.ssa", fullName: "Dr.ssa Federica Meroni" },     dr_meroni: { name: "Federica", surname: "Meroni", title: "Dr.ssa", fullName: "Dr.ssa Federica Meroni" },
     dr_calzatini: { name: "Francesco", surname: "Calzatini", title: "Dr.", fullName: "Dr. Francesco Calzatini" },     dr_calzatini: { name: "Francesco", surname: "Calzatini", title: "Dr.", fullName: "Dr. Francesco Calzatini" },
-    dr_ferrari: { name: "Elisabetta", surname: "Ferrari", title: "Dr.ssa", fullName: "Dr.ssa Elisabetta Ferrari" }+    dr_ferrari: { name: "Elisabetta", surname: "Ferrari", title: "Dr.ssa", fullName: "Dr.ssa Elisabetta Ferrari" }, 
 +    dr_ferendeles: { name: "Francesca", surname: "Ferendeles", title: "Dr.ssa", fullName: "Dr.ssa Francesca Ferendeles" }, 
 +    dr_fumagalli_l: { name: "Letizia", surname: "Fumagalli", title: "Dr.ssa", fullName: "Dr.ssa Letizia Fumagalli" }, 
 +    dr_fumagalli_m: { name: "Mara", surname: "Fumagalli", title: "Dr.ssa", fullName: "Dr.ssa Mara Fumagalli" }, 
 +    dr_corno: { name: "Federica", surname: "Corno", title: "Dr.ssa", fullName: "Dr.ssa Federica Corno" }, 
 +    dr_evasi: { name: "Veronica", surname: "Evasi", title: "Dr.ssa", fullName: "Dr.ssa Veronica Evasi" }, 
 +    dr_cereda: { name: "Lidia", surname: "Cereda", title: "Dr.ssa", fullName: "Dr.ssa Lidia Cereda" }, 
 +    dr_ceccon: { name: "Chiara", surname: "Ceccon", title: "Dr.ssa", fullName: "Dr.ssa Chiara Ceccon" }, 
 +    dr_nava: { name: "Chiara", surname: "Nava", title: "Dr.ssa", fullName: "Dr.ssa Chiara Nava" }, 
 +    dr_terenzi: { name: "Francesca", surname: "Terenzi", title: "Dr.ssa", fullName: "Dr.ssa Francesca Terenzi" }, 
 +    dr_raffa: { name: "Milena", surname: "Raffa", title: "Dr.ssa", fullName: "Dr.ssa Milena Raffa" }, 
 +    dr_aquisti: { name: "Giulia", surname: "Aquisti", title: "Dr.ssa", fullName: "Dr.ssa Giulia Aquisti" }
 }; };
 +
 +// Database infermiere dinamico
 +let nursesData = {
 +    inf_rossi: { name: "Maria", surname: "Rossi", title: "Inf.", fullName: "Inf. Maria Rossi" },
 +    inf_bianchi: { name: "Laura", surname: "Bianchi", title: "Inf.", fullName: "Inf. Laura Bianchi" },
 +    inf_verdi: { name: "Giulia", surname: "Verdi", title: "Inf.", fullName: "Inf. Giulia Verdi" },
 +    inf_ferrari: { name: "Anna", surname: "Ferrari", title: "Inf.", fullName: "Inf. Anna Ferrari" },
 +    inf_moretti: { name: "Silvia", surname: "Moretti", title: "Inf.", fullName: "Inf. Silvia Moretti" },
 +    inf_conti: { name: "Elena", surname: "Conti", title: "Inf.", fullName: "Inf. Elena Conti" }
 +};
 +
 +// Database farmacisti dinamico
 +let pharmacistsData = {
 +    farm_lombardi: { name: "Marco", surname: "Lombardi", title: "Dr. Farm.", fullName: "Dr. Farm. Marco Lombardi" },
 +    farm_ricci: { name: "Paolo", surname: "Ricci", title: "Dr. Farm.", fullName: "Dr. Farm. Paolo Ricci" },
 +    farm_marino: { name: "Francesca", surname: "Marino", title: "Dr.ssa Farm.", fullName: "Dr.ssa Farm. Francesca Marino" },
 +    farm_greco: { name: "Andrea", surname: "Greco", title: "Dr. Farm.", fullName: "Dr. Farm. Andrea Greco" },
 +    farm_bruno: { name: "Valentina", surname: "Bruno", title: "Dr.ssa Farm.", fullName: "Dr.ssa Farm. Valentina Bruno" }
 +};
 +
 +// Database tecnici di farmacia dinamico
 +let technicianData = {
 +    tec_russo: { name: "Giuseppe", surname: "Russo", title: "Tec.", fullName: "Tec. Giuseppe Russo" },
 +    tec_gallo: { name: "Roberto", surname: "Gallo", title: "Tec.", fullName: "Tec. Roberto Gallo" },
 +    tec_costa: { name: "Michela", surname: "Costa", title: "Tec.", fullName: "Tec. Michela Costa" },
 +    tec_rizzo: { name: "Alessandro", surname: "Rizzo", title: "Tec.", fullName: "Tec. Alessandro Rizzo" },
 +    tec_longo: { name: "Chiara", surname: "Longo", title: "Tec.", fullName: "Tec. Chiara Longo" },
 +    tec_giordano: { name: "Matteo", surname: "Giordano", title: "Tec.", fullName: "Tec. Matteo Giordano" }
 +};
 +
 +
  
 // VARIABILI GLOBALI // VARIABILI GLOBALI
 let patientData = {}; let patientData = {};
 let enteralData = null; let enteralData = null;
-window.currentActiveReport = null;+let currentRequirements = null; 
 + 
 +// CONFIGURAZIONE CLINICA AVANZATA (NUOVO) 
 +let clinicalConfig = { 
 +    calciumReq: 160, 
 +    phosphorusReq: 84, 
 +    magnesiumReq: 0.6, 
 +    maxGIR: 12.0, 
 +    maxLipids: 3.0, 
 +    maxProtein: 4.5, 
 +    hospitalName: "ASST LECCO", 
 +    departmentName: "S.C. Neonatologia e Terapia Intensiva Neonatale", 
 +    directorName: "Dr. Roberto Bellù" 
 +}; 
 + 
 +// FUNZIONE RESET PULSANTE FABBISOGNI 
 +function resetNutritionButton() { 
 +    const nutritionBtn = document.getElementById('calculateNutritionBtn'); 
 +    if (nutritionBtn) { 
 +        nutritionBtn.className = 'button calculate-nutrition-pending'; 
 +        nutritionBtn.innerHTML = 'RICALCOLA FABBISOGNI'; 
 +         
 +        // Nascondi i risultati precedenti 
 +        const nutritionResults = document.getElementById('nutritionResults'); 
 +        if (nutritionResults) { 
 +            nutritionResults.classList.add('hidden'); 
 +        } 
 +         
 +        // Reset anche il pulsante NPT perché i fabbisogni sono cambiati 
 +        resetParenteralButton(); 
 +    } 
 +
 + 
 +// FUNZIONE RESET PULSANTE PARENTERALE 
 +function resetParenteralButton() { 
 +    const parenteralBtn = document.getElementById('calculateParenteralBtn'); 
 +    if (parenteralBtn) { 
 +        parenteralBtn.className = 'button'; 
 +        parenteralBtn.innerHTML = 'CALCOLA NPT AUTOMATICA'; 
 +         
 +        // Reset anche i campi visualizzati 
 +        document.getElementById('calculatedTotalVolume').value = "Premere 'Calcola NPT'"; 
 +        document.getElementById('suggestedGlucose').value = "Premere 'Calcola NPT'"; 
 +        document.getElementById('calculatedProteinVol').value = "--"; 
 +        document.getElementById('calculatedLipidVol').value = "--"; 
 +         
 +        // Nascondi i risultati precedenti 
 +        const parenteralResults = document.getElementById('parenteralResults'); 
 +        if (parenteralResults) { 
 +            parenteralResults.classList.add('hidden'); 
 +        } 
 +    } 
 +
 + 
 + 
 +// SISTEMA PROTEZIONE CONFIGURAZIONE 
 +function checkConfigAccess() { 
 +    // Password predefinita (modificabile) 
 +    const ADMIN_PASSWORD = "admin2025"; 
 +     
 +    // Controlla se l'accesso è già stato autorizzato in questa sessione 
 +    if (window.configAccessGranted === true) { 
 +        return true; 
 +    } 
 +     
 +    // Richiedi password 
 +    const userPassword = prompt( 
 +        "🔐 ACCESSO CONFIGURAZIONE RISERVATO\n\n"
 +        "Inserire la password di amministrazione per accedere alle impostazioni del sistema NPT Calculator v3.0:" 
 +    ); 
 +     
 +    // Se utente cancella 
 +    if (userPassword === null) { 
 +        return false; 
 +    } 
 +     
 +    // Verifica password 
 +    if (userPassword === ADMIN_PASSWORD) { 
 +        window.configAccessGranted = true; 
 +        alert("✅ Accesso autorizzato!\n\nBenvenuto nella configurazione avanzata NPT Calculator v3.0"); 
 +        return true; 
 +    } else { 
 +        alert("❌ Password non corretta!\n\nAccesso negato alla configurazione."); 
 +        return false; 
 +    } 
 +
 + 
 +// Funzione per logout configurazione 
 +function logoutConfig() { 
 +    window.configAccessGranted = false; 
 +    alert("🔓 Logout configurazione effettuato.\nPer rientrare servirà di nuovo la password."); 
 +    // Torna al TAB 1 
 +    showTab('patient-data'); 
 +}
  
-// INIZIALIZZAZIONE 
-document.addEventListener('DOMContentLoaded', function() { 
-    // Imposta data odierna 
-    const today = new Date().toISOString().split('T')[0]; 
-    document.getElementById('prescriptionDate').value = today; 
-}); 
  
-// FUNZIONE TAB+// FUNZIONE CORRETTA PER CAMBIO TAB
 function showTab(tabId) { function showTab(tabId) {
-    // Rimuovi classe active da tutti i contenuti+    // Nascondi tutti i contenuti dei tab
     document.querySelectorAll('.tab-content').forEach(content => {     document.querySelectorAll('.tab-content').forEach(content => {
         content.classList.remove('active');         content.classList.remove('active');
     });     });
          
-    // Rimuovi classe active da tutte le tab+    // Rimuovi classe active da tutti i tab
     document.querySelectorAll('.tab').forEach(tab => {     document.querySelectorAll('.tab').forEach(tab => {
         tab.classList.remove('active');         tab.classList.remove('active');
     });     });
          
-    // Mostra il contenuto selezionato+    // Mostra il contenuto del tab selezionato
     const targetContent = document.getElementById(tabId);     const targetContent = document.getElementById(tabId);
     if (targetContent) {     if (targetContent) {
Linea 1288: Linea 2243:
     }     }
          
-    // Attiva la tab cliccata +    // Trova e attiva il tab cliccato 
-    event.target.closest('.tab').classList.add('active');+    const clickedTab = event.target.closest('.tab')
 +    if (clickedTab) { 
 +        clickedTab.classList.add('active'); 
 +    } 
 +     
 +    // Sistema di protezione per TAB configurazione 
 +    if (tabId === 'config') { 
 +        if (!checkConfigAccess()) { 
 +            return; // Blocca l'accesso se password non corretta 
 +        } 
 +        setTimeout(() => { 
 +            populateEnteralConfigTable(); 
 +            populateParenteralConfigTable(); 
 +            populateDoctorsConfigTable(); 
 +            populateNursesConfigTable(); 
 +            populatePharmacistsConfigTable(); 
 +            populateTechniciansConfigTable(); 
 +        }, 100); 
 +    } 
 + 
 +// Popola le dropdown del personale quando si apre il TAB 5 (report) 
 +if (tabId === 'report') { 
 +    setTimeout(() => { 
 +        updatePreparationStaffDropdowns(); 
 +    }, 100);
 } }
  
-// FUNZIONE CALCOLO FASE+
 + 
 +// FUNZIONE GESTIONE CARTELLA CLINICA 
 +function setupMedicalRecordField() { 
 +    const medicalRecordInput = document.getElementById('medicalRecord'); 
 +    const currentYear = new Date().getFullYear().toString(); 
 +     
 +    // Imposta il valore iniziale con l'anno corrente 
 +    if (!medicalRecordInput.value) { 
 +        medicalRecordInput.value = currentYear; 
 +    } 
 +     
 +    // Gestisce l'input per mantenere sempre l'anno all'inizio 
 +    medicalRecordInput.addEventListener('input', function(e) { 
 +        let value = e.target.value.replace(/\D/g, ''); // Solo numeri 
 +         
 +        // Se l'utente cerca di cancellare l'anno, lo ripristina 
 +        if (value.length < 4 || !value.startsWith(currentYear)) { 
 +            value = currentYear + value.slice(4); 
 +        } 
 +         
 +        // Limita a 10 cifre totali 
 +        if (value.length > 10) { 
 +            value = value.slice(0, 10); 
 +        } 
 +         
 +        e.target.value = value; 
 +    }); 
 +     
 +    // Quando il campo ottiene il focus, posiziona il cursore dopo l'anno 
 +    medicalRecordInput.addEventListener('focus', function(e) { 
 +        if (e.target.value === currentYear) { 
 +            // Posiziona il cursore alla fine 
 +            setTimeout(() => { 
 +                e.target.setSelectionRange(4, 4); 
 +            }, 0); 
 +        } 
 +    }); 
 +     
 +    // Suggerimento visivo 
 +    medicalRecordInput.addEventListener('blur', function(e) { 
 +        if (e.target.value === currentYear) { 
 +            e.target.placeholder = currentYear + '000001'; 
 +        } 
 +    }); 
 +
 + 
 +function updateDoctorsDropdown() { 
 +    console.log('updateDoctorsDropdown chiamata'); 
 +    const prescribingDoctorSelect = document.getElementById('prescribingDoctor'); 
 +    console.log('Elemento prescribingDoctor trovato:', prescribingDoctorSelect); 
 +     
 +    if (!prescribingDoctorSelect) { 
 +        console.error('ERRORE: Elemento prescribingDoctor non trovato!'); 
 +        return; 
 +    } 
 +     
 +    console.log('doctorsData:', doctorsData); 
 +    console.log('Numero medici:', Object.keys(doctorsData).length); 
 +     
 +    const currentValue = prescribingDoctorSelect.value; 
 +    prescribingDoctorSelect.innerHTML = '<option value="">Seleziona medico</option>'; 
 +     
 +    Object.keys(doctorsData).forEach(function(key) { 
 +        const doctor = doctorsData[key]; 
 +        console.log('Aggiungendo medico:', doctor.fullName); 
 +        const option = document.createElement('option'); 
 +        option.value = key; 
 +        option.textContent = doctor.fullName; 
 +        prescribingDoctorSelect.appendChild(option); 
 +    }); 
 +     
 +    // Ripristina il valore precedente se esiste ancora 
 +    if (currentValue && doctorsData[currentValue]) { 
 +        prescribingDoctorSelect.value = currentValue; 
 +    } 
 +     
 +    console.log('Dropdown popolata con', prescribingDoctorSelect.options.length, 'opzioni'); 
 +
 + 
 +// FUNZIONE CALCOLO ETÀ POST-CONCEZIONALE 
 +function calculatePostConceptionalAge() { 
 +    const gestWeeks = parseInt(document.getElementById('gestationalWeeks').value) || 0; 
 +    const gestDays = parseInt(document.getElementById('gestationalDays').value) || 0; 
 +    const daysOfLife = parseInt(document.getElementById('daysOfLife').value) || 0; 
 +     
 +    if (gestWeeks === 0 || daysOfLife === 0) { 
 +        document.getElementById('postConceptionalAge').value = ''; 
 +        return null; 
 +    } 
 +     
 +    // Calcola età post-concezionale 
 +    const totalGestationalDays = (gestWeeks * 7) + gestDays; 
 +    const totalPostConceptionalDays = totalGestationalDays + daysOfLife; 
 +     
 +    // Converti in settimane+giorni 
 +    const pcWeeks = Math.floor(totalPostConceptionalDays / 7); 
 +    const pcDays = totalPostConceptionalDays % 7; 
 +     
 +    const pcAge = pcWeeks + '+' + pcDays; 
 +    document.getElementById('postConceptionalAge').value = pcAge + ' sett.'; 
 +     
 +    return { weeks: pcWeeks, days: pcDays, format: pcAge }; 
 +
 + 
 +// FUNZIONE CALCOLO FASE NUTRIZIONALE (DA VERSIONE 17)
 function calculatePhase() { function calculatePhase() {
     const medicalRecord = document.getElementById('medicalRecord').value;     const medicalRecord = document.getElementById('medicalRecord').value;
-    const birthWeight = parseInt(document.getElementById('birthWeight').value); +    const phaseBirthWeight = parseInt(document.getElementById('birthWeight').value); 
-    const currentWeight = parseInt(document.getElementById('currentWeight').value);+    const phaseCurrentWeight = parseInt(document.getElementById('currentWeight').value);
     const daysOfLife = parseInt(document.getElementById('daysOfLife').value);     const daysOfLife = parseInt(document.getElementById('daysOfLife').value);
     const bun = document.getElementById('bun').value;     const bun = document.getElementById('bun').value;
Linea 1305: Linea 2389:
     const diuresis = document.getElementById('diuresis').value;     const diuresis = document.getElementById('diuresis').value;
     const prescriptionDate = document.getElementById('prescriptionDate').value;     const prescriptionDate = document.getElementById('prescriptionDate').value;
-    const prescribingDoctor = document.getElementById('prescribingDoctor').value;+    const prescribingDoctorValue = document.getElementById('prescribingDoctor').value;
          
-    patientData = { +    // Trova il nome completo del medico 
-        medicalRecord: medicalRecord, +    const doctorFullName = prescribingDoctorValue && doctorsData[prescribingDoctorValue] ?  
-        birthWeight: birthWeight,  +                          doctorsData[prescribingDoctorValue].fullName : ''; 
-        currentWeight: currentWeight,  +     
-        daysOfLife: daysOfLife, + 
-        bun: bun, +// Recupera età gestazionale per i report 
-        glucose: glucose, +const gestationalWeeks = parseInt(document.getElementById('gestationalWeeks').value) || null; 
-        sodium: sodium, +const gestationalDays = parseInt(document.getElementById('gestationalDays').value) || null; 
-        ph: ph, + 
-        baseExcess: baseExcess, +// Calcola età post-concezionale 
-        diuresis: diuresis, +const postConceptionalAge = calculatePostConceptionalAge(); 
-        prescriptionDate: prescriptionDate, + 
-        prescribingDoctor: prescribingDoctor +patientData = { 
-    };+    medicalRecord: medicalRecord, 
 +    birthWeight: phaseBirthWeight,  
 +    currentWeight: phaseCurrentWeight,  
 +    daysOfLife: daysOfLife, 
 +    gestationalWeeks: gestationalWeeks, 
 +    gestationalDays: gestationalDays, 
 +    postConceptionalAge: postConceptionalAge, 
 +    bun: bun, 
 +    glucose: glucose, 
 +    sodium: sodium, 
 +    ph: ph, 
 +    baseExcess: baseExcess, 
 +    diuresis: diuresis, 
 +    prescriptionDate: prescriptionDate, 
 +    prescribingDoctor: prescribingDoctorValue, 
 +    prescribingDoctorName: doctorFullName 
 +};
          
     document.getElementById('targetDay').value = daysOfLife;     document.getElementById('targetDay').value = daysOfLife;
Linea 1333: Linea 2433:
         if (bunValue < 9) {         if (bunValue < 9) {
             bunStatus = 'Basso - Aumentare proteine';             bunStatus = 'Basso - Aumentare proteine';
-            bunWarning = 'BUN basso: considerare aumento proteine';+            bunWarning = 'BUN basso: considerare aumento fortificazione proteica (+1%)';
         } else if (bunValue > 14) {         } else if (bunValue > 14) {
             bunStatus = 'Elevato - Ridurre proteine';             bunStatus = 'Elevato - Ridurre proteine';
-            bunWarning = 'BUN elevato: ridurre proteine';+            bunWarning = 'BUN elevato: ridurre fortificazione proteica (-1%)';
         } else {         } else {
             bunStatus = 'Normale (9-14 mg/dL)';             bunStatus = 'Normale (9-14 mg/dL)';
Linea 1342: Linea 2442:
     } else {     } else {
         bunStatus = 'Non inserito';         bunStatus = 'Non inserito';
 +    }
 +    
 +    // Analisi altri parametri
 +    let otherWarnings = [];
 +    
 +    if (glucose && glucose !== '') {
 +        const glucoseValue = parseFloat(glucose);
 +        if (glucoseValue < 70) {
 +            otherWarnings.push('⚠️ Ipoglicemia: considerare riduzione velocità glucosio');
 +        } else if (glucoseValue > 150) {
 +            otherWarnings.push('⚠️ Iperglicemia: ridurre concentrazione glucosio NPT');
 +        }
 +    }
 +    
 +    if (sodium && sodium !== '') {
 +        const sodiumValue = parseFloat(sodium);
 +        if (sodiumValue < 135) {
 +            otherWarnings.push('⚠️ Iponatremia: aumentare sodio in NPT');
 +        } else if (sodiumValue > 145) {
 +            otherWarnings.push('⚠️ Ipernatremia: ridurre sodio, aumentare liquidi');
 +        }
 +    }
 +    
 +    if (ph && ph !== '') {
 +        const phValue = parseFloat(ph);
 +        if (phValue < 7.35) {
 +            otherWarnings.push('⚠️ Acidosi: valutare bicarbonato o ridurre cloruri');
 +        } else if (phValue > 7.45) {
 +            otherWarnings.push('⚠️ Alcalosi: ridurre bicarbonato, aumentare cloruri');
 +        }
 +    }
 +    
 +    if (baseExcess && baseExcess !== '') {
 +        const beValue = parseFloat(baseExcess);
 +        if (beValue < -4) {
 +            otherWarnings.push('⚠️ BE < -4: Acidosi metabolica - Considera Sodio Acetato in NPT');
 +        } else if (beValue > 2) {
 +            otherWarnings.push('⚠️ BE > +2: Alcalosi metabolica - Ridurre bicarbonato');
 +        }
 +    }
 +    
 +    // Raccomandazione combinata pH + BE per Sodio Acetato
 +    if (ph && baseExcess) {
 +        const phValue = parseFloat(ph);
 +        const beValue = parseFloat(baseExcess);
 +        if (phValue < 7.25 || beValue < -4) {
 +            otherWarnings.push('🧪 RACCOMANDAZIONE: Usa Sodio Acetato invece di NaCl in NPT');
 +        }
 +    }
 +    
 +    if (diuresis && diuresis !== '') {
 +        const diuresisValue = parseFloat(diuresis);
 +        if (diuresisValue < 1) {
 +            otherWarnings.push('⚠️ Oliguria: ridurre liquidi, controllare funzione renale');
 +        } else if (diuresisValue > 3) {
 +            otherWarnings.push('⚠️ Poliuria: aumentare liquidi, controllare osmolarità');
 +        }
     }     }
          
Linea 1351: Linea 2508:
         phaseInfoHtml += '<p><strong>Cartella:</strong> ' + medicalRecord + '</p>';         phaseInfoHtml += '<p><strong>Cartella:</strong> ' + medicalRecord + '</p>';
     }     }
-    phaseInfoHtml += '<p><strong>Peso:</strong> ' + currentWeight + 'g (nascita: ' + birthWeight + 'g)</p>';+    phaseInfoHtml += '<p><strong>Peso:</strong> ' + phaseCurrentWeight + 'g (nascita: ' + phaseBirthWeight + 'g)</p>';
     phaseInfoHtml += '<p><strong>Giorni di vita:</strong> ' + daysOfLife + '</p>';     phaseInfoHtml += '<p><strong>Giorni di vita:</strong> ' + daysOfLife + '</p>';
 +    
 +  if (gestationalWeeks && gestationalWeeks > 0) {
 +    const gestDaysDisplay = gestationalDays || 0;
 +    phaseInfoHtml += '<p><strong>Età gestazionale:</strong> ' + gestationalWeeks + '+' + gestDaysDisplay + ' settimane</p>';
 +    if (postConceptionalAge && postConceptionalAge.format) {
 +        phaseInfoHtml += '<p><strong>Età post-concezionale:</strong> ' + postConceptionalAge.format + ' settimane</p>';
 +    }
 +    }
     phaseInfoHtml += '<p><strong>Fase nutrizionale:</strong> ' + phase + '</p>';     phaseInfoHtml += '<p><strong>Fase nutrizionale:</strong> ' + phase + '</p>';
     phaseInfoHtml += '</div>';     phaseInfoHtml += '</div>';
Linea 1359: Linea 2524:
     if (patientData.bun) {     if (patientData.bun) {
         phaseInfoHtml += '<p><strong>BUN:</strong> ' + patientData.bun + ' mg/dL (' + bunStatus + ')</p>';         phaseInfoHtml += '<p><strong>BUN:</strong> ' + patientData.bun + ' mg/dL (' + bunStatus + ')</p>';
 +    }
 +    if (patientData.glucose) {
 +        const gluStatus = parseFloat(patientData.glucose) >= 70 && parseFloat(patientData.glucose) <= 110 ? 'Normale' : 'Fuori range';
 +        phaseInfoHtml += '<p><strong>Glicemia:</strong> ' + patientData.glucose + ' mg/dL (' + gluStatus + ')</p>';
 +    }
 +    if (patientData.sodium) {
 +        const naStatus = parseFloat(patientData.sodium) >= 135 && parseFloat(patientData.sodium) <= 145 ? 'Normale' : 'Fuori range';
 +        phaseInfoHtml += '<p><strong>Natremia:</strong> ' + patientData.sodium + ' mEq/L (' + naStatus + ')</p>';
 +    }
 +    if (patientData.ph) {
 +        const phStatus = parseFloat(patientData.ph) >= 7.35 && parseFloat(patientData.ph) <= 7.45 ? 'Normale' : 'Fuori range';
 +        phaseInfoHtml += '<p><strong>pH:</strong> ' + patientData.ph + ' (' + phStatus + ')</p>';
 +    }
 +    if (patientData.baseExcess) {
 +        const beStatus = parseFloat(patientData.baseExcess) >= -4 && parseFloat(patientData.baseExcess) <= 2 ? 'Normale' : 'Fuori range';
 +        phaseInfoHtml += '<p><strong>BE:</strong> ' + patientData.baseExcess + ' mEq/L (' + beStatus + ')</p>';
 +    }
 +    if (patientData.diuresis) {
 +        const diuStatus = parseFloat(patientData.diuresis) >= 1 && parseFloat(patientData.diuresis) <= 3 ? 'Normale' : 'Fuori range';
 +        phaseInfoHtml += '<p><strong>Diuresi:</strong> ' + patientData.diuresis + ' mL/kg/die (' + diuStatus + ')</p>';
     }     }
     phaseInfoHtml += '</div>';     phaseInfoHtml += '</div>';
Linea 1365: Linea 2550:
     if (bunWarning) {     if (bunWarning) {
         phaseInfoHtml += '<div class="info"><strong>Nota BUN:</strong> ' + bunWarning + '</div>';         phaseInfoHtml += '<div class="info"><strong>Nota BUN:</strong> ' + bunWarning + '</div>';
 +    }
 +    
 +    if (otherWarnings.length > 0) {
 +        phaseInfoHtml += '<div class="warning"><strong>Avvertenze Cliniche:</strong><br>' + otherWarnings.join('<br>') + '</div>';
     }     }
          
Linea 1375: Linea 2564:
     document.getElementById('calculatePhaseBtn').innerHTML = 'FASE CALCOLATA ✓';     document.getElementById('calculatePhaseBtn').innerHTML = 'FASE CALCOLATA ✓';
          
 +    // Aggiorna il suggerimento sodio se il TAB 3 è già stato visitato
     updateSodiumRecommendation();     updateSodiumRecommendation();
 +    
 +    // RESET anche il pulsante NPT
 +    resetParenteralButton();
 } }
  
-function updateSodiumRecommendation() { +// FUNZIONE AGGIORNAMENTO OPZIONI FORTIFICANTE
-    // Implementazione vuota per ora +
-+
- +
-// FUNZIONE FORTIFICANTE+
 function updateFortifierOptions() { function updateFortifierOptions() {
     const formulaType = document.getElementById('formulaType').value;     const formulaType = document.getElementById('formulaType').value;
     const fortifierSection = document.getElementById('fortifierSection');     const fortifierSection = document.getElementById('fortifierSection');
 +    const fortifierSelect = document.getElementById('fortifierType');
          
     if (formulaType === 'maternal') {     if (formulaType === 'maternal') {
         fortifierSection.classList.remove('hidden');         fortifierSection.classList.remove('hidden');
 +        
 +        fortifierSelect.innerHTML = '<option value="none">Nessun fortificante</option>';
 +        Object.keys(fortifierData).forEach(function(key) {
 +            const option = document.createElement('option');
 +            option.value = key;
 +            option.textContent = fortifierData[key].name;
 +            fortifierSelect.appendChild(option);
 +        });
     } else {     } else {
         fortifierSection.classList.add('hidden');         fortifierSection.classList.add('hidden');
 +        fortifierSelect.value = 'none';
     }     }
 } }
  
 +// FUNZIONE AGGIORNAMENTO DISPLAY CONCENTRAZIONE
 function updateConcentrationDisplay() { function updateConcentrationDisplay() {
     const concentration = document.getElementById('fortifierConcentration').value;     const concentration = document.getElementById('fortifierConcentration').value;
Linea 1399: Linea 2599:
 } }
  
-// FUNZIONE CALCOLO ENTERALE+// FUNZIONE CALCOLO NUTRIZIONE ENTERALE (DA VERSIONE 17)
 function calculateEnteral() { function calculateEnteral() {
-    if (!patientData.birthWeight) { +    // Controlla se i dati di base sono presenti 
-        alert('Prima inserire i dati del paziente nel TAB 1');+    const enteralCurrentWeight = parseInt(document.getElementById('currentWeight').value); 
 +    const enteralBirthWeight = parseInt(document.getElementById('birthWeight').value); 
 +     
 +    if (!enteralCurrentWeight || !enteralBirthWeight) { 
 +        alert('Prima inserire peso attuale e peso alla nascita nel TAB 1');
         return;         return;
 +    }
 +    
 +    // Aggiorna patientData se non è stato ancora fatto
 +    if (!patientData.currentWeight) {
 +        patientData.currentWeight = enteralCurrentWeight;
 +        patientData.birthWeight = enteralBirthWeight;
     }     }
          
Linea 1437: Linea 2647:
         const volumePerKg = (dailyVolume / currentWeight) * 1000;         const volumePerKg = (dailyVolume / currentWeight) * 1000;
                  
 +        // Calcoli finali per kg di peso
         enteralData = {         enteralData = {
             volume: dailyVolume,             volume: dailyVolume,
Linea 1456: Linea 2667:
         tableHtml += '<strong>Volume latte:</strong> ' + dailyVolume + ' ml (' + volumePerKg.toFixed(1) + ' ml/kg/die)<br>';         tableHtml += '<strong>Volume latte:</strong> ' + dailyVolume + ' ml (' + volumePerKg.toFixed(1) + ' ml/kg/die)<br>';
         if (additionalFluids > 0) {         if (additionalFluids > 0) {
-            tableHtml += '<strong>Altri liquidi:</strong> ' + additionalFluids + ' ml<br>';+            tableHtml += '<strong>Altri liquidi:</strong> ' + additionalFluids + ' ml (' + ((additionalFluids/currentWeight)*1000).toFixed(1) + ' ml/kg/die)<br>';
             tableHtml += '<strong>💧 TOTALE LIQUIDI:</strong> ' + totalFluids + ' ml (' + totalFluidsPerKg.toFixed(1) + ' ml/kg/die)';             tableHtml += '<strong>💧 TOTALE LIQUIDI:</strong> ' + totalFluids + ' ml (' + totalFluidsPerKg.toFixed(1) + ' ml/kg/die)';
         } else {         } else {
Linea 1476: Linea 2687:
     document.getElementById('enteralResults').classList.remove('hidden');     document.getElementById('enteralResults').classList.remove('hidden');
          
 +    // Aggiorna il pulsante a verde
     const enteralBtn = document.getElementById('calculateEnteralBtn');     const enteralBtn = document.getElementById('calculateEnteralBtn');
     if (enteralBtn) {     if (enteralBtn) {
Linea 1481: Linea 2693:
         enteralBtn.innerHTML = 'Apporti Enterali Calcolati ✓';         enteralBtn.innerHTML = 'Apporti Enterali Calcolati ✓';
     }     }
 +    
 +    // RESET del pulsante Fabbisogni quando si modificano gli apporti enterali
 +    resetNutritionButton();
 } }
  
-// FUNZIONE CARICAMENTO VALORI DEFAULT+// FUNZIONE CARICAMENTO VALORI STANDARD (DA VERSIONE 17)
 function loadNutritionDefaults() { function loadNutritionDefaults() {
-    if (!patientData.birthWeight) { +    // Controlla se i dati di base sono presenti 
-        alert('Prima inserire i dati del paziente nel TAB 1');+    const defaultsCurrentWeight = parseInt(document.getElementById('currentWeight').value); 
 +    const defaultsBirthWeight = parseInt(document.getElementById('birthWeight').value); 
 +    const defaultsDaysOfLife = parseInt(document.getElementById('daysOfLife').value); 
 +     
 +    if (!defaultsCurrentWeight || !defaultsBirthWeight || !defaultsDaysOfLife) { 
 +        alert('Prima inserire peso attuale, peso alla nascita e giorni di vita nel TAB 1');
         return;         return;
 +    }
 +    
 +    // Aggiorna patientData se non è stato ancora fatto
 +    if (!patientData.currentWeight) {
 +        patientData.currentWeight = defaultsCurrentWeight;
 +        patientData.birthWeight = defaultsBirthWeight;
 +        patientData.daysOfLife = defaultsDaysOfLife;
     }     }
          
     const targetDay = parseInt(document.getElementById('targetDay').value);     const targetDay = parseInt(document.getElementById('targetDay').value);
-    const birthWeight = patientData.birthWeight;+    const patientBirthWeightForCalculation = patientData.birthWeight;
          
     const weightCategorySelect = document.getElementById('weightCategory');     const weightCategorySelect = document.getElementById('weightCategory');
-    let selectedCategory = weightCategorySelect.value || (birthWeight <= 1500 ? '≤1500g' : '>1500g');+    let selectedCategory = weightCategorySelect.value || (patientBirthWeightForCalculation <= 1500 ? '≤1500g' : '>1500g');
     weightCategorySelect.value = selectedCategory;     weightCategorySelect.value = selectedCategory;
          
Linea 1520: Linea 2747:
     document.getElementById('reqCarbs').value = plan.carbs;     document.getElementById('reqCarbs').value = plan.carbs;
     document.getElementById('reqLipids').value = plan.lipids;     document.getElementById('reqLipids').value = plan.lipids;
-    document.getElementById('reqCalcium').value = targetDay > 3 ? 160 : 0; +     
-    document.getElementById('reqPhosphorus').value = targetDay > 3 ? 84 : 0; +    // Usa configurazione clinica per elettroliti 
-    document.getElementById('reqMagnesium').value = targetDay > 3 ? 0.: 0;+    document.getElementById('reqCalcium').value = targetDay > 3 ? clinicalConfig.calciumReq : 0; 
 +    document.getElementById('reqPhosphorus').value = targetDay > 3 ? clinicalConfig.phosphorusReq : 0; 
 +    document.getElementById('reqMagnesium').value = targetDay > 3 ? clinicalConfig.magnesiumReq : 0;
     document.getElementById('reqSodium').value = targetDay > 2 ? 2.0 : 0;     document.getElementById('reqSodium').value = targetDay > 2 ? 2.0 : 0;
     document.getElementById('reqPotassium').value = targetDay > 2 ? 1.5 : 0;     document.getElementById('reqPotassium').value = targetDay > 2 ? 1.5 : 0;
          
-    // Vitamine/oligoelementi +    // Gestione automatica tipo di sodio basata sui parametri clinici 
-    const currentWeight = patientData.currentWeight; +    const sodiumSelect = document.getElementById('sodiumType'); 
-    const enteralVolumePerKg = enteralData ? (enteralData.totalFluids / currentWeight * 1000) : 0;+    if (patientData.ph || patientData.baseExcess) { 
 +        const ph = patientData.ph ? parseFloat(patientData.ph) : null; 
 +        const be = patientData.baseExcess ? parseFloat(patientData.baseExcess) : null; 
 +         
 +        // Auto-seleziona Sodio Acetato se acidosi 
 +        if ((ph && ph < 7.30) || (be && be < -4)) { 
 +            sodiumSelect.value = 'sodium_acetate'; 
 +        } else { 
 +            sodiumSelect.value = 'nacl'; 
 +        } 
 +    } 
 +     
 +    // Aggiorna il suggerimento sodio 
 +    updateSodiumRecommendation(); 
 +     
 +    // Gestione vitamine/oligoelementi con controllo enterale 
 +    const patientCurrentWeight = patientData.currentWeight; 
 +    const enteralVolumePerKg = enteralData ? (enteralData.totalFluids / patientCurrentWeight * 1000) : 0;
          
     if (targetDay >= 3 && enteralVolumePerKg < 100) {     if (targetDay >= 3 && enteralVolumePerKg < 100) {
Linea 1535: Linea 2781:
         document.getElementById('reqPeditrace').value = 1.0;         document.getElementById('reqPeditrace').value = 1.0;
     } else {     } else {
 +        // Mantieni i valori a zero se prima del 3° giorno o se enterale ≥100 ml/kg/die
         document.getElementById('reqVitalipid').value = 0;         document.getElementById('reqVitalipid').value = 0;
         document.getElementById('reqSoluvit').value = 0;         document.getElementById('reqSoluvit').value = 0;
Linea 1540: Linea 2787:
     }     }
          
-    document.getElementById('reqCarnitine').value = 0;+    document.getElementById('reqCarnitine').value = 0; // La carnitina verrà gestita separatamente
          
-    const loadBtn = document.getElementById('loadDefaultsBtn')+    document.getElementById('loadDefaultsBtn').className = 'button load-defaults-completed'; 
-    if (loadBtn) { +    document.getElementById('loadDefaultsBtn').innerHTML = 'Valori Caricati ✓'; 
-        loadBtn.className = 'button load-defaults-completed'; +     
-        loadBtn.innerHTML = 'Valori Standard Caricati ✓'; +    // RESET del pulsante Fabbisogni quando si modificano i valori standard 
-    }+    resetNutritionButton();
 } }
  
 +// FUNZIONE AGGIORNAMENTO UNITÀ CARBOIDRATI
 function updateCarbUnit() { function updateCarbUnit() {
     const unit = document.getElementById('carbUnit').value;     const unit = document.getElementById('carbUnit').value;
Linea 1563: Linea 2811:
         carbInput.setAttribute('step', '0.1');         carbInput.setAttribute('step', '0.1');
     }     }
 +    
 +    // Reset fabbisogni quando si cambia unità
 +    resetNutritionButton();
 } }
  
 +// FUNZIONE AGGIORNAMENTO CATEGORIA PESO
 function updateWeightCategory() { function updateWeightCategory() {
-    // Placeholder+    // Reset fabbisogni quando si cambia categoria peso 
 +    resetNutritionButton();
 } }
  
 +// FUNZIONE AGGIORNAMENTO TIPO SODIO
 function updateSodiumChoice() { function updateSodiumChoice() {
-    // Placeholder+    // Resetta i fabbisogni quando si cambia il tipo di sodio 
 +    resetNutritionButton();
 } }
  
-// FUNZIONE CALCOLO FABBISOGNI+// FUNZIONE AGGIORNAMENTO SUGGERIMENTO SODIO 
 +function updateSodiumRecommendation() { 
 +    const sodiumSelect = document.getElementById('sodiumType'); 
 +    const recommendationDiv = document.getElementById('sodiumRecommendation'); 
 +     
 +    if (!patientData.ph && !patientData.baseExcess) { 
 +        // Nessun dato clinico disponibile 
 +        recommendationDiv.classList.add('hidden'); 
 +        return; 
 +    } 
 +     
 +    const ph = patientData.ph ? parseFloat(patientData.ph) : null; 
 +    const be = patientData.baseExcess ? parseFloat(patientData.baseExcess) : null; 
 +     
 +    // Logica di raccomandazione 
 +    let needsAcetate = false; 
 +    let reason = ''; 
 +     
 +    if (ph && ph < 7.30) { 
 +        needsAcetate = true; 
 +        reason = 'pH < 7.30 (acidosi)'; 
 +    } else if (be && be < -4) { 
 +        needsAcetate = true; 
 +        reason = 'BE < -4 mEq/L (acidosi metabolica)'; 
 +    } else if (ph && be && (ph < 7.30 || be < -4)) { 
 +        needsAcetate = true; 
 +        reason = 'pH < 7.30 o BE < -4 (acidosi)'; 
 +    } 
 +     
 +    if (needsAcetate) { 
 +        // Suggerisci Sodio Acetato 
 +        if (sodiumSelect.value === 'nacl') { 
 +            // L'utente ha selezionato NaCl ma dovrebbe usare Acetato 
 +            recommendationDiv.innerHTML = '<div class="warning" style="padding: 8px; font-size: 12px;">'
 +                '<strong>⚠️ RACCOMANDAZIONE CLINICA:</strong><br>'
 +                'In base ai parametri clinici (' + reason + '), si raccomanda <strong>Sodio Acetato</strong> invece di Sodio Cloruro per effetto alcalinizzante.'
 +                '</div>'; 
 +            recommendationDiv.classList.remove('hidden'); 
 +        } else { 
 +            // L'utente ha già selezionato Acetato - mostra conferma 
 +            recommendationDiv.innerHTML = '<div class="info" style="padding: 8px; font-size: 12px;">'
 +                '<strong>✅ SCELTA APPROPRIATA:</strong><br>'
 +                'Sodio Acetato è indicato per i parametri clinici attuali (' + reason + ').'
 +                '</div>'; 
 +            recommendationDiv.classList.remove('hidden'); 
 +        } 
 +    } else { 
 +        // Parametri normali 
 +        if (sodiumSelect.value === 'sodium_acetate') { 
 +            // L'utente ha selezionato Acetato ma i parametri sono normali 
 +            recommendationDiv.innerHTML = '<div class="info" style="padding: 8px; font-size: 12px;">'
 +                '<strong>ℹ️ NOTA:</strong><br>'
 +                'I parametri clinici sono nella norma. Sodio Cloruro potrebbe essere sufficiente, ma Sodio Acetato è comunque sicuro.'
 +                '</div>'; 
 +            recommendationDiv.classList.remove('hidden'); 
 +        } else { 
 +            // Tutto normale 
 +            recommendationDiv.classList.add('hidden'); 
 +        } 
 +    } 
 +
 + 
 +// FUNZIONE CALCOLO FABBISOGNI NUTRIZIONALI (DA VERSIONE 17)
 function calculateNutrition() { function calculateNutrition() {
-    if (!patientData.birthWeight) { +    // Controlla se i dati di base sono presenti 
-        alert('Prima inserire i dati del paziente nel TAB 1');+    const nutritionCurrentWeight = parseInt(document.getElementById('currentWeight').value); 
 +    const nutritionBirthWeight = parseInt(document.getElementById('birthWeight').value); 
 +     
 +    if (!nutritionCurrentWeight || !nutritionBirthWeight) { 
 +        alert('Prima inserire peso attuale e peso alla nascita nel TAB 1');
         return;         return;
 +    }
 +    
 +    // Aggiorna patientData se non è stato ancora fatto
 +    if (!patientData.currentWeight) {
 +        patientData.currentWeight = nutritionCurrentWeight;
 +        patientData.birthWeight = nutritionBirthWeight;
     }     }
          
Linea 1601: Linea 2928:
         (requirements.carbs * 1440 / 1000) : requirements.carbs;         (requirements.carbs * 1440 / 1000) : requirements.carbs;
          
-    const currentWeight = patientData.currentWeight;+    const patientCurrentWeight = patientData.currentWeight
 +    const enteralVolumePerKg = enteralData ? (enteralData.totalFluids / patientCurrentWeight * 1000) : 0;
          
     const enteralProtein = enteralData ? enteralData.protein : 0;     const enteralProtein = enteralData ? enteralData.protein : 0;
Linea 1674: Linea 3002:
     document.getElementById('calculateNutritionBtn').className = 'button calculate-nutrition-completed';     document.getElementById('calculateNutritionBtn').className = 'button calculate-nutrition-completed';
     document.getElementById('calculateNutritionBtn').innerHTML = 'FABBISOGNI CALCOLATI ✓';     document.getElementById('calculateNutritionBtn').innerHTML = 'FABBISOGNI CALCOLATI ✓';
 +    
 +    // RESET del pulsante NPT quando si modificano i fabbisogni
 +    resetParenteralButton();
 } }
  
-// FUNZIONE CALCOLO ELETTROLITI AGGIUNTIVI+// FUNZIONE CALCOLO ELETTROLITI AGGIUNTIVI (DA VERSIONE 17)
 function calculateElectrolyteAdditions(calciumNeeded, phosphorusNeeded, magnesiumNeeded, sodiumNeeded, potassiumNeeded, currentWeightKg) { function calculateElectrolyteAdditions(calciumNeeded, phosphorusNeeded, magnesiumNeeded, sodiumNeeded, potassiumNeeded, currentWeightKg) {
     const additions = {     const additions = {
Linea 1686: Linea 3017:
         kcl: 0,         kcl: 0,
         totalVolume: 0,         totalVolume: 0,
-        providedCalcium: 0, 
-        providedPhosphorus: 0, 
-        providedMagnesium: 0, 
-        providedSodium: 0, 
-        providedPotassium: 0, 
         sodiumSource: 'nacl'         sodiumSource: 'nacl'
     };     };
          
 +    // Determina il tipo di sodio da utilizzare
     const sodiumTypeSelect = document.getElementById('sodiumType');     const sodiumTypeSelect = document.getElementById('sodiumType');
     const selectedSodiumType = sodiumTypeSelect ? sodiumTypeSelect.value : 'nacl';     const selectedSodiumType = sodiumTypeSelect ? sodiumTypeSelect.value : 'nacl';
     additions.sodiumSource = selectedSodiumType;     additions.sodiumSource = selectedSodiumType;
          
-    const totalCalciumNeeded = calciumNeeded * currentWeightKg; +    // Calcola fabbisogni totali per paziente 
-    const totalPhosphorusNeeded = phosphorusNeeded * currentWeightKg; +    const totalCalciumNeeded = calciumNeeded * currentWeightKg; // mg 
-    const totalMagnesiumNeeded = magnesiumNeeded * currentWeightKg; +    const totalPhosphorusNeeded = phosphorusNeeded * currentWeightKg; // mg 
-    const totalSodiumNeeded = sodiumNeeded * currentWeightKg; +    const totalMagnesiumNeeded = magnesiumNeeded * currentWeightKg; // mEq 
-    const totalPotassiumNeeded = potassiumNeeded * currentWeightKg;+    const totalSodiumNeeded = sodiumNeeded * currentWeightKg; // mEq 
 +    const totalPotassiumNeeded = potassiumNeeded * currentWeightKg; // mEq
          
     // Calcio Gluconato 10% (840 mg Ca/100ml)     // Calcio Gluconato 10% (840 mg Ca/100ml)
     if (totalCalciumNeeded > 0) {     if (totalCalciumNeeded > 0) {
         additions.ca_gluconato = totalCalciumNeeded / (parenteralConfig.ca_gluconato.calcium / 100);         additions.ca_gluconato = totalCalciumNeeded / (parenteralConfig.ca_gluconato.calcium / 100);
-        additions.providedCalcium = totalCalciumNeeded; 
     }     }
          
     // Esafosfina (1600 mg P/100ml + 130 mEq Na/100ml)     // Esafosfina (1600 mg P/100ml + 130 mEq Na/100ml)
 +    let sodiumFromEsafosfina = 0;
     if (totalPhosphorusNeeded > 0) {     if (totalPhosphorusNeeded > 0) {
         additions.esafosfina = totalPhosphorusNeeded / (parenteralConfig.esafosfina.phosphorus / 100);         additions.esafosfina = totalPhosphorusNeeded / (parenteralConfig.esafosfina.phosphorus / 100);
-        additions.providedPhosphorus = totalPhosphorusNeeded; +        sodiumFromEsafosfina = (additions.esafosfina * parenteralConfig.esafosfina.sodium / 100);
-        additions.providedSodium += (additions.esafosfina * parenteralConfig.esafosfina.sodium / 100);+
     }     }
          
Linea 1720: Linea 3047:
     if (totalMagnesiumNeeded > 0) {     if (totalMagnesiumNeeded > 0) {
         additions.mg_sulfate = totalMagnesiumNeeded / (parenteralConfig.mg_sulfate.magnesium / 100);         additions.mg_sulfate = totalMagnesiumNeeded / (parenteralConfig.mg_sulfate.magnesium / 100);
-        additions.providedMagnesium = totalMagnesiumNeeded; 
     }     }
          
-    // Sodio rimanente +    // Sodio rimanente (dopo quello da Esafosfina) 
-    const remainingSodium = Math.max(0, totalSodiumNeeded - additions.providedSodium);+    const remainingSodium = Math.max(0, totalSodiumNeeded - sodiumFromEsafosfina);
          
     if (remainingSodium > 0) {     if (remainingSodium > 0) {
Linea 1734: Linea 3060:
             additions.nacl = remainingSodium / concentrationNaCl;             additions.nacl = remainingSodium / concentrationNaCl;
         }         }
-        additions.providedSodium += remainingSodium; 
     }     }
          
Linea 1740: Linea 3065:
     if (totalPotassiumNeeded > 0) {     if (totalPotassiumNeeded > 0) {
         additions.kcl = totalPotassiumNeeded / (parenteralConfig.kcl.potassium / 100);         additions.kcl = totalPotassiumNeeded / (parenteralConfig.kcl.potassium / 100);
-        additions.providedPotassium = totalPotassiumNeeded; 
     }     }
          
 +    // Volume totale degli elettroliti
     additions.totalVolume = additions.ca_gluconato + additions.esafosfina + additions.mg_sulfate + additions.nacl + additions.sodium_acetate + additions.kcl;     additions.totalVolume = additions.ca_gluconato + additions.esafosfina + additions.mg_sulfate + additions.nacl + additions.sodium_acetate + additions.kcl;
          
Linea 1748: Linea 3073:
 } }
  
-// FUNZIONE CALCOLO NPT PARENTERALE+ 
 +// FUNZIONE CALCOLO OSMOLARITÀ NPT (MIGLIORATA) 
 +function calculateNPTOsmolarity(calc, currentWeightKg, residualNeeds) { 
 +    let totalOsmolarity = 0; 
 +    let osmolarityBreakdown = {}; 
 +    let componentDetails = []; 
 +     
 +    // Glucosio 50% - osmolarità molto alta 
 +    if (calc.neededGlucose > 0) { 
 +        const glucoseOsmol = (calc.glucose50Volume * parenteralConfig.glucose50.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.glucose = glucoseOsmol; 
 +        totalOsmolarity += glucoseOsmol; 
 +        componentDetails.push({ 
 +            name: 'Glucosio 50%', 
 +            volume: calc.glucose50Volume, 
 +            concentration: parenteralConfig.glucose50.osmolarity, 
 +            contribution: glucoseOsmol 
 +        }); 
 +    } 
 +     
 +    // Trophamine 6% 
 +    const proteinOsmol = (calc.proteinVolume * parenteralConfig.trophamine.osmolarity) / calc.totalVolume; 
 +    osmolarityBreakdown.protein = proteinOsmol; 
 +    totalOsmolarity += proteinOsmol; 
 +    componentDetails.push({ 
 +        name: 'Trophamine 6%', 
 +        volume: calc.proteinVolume, 
 +        concentration: parenteralConfig.trophamine.osmolarity, 
 +        contribution: proteinOsmol 
 +    }); 
 +     
 +    // Intralipid 20% 
 +    const lipidOsmol = (calc.lipidVolume * parenteralConfig.intralipid.osmolarity) / calc.totalVolume; 
 +    osmolarityBreakdown.lipid = lipidOsmol; 
 +    totalOsmolarity += lipidOsmol; 
 +    componentDetails.push({ 
 +        name: 'Intralipid 20%', 
 +        volume: calc.lipidVolume, 
 +        concentration: parenteralConfig.intralipid.osmolarity, 
 +        contribution: lipidOsmol 
 +    }); 
 +     
 +    // Elettroliti 
 +    if (calc.electrolyteAdditions.ca_gluconato > 0) { 
 +        const caOsmol = (calc.electrolyteAdditions.ca_gluconato * parenteralConfig.ca_gluconato.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.calcium = caOsmol; 
 +        totalOsmolarity += caOsmol; 
 +        componentDetails.push({ 
 +            name: 'Calcio Gluconato 10%', 
 +            volume: calc.electrolyteAdditions.ca_gluconato, 
 +            concentration: parenteralConfig.ca_gluconato.osmolarity, 
 +            contribution: caOsmol 
 +        }); 
 +    } 
 +     
 +    if (calc.electrolyteAdditions.esafosfina > 0) { 
 +        const pOsmol = (calc.electrolyteAdditions.esafosfina * parenteralConfig.esafosfina.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.phosphorus = pOsmol; 
 +        totalOsmolarity += pOsmol; 
 +        componentDetails.push({ 
 +            name: 'Esafosfina', 
 +            volume: calc.electrolyteAdditions.esafosfina, 
 +            concentration: parenteralConfig.esafosfina.osmolarity, 
 +            contribution: pOsmol 
 +        }); 
 +    } 
 +     
 +    if (calc.electrolyteAdditions.mg_sulfate > 0) { 
 +        const mgOsmol = (calc.electrolyteAdditions.mg_sulfate * parenteralConfig.mg_sulfate.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.magnesium = mgOsmol; 
 +        totalOsmolarity += mgOsmol; 
 +        componentDetails.push({ 
 +            name: 'Magnesio Solfato', 
 +            volume: calc.electrolyteAdditions.mg_sulfate, 
 +            concentration: parenteralConfig.mg_sulfate.osmolarity, 
 +            contribution: mgOsmol 
 +        }); 
 +    } 
 +     
 +    if (calc.electrolyteAdditions.nacl > 0) { 
 +        const naclOsmol = (calc.electrolyteAdditions.nacl * parenteralConfig.nacl.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.nacl = naclOsmol; 
 +        totalOsmolarity += naclOsmol; 
 +        componentDetails.push({ 
 +            name: 'Sodio Cloruro', 
 +            volume: calc.electrolyteAdditions.nacl, 
 +            concentration: parenteralConfig.nacl.osmolarity, 
 +            contribution: naclOsmol 
 +        }); 
 +    } 
 +     
 +    if (calc.electrolyteAdditions.sodium_acetate > 0) { 
 +        const naAcetOsmol = (calc.electrolyteAdditions.sodium_acetate * parenteralConfig.sodium_acetate.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.sodium_acetate = naAcetOsmol; 
 +        totalOsmolarity += naAcetOsmol; 
 +        componentDetails.push({ 
 +            name: 'Sodio Acetato', 
 +            volume: calc.electrolyteAdditions.sodium_acetate, 
 +            concentration: parenteralConfig.sodium_acetate.osmolarity, 
 +            contribution: naAcetOsmol 
 +        }); 
 +    } 
 +     
 +    if (calc.electrolyteAdditions.kcl > 0) { 
 +        const kclOsmol = (calc.electrolyteAdditions.kcl * parenteralConfig.kcl.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.kcl = kclOsmol; 
 +        totalOsmolarity += kclOsmol; 
 +        componentDetails.push({ 
 +            name: 'Potassio Cloruro', 
 +            volume: calc.electrolyteAdditions.kcl, 
 +            concentration: parenteralConfig.kcl.osmolarity, 
 +            contribution: kclOsmol 
 +        }); 
 +    } 
 +     
 +    // Vitamine e Carnitina (osmolarità bassa) 
 +    let vitaminsOsmol = 0; 
 +    if (residualNeeds.vitalipid > 0) { 
 +        const vitalipidVolume = residualNeeds.vitalipid * currentWeightKg; 
 +        const vitOsmol = (vitalipidVolume * 280) / calc.totalVolume; 
 +        vitaminsOsmol += vitOsmol; 
 +        componentDetails.push({ 
 +            name: 'Vitalipid N Infant', 
 +            volume: vitalipidVolume, 
 +            concentration: 280, 
 +            contribution: vitOsmol 
 +        }); 
 +    } 
 +     
 +    if (residualNeeds.soluvit > 0) { 
 +        const soluvitVolume = residualNeeds.soluvit * currentWeightKg; 
 +        const solOsmol = (soluvitVolume * 300) / calc.totalVolume; 
 +        vitaminsOsmol += solOsmol; 
 +        componentDetails.push({ 
 +            name: 'Soluvit N', 
 +            volume: soluvitVolume, 
 +            concentration: 300, 
 +            contribution: solOsmol 
 +        }); 
 +    } 
 +     
 +    if (residualNeeds.peditrace > 0) { 
 +        const peditraceVolume = residualNeeds.peditrace * currentWeightKg; 
 +        const pedOsmol = (peditraceVolume * 350) / calc.totalVolume; 
 +        vitaminsOsmol += pedOsmol; 
 +        componentDetails.push({ 
 +            name: 'Peditrace', 
 +            volume: peditraceVolume, 
 +            concentration: 350, 
 +            contribution: pedOsmol 
 +        }); 
 +    } 
 +     
 +    if (vitaminsOsmol > 0) { 
 +        osmolarityBreakdown.vitamins = vitaminsOsmol; 
 +        totalOsmolarity += vitaminsOsmol; 
 +    } 
 +     
 +    if (residualNeeds.carnitine > 0) { 
 +        const carnitineVolume = (residualNeeds.carnitine * currentWeightKg) / 100; 
 +        const carOsmol = (carnitineVolume * parenteralConfig.carnitene.osmolarity) / calc.totalVolume; 
 +        osmolarityBreakdown.carnitine = carOsmol; 
 +        totalOsmolarity += carOsmol; 
 +        componentDetails.push({ 
 +            name: 'Carnitene', 
 +            volume: carnitineVolume, 
 +            concentration: parenteralConfig.carnitene.osmolarity, 
 +            contribution: carOsmol 
 +        }); 
 +    } 
 +     
 +    return { 
 +        total: Math.round(totalOsmolarity), 
 +        breakdown: osmolarityBreakdown, 
 +        details: componentDetails, 
 +        isHypertonic: totalOsmolarity > 900, 
 +        requiresCVC: totalOsmolarity > 600 
 +    }; 
 +
 + 
 +// FUNZIONE CALCOLO NPT PARENTERALE (DA VERSIONE 17 CON CONTROLLI CLINICI)
 function calculateParenteral() { function calculateParenteral() {
     if (!window.residualNeeds) {     if (!window.residualNeeds) {
Linea 1755: Linea 3260:
     }     }
          
-    const currentWeight = patientData.currentWeight; +    const parentCurrentWeight = patientData.currentWeight; 
-    const currentWeightKg = currentWeight / 1000;+    const currentWeightKg = parentCurrentWeight / 1000;
     const residualNeeds = window.residualNeeds;     const residualNeeds = window.residualNeeds;
          
 +    // CONTROLLI DI SICUREZZA BASATI SU CONFIGURAZIONE CLINICA
 +    const gir = (residualNeeds.carbs * 1000) / 1440; // mg/kg/min
 +    let alerts = [];
 +    
 +    if (gir > clinicalConfig.maxGIR) {
 +        alerts.push('⚠️ GIR > ' + clinicalConfig.maxGIR + ' mg/kg/min - Rischio iperglicemia');
 +    }
 +    if (residualNeeds.lipids > clinicalConfig.maxLipids) {
 +        alerts.push('⚠️ Lipidi > ' + clinicalConfig.maxLipids + ' g/kg/die - Monitorare trigliceridi');
 +    }
 +    if (residualNeeds.protein > clinicalConfig.maxProtein) {
 +        alerts.push('⚠️ Proteine > ' + clinicalConfig.maxProtein + ' g/kg/die - Monitorare BUN');
 +    }
 +    
 +    // Volume totale residuo richiesto
     const totalVolume = Math.round(residualNeeds.liquids * currentWeightKg);     const totalVolume = Math.round(residualNeeds.liquids * currentWeightKg);
          
 +    // CALCOLA ELETTROLITI AGGIUNTIVI
     const electrolyteAdditions = calculateElectrolyteAdditions(     const electrolyteAdditions = calculateElectrolyteAdditions(
         residualNeeds.calcium,         residualNeeds.calcium,
Linea 1770: Linea 3291:
     );     );
          
 +    // Volume proteine (Trophamine 6%)
     const proteinVolume = Math.round((residualNeeds.protein * currentWeightKg * 100) / 6);     const proteinVolume = Math.round((residualNeeds.protein * currentWeightKg * 100) / 6);
 +    
 +    // Volume lipidi (Intralipid 20%)
     const lipidVolume = Math.round((residualNeeds.lipids * currentWeightKg * 100) / 20);     const lipidVolume = Math.round((residualNeeds.lipids * currentWeightKg * 100) / 20);
          
 +    // Volume vitamine/oligoelementi/carnitina
     const vitaminsVolume = (residualNeeds.vitalipid * currentWeightKg) + (residualNeeds.soluvit * currentWeightKg) + (residualNeeds.peditrace * currentWeightKg);     const vitaminsVolume = (residualNeeds.vitalipid * currentWeightKg) + (residualNeeds.soluvit * currentWeightKg) + (residualNeeds.peditrace * currentWeightKg);
     const carnitineVolume = residualNeeds.carnitine > 0 ? (residualNeeds.carnitine * currentWeightKg) / 100 : 0;     const carnitineVolume = residualNeeds.carnitine > 0 ? (residualNeeds.carnitine * currentWeightKg) / 100 : 0;
          
-    const neededGlucose = residualNeeds.carbs * currentWeightKg; +    // CALCOLO CON GLUCOSIO 50% + ACQUA BIDISTILLATA 
-    const glucose50Volume = (neededGlucose * 100) / 50;+    const neededGlucose = residualNeeds.carbs * currentWeightKg; // grammi totali di glucosio 
 +    const glucose50Volume = (neededGlucose * 100) / 50; // ml di glucosio 50% necessari
          
 +    // Volume utilizzato
     const usedVolume = proteinVolume + lipidVolume + vitaminsVolume + carnitineVolume + glucose50Volume + electrolyteAdditions.totalVolume;     const usedVolume = proteinVolume + lipidVolume + vitaminsVolume + carnitineVolume + glucose50Volume + electrolyteAdditions.totalVolume;
 +    
 +    // Volume rimanente = Acqua Bidistillata
     const waterVolume = totalVolume - usedVolume;     const waterVolume = totalVolume - usedVolume;
-     
-    let glucoseMessage = ''; 
-     
-    if (waterVolume < 0) { 
-        glucoseMessage = '<div class="warning"><strong>ERRORE CALCOLO:</strong><br>' + 
-                        '• Volume totale richiesto: ' + totalVolume + ' ml<br>' + 
-                        '• Volume utilizzato: ' + usedVolume.toFixed(1) + ' ml<br>' + 
-                        '• Acqua rimanente: ' + waterVolume.toFixed(1) + ' ml (NEGATIVO!)<br><br>' + 
-                        '<strong>SOLUZIONE:</strong> Aumentare il volume totale NPT.</div>'; 
-         
-        document.getElementById('calculatedTotalVolume').value = totalVolume + ' ml (ERRORE)'; 
-        document.getElementById('suggestedGlucose').value = 'Errore - Volume insufficiente'; 
-        document.getElementById('calculatedProteinVol').value = proteinVolume + ' ml'; 
-        document.getElementById('calculatedLipidVol').value = lipidVolume + ' ml'; 
-         
-        document.getElementById('parenteralTable').innerHTML = glucoseMessage; 
-        document.getElementById('parenteralResults').classList.remove('hidden'); 
-        return; 
-    } 
-     
-    if (neededGlucose <= 0) { 
-        glucoseMessage = '<div class="info"><strong>GLUCOSIO DA ENTERALE:</strong><br>' + 
-                        '• Tutto il glucosio necessario proviene dall\'alimentazione enterale<br>' + 
-                        '• Non necessario glucosio in NPT</div>'; 
-         
-        document.getElementById('suggestedGlucose').value = 'Non necessario (enterale sufficiente)'; 
-    } else { 
-        glucoseMessage = '<div class="info"><strong>CALCOLO GLUCOSIO:</strong><br>' + 
-                        '• Glucosio necessario: ' + neededGlucose.toFixed(1) + 'g<br>' + 
-                        '• Glucosio 50%: ' + glucose50Volume.toFixed(1) + 'ml<br>' + 
-                        '• Acqua bidistillata: ' + waterVolume.toFixed(1) + 'ml<br>' + 
-                        '• <strong>Concentrazione finale: ' + ((neededGlucose * 100) / totalVolume).toFixed(1) + '%</strong></div>'; 
-         
-        document.getElementById('suggestedGlucose').value = 'Glucosio 50% + Acqua'; 
-    } 
          
     document.getElementById('calculatedTotalVolume').value = totalVolume + ' ml';     document.getElementById('calculatedTotalVolume').value = totalVolume + ' ml';
 +    document.getElementById('suggestedGlucose').value = 'Glucosio 50% + Acqua + Elettroliti';
     document.getElementById('calculatedProteinVol').value = proteinVolume + ' ml';     document.getElementById('calculatedProteinVol').value = proteinVolume + ' ml';
     document.getElementById('calculatedLipidVol').value = lipidVolume + ' ml';     document.getElementById('calculatedLipidVol').value = lipidVolume + ' ml';
          
-    let resultHtml = glucoseMessage;+    let resultHtml = '<div class="info">'; 
 +    resultHtml += '<strong>NPT v3.0 UNIFIED - SISTEMA COMPLETO CON CONTROLLI CLINICI</strong><br>'; 
 +    resultHtml += '<strong>Peso:</strong> ' + parentCurrentWeight + 'g<br>'; 
 +    resultHtml += '<strong>GIR:</strong> ' + gir.toFixed(1) + ' mg/kg/min<br>'; 
 +    resultHtml += '<strong>Enterale:</strong> ' + (enteralData ? enteralData.totalFluids : 0) + ' ml (' + (enteralData ? (enteralData.totalFluids/currentWeightKg).toFixed(1) : 0) + ' ml/kg/die)<br>'; 
 +    if (enteralData && enteralData.additionalFluids > 0) { 
 +        resultHtml += '<strong>→ Latte:</strong> ' + (enteralData.volume || 0) + ' ml, <strong>Altri liquidi:</strong> ' + enteralData.additionalFluids + ' ml<br>'; 
 +    } 
 +    resultHtml += '</div>';
          
-    resultHtml += '<div class="info">'; +    // MOSTRA ALERT CLINICI SE PRESENTI 
-    resultHtml += '<strong>NPT v2.0 - COMPOSIZIONE COMPLETA</strong><br>'; +    if (alerts.length > 0) { 
-    resultHtml += '<strong>Peso:</strong> ' + currentWeight + 'g<br>'; +        resultHtml += '<div class="alert-critical"><strong>ALERT CLINICI:</strong><br>'alerts.join('<br>'+ '</div>'; 
-    resultHtml += '<strong>Enterale:</strong> ' + (enteralData ? enteralData.totalFluids : 0) + ml<br>'+    }
-    resultHtml +'</div>';+
          
     resultHtml += '<table class="results-table">';     resultHtml += '<table class="results-table">';
Linea 1837: Linea 3339:
          
     resultHtml += '<tr><td><strong>Trophamine 6%</strong></td><td><strong>' + proteinVolume.toFixed(1) + '</strong></td></tr>';     resultHtml += '<tr><td><strong>Trophamine 6%</strong></td><td><strong>' + proteinVolume.toFixed(1) + '</strong></td></tr>';
-    resultHtml += '<tr><td><strong>Intralipid 20%</strong></td><td><strong>'Math.max(0, lipidVolume).toFixed(1) + '</strong></td></tr>';+    resultHtml += '<tr><td><strong>Intralipid 20%</strong></td><td><strong>' + lipidVolume.toFixed(1) + '</strong></td></tr>';
          
 +    // ELETTROLITI AGGIUNTIVI
     if (electrolyteAdditions.ca_gluconato > 0) {     if (electrolyteAdditions.ca_gluconato > 0) {
         resultHtml += '<tr><td><strong>Calcio Gluconato 10% (1g/10mL, 0.44 mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.ca_gluconato.toFixed(1) + '</strong></td></tr>';         resultHtml += '<tr><td><strong>Calcio Gluconato 10% (1g/10mL, 0.44 mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.ca_gluconato.toFixed(1) + '</strong></td></tr>';
Linea 1846: Linea 3349:
     }     }
     if (electrolyteAdditions.mg_sulfate > 0) {     if (electrolyteAdditions.mg_sulfate > 0) {
-        resultHtml += '<tr><td><strong>Magnesio Solfato (2g/10mL, 1.6 mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.mg_sulfate.toFixed(1) + '</strong></td></tr>';+        resultHtml += '<tr><td><strong>Magnesio Solfato (2g/10ml, 1.6 mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.mg_sulfate.toFixed(1) + '</strong></td></tr>';
     }     }
     if (electrolyteAdditions.nacl > 0) {     if (electrolyteAdditions.nacl > 0) {
Linea 1852: Linea 3355:
     }     }
     if (electrolyteAdditions.sodium_acetate > 0) {     if (electrolyteAdditions.sodium_acetate > 0) {
-        resultHtml += '<tr><td><strong>Sodio Acetato (mEq/mL) - Alcalinizzante</strong></td><td><strong>' + electrolyteAdditions.sodium_acetate.toFixed(1) + '</strong></td></tr>';+        resultHtml += '<tr><td><strong>Sodio Acetato (mEq/mL) - Alcalinizzante</strong></td><td><strong>' + electrolyteAdditions.sodium_acetate.toFixed(1) + '</strong></td></tr>';
     }     }
     if (electrolyteAdditions.kcl > 0) {     if (electrolyteAdditions.kcl > 0) {
         resultHtml += '<tr><td><strong>Potassio Cloruro (2 mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.kcl.toFixed(1) + '</strong></td></tr>';         resultHtml += '<tr><td><strong>Potassio Cloruro (2 mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.kcl.toFixed(1) + '</strong></td></tr>';
     }     }
-    +    
 +    // VITAMINE
     if (residualNeeds.vitalipid > 0) {     if (residualNeeds.vitalipid > 0) {
         const vitalipidVolume = residualNeeds.vitalipid * currentWeightKg;         const vitalipidVolume = residualNeeds.vitalipid * currentWeightKg;
Linea 1871: Linea 3375:
     }     }
          
 +    
 +    // CARNITINA
     if (residualNeeds.carnitine > 0) {     if (residualNeeds.carnitine > 0) {
-        resultHtml += '<tr><td><strong>Carnitene</strong></td><td><strong>' + carnitineVolume.toFixed(1) + '</strong></td></tr>';+        resultHtml += '<tr><td><strong>Carnitene (100 mg/ml)</strong></td><td><strong>' + carnitineVolume.toFixed(1) + '</strong></td></tr>';
     }     }
          
 +    // ACQUA BIDISTILLATA
     if (waterVolume > 0) {     if (waterVolume > 0) {
         resultHtml += '<tr><td><strong>Acqua Bidistillata</strong></td><td><strong>' + waterVolume.toFixed(1) + '</strong></td></tr>';         resultHtml += '<tr><td><strong>Acqua Bidistillata</strong></td><td><strong>' + waterVolume.toFixed(1) + '</strong></td></tr>';
Linea 1884: Linea 3391:
     document.getElementById('parenteralTable').innerHTML = resultHtml;     document.getElementById('parenteralTable').innerHTML = resultHtml;
          
-    // PREPARAZIONE CON DEFLUSSORE+    // CALCOLO OSMOLARITÀ 
 +const osmolarityData = calculateNPTOsmolarity({ 
 +    totalVolume: totalVolume, 
 +    waterVolume: waterVolume, 
 +    glucose50Volume: glucose50Volume, 
 +    proteinVolume: proteinVolume, 
 +    lipidVolume: lipidVolume, 
 +    electrolyteAdditions: electrolyteAdditions 
 +}, currentWeightKg, residualNeeds); 
 + 
 +// AGGIUNGI SEZIONE OSMOLARITÀ 
 +let osmolarityHtml = '<div style="margin-top: 20px; padding: 15px; border-radius: 8px; background-color: '; 
 +if (osmolarityData.isHypertonic) { 
 +    osmolarityHtml += '#ffebee; border-left: 4px solid #f44336;'; 
 +} else if (osmolarityData.requiresCVC) { 
 +    osmolarityHtml += '#fff3e0; border-left: 4px solid #ff9800;'; 
 +} else { 
 +    osmolarityHtml += '#e8f5e8; border-left: 4px solid #4caf50;'; 
 +
 +osmolarityHtml += '">'; 
 +osmolarityHtml += '<h4 style="margin-top: 0; color: #2c3e50;">📊 ANALISI OSMOLARITÀ NPT</h4>'; 
 +osmolarityHtml += '<div style="display: flex; flex-wrap: wrap; gap: 20px;">'; 
 +osmolarityHtml += '<div>'; 
 +osmolarityHtml += '<p><strong>Osmolarità totale:</strong> ' + osmolarityData.total + ' mOsm/L</p>'; 
 + 
 +if (osmolarityData.isHypertonic) { 
 +    osmolarityHtml += '<p style="color: #d32f2f; font-weight: bold;"><strong>⚠️ SOLUZIONE IPERTONICA</strong><br>Richiede OBBLIGATORIAMENTE accesso venoso centrale</p>'; 
 +} else if (osmolarityData.requiresCVC) { 
 +    osmolarityHtml += '<p style="color: #f57c00; font-weight: bold;"><strong>⚠️ OSMOLARITÀ ELEVATA</strong><br>Raccomandato accesso venoso centrale</p>'; 
 +} else { 
 +    osmolarityHtml += '<p style="color: #388e3c; font-weight: bold;"><strong>✅ OSMOLARITÀ NORMALE</strong><br>Compatibile con accesso periferico</p>'; 
 +
 + 
 +osmolarityHtml += '</div>'; 
 +osmolarityHtml += '<div>'; 
 +osmolarityHtml += '<p><strong>Contributi principali:</strong></p>'; 
 +osmolarityData.details.forEach(function(detail) { 
 +    if (detail.contribution > 30) { // Mostra contributi > 30 mOsm/L 
 +        osmolarityHtml += '<p style="font-size: 13px;">• ' + detail.name + ': ' + Math.round(detail.contribution) + ' mOsm/L</p>'; 
 +    } 
 +}); 
 +osmolarityHtml += '</div>'; 
 +osmolarityHtml += '</div>'; 
 +osmolarityHtml += '</div>'; 
 + 
 +document.getElementById('parenteralTable').innerHTML += osmolarityHtml; 
 + 
 +    // CREAZIONE RICETTA PER PREPARAZIONE
     const deflectorVolume = parseInt(document.getElementById('deflectorVolume').value) || 30;     const deflectorVolume = parseInt(document.getElementById('deflectorVolume').value) || 30;
     const totalVolumeWithDeflector = totalVolume + deflectorVolume;     const totalVolumeWithDeflector = totalVolume + deflectorVolume;
 +    const ratio = totalVolumeWithDeflector / totalVolume;
          
     let preparationHtml = '<div class="info">';     let preparationHtml = '<div class="info">';
-    preparationHtml += '<strong>📋 RICETTA PREPARAZIONE (Deflussore: ' + deflectorVolume + ' ml)</strong><br>';+    preparationHtml += '<strong>📋 RICETTA PER PREPARAZIONE (Volume deflussore: ' + deflectorVolume + ' ml)</strong><br>';
     preparationHtml += '• <strong>Volume prescrizione:</strong> ' + totalVolume + ' ml<br>';     preparationHtml += '• <strong>Volume prescrizione:</strong> ' + totalVolume + ' ml<br>';
 +    preparationHtml += '• <strong>Volume deflussore:</strong> +' + deflectorVolume + ' ml<br>';
     preparationHtml += '• <strong>Volume totale preparazione:</strong> ' + totalVolumeWithDeflector + ' ml';     preparationHtml += '• <strong>Volume totale preparazione:</strong> ' + totalVolumeWithDeflector + ' ml';
     preparationHtml += '</div>';     preparationHtml += '</div>';
          
     preparationHtml += '<table class="results-table">';     preparationHtml += '<table class="results-table">';
-    preparationHtml += '<tr><th>Componente</th><th>Prescrizione (ml)</th><th>Preparazione (ml)</th></tr>'+    preparationHtml += '<tr><th>Componente</th><th>Volume Prescrizione (ml)</th><th>Volume Preparazione (ml)</th></tr>';
-     +
-    const ratio = totalVolumeWithDeflector / totalVolume;+
          
     if (neededGlucose > 0) {     if (neededGlucose > 0) {
Linea 1904: Linea 3458:
          
     preparationHtml += '<tr><td><strong>Trophamine 6%</strong></td><td>' + proteinVolume.toFixed(1) + '</td><td><strong>' + (proteinVolume * ratio).toFixed(1) + '</strong></td></tr>';     preparationHtml += '<tr><td><strong>Trophamine 6%</strong></td><td>' + proteinVolume.toFixed(1) + '</td><td><strong>' + (proteinVolume * ratio).toFixed(1) + '</strong></td></tr>';
-    preparationHtml += '<tr><td><strong>Intralipid 20%</strong></td><td>'Math.max(0, lipidVolume).toFixed(1) + '</td><td><strong>' + (Math.max(0, lipidVolume* ratio).toFixed(1) + '</strong></td></tr>';+    preparationHtml += '<tr><td><strong>Intralipid 20%</strong></td><td>' + lipidVolume.toFixed(1) + '</td><td><strong>' + (lipidVolume * ratio).toFixed(1) + '</strong></td></tr>';
          
     if (electrolyteAdditions.ca_gluconato > 0) {     if (electrolyteAdditions.ca_gluconato > 0) {
Linea 1913: Linea 3467:
     }     }
     if (electrolyteAdditions.mg_sulfate > 0) {     if (electrolyteAdditions.mg_sulfate > 0) {
-        preparationHtml += '<tr><td><strong>Magnesio Solfato (2g/10mL, 1.6 mEq/mL)</strong></td><td>' + electrolyteAdditions.mg_sulfate.toFixed(1) + '</td><td><strong>' + (electrolyteAdditions.mg_sulfate * ratio).toFixed(1) + '</strong></td></tr>';+        preparationHtml += '<tr><td><strong>Magnesio Solfato (2g/10ml, 1.6 mEq/mL)</strong></td><td>' + electrolyteAdditions.mg_sulfate.toFixed(1) + '</td><td><strong>' + (electrolyteAdditions.mg_sulfate * ratio).toFixed(1) + '</strong></td></tr>';
     }     }
     if (electrolyteAdditions.nacl > 0) {     if (electrolyteAdditions.nacl > 0) {
Linea 1919: Linea 3473:
     }     }
     if (electrolyteAdditions.sodium_acetate > 0) {     if (electrolyteAdditions.sodium_acetate > 0) {
-        preparationHtml += '<tr><td><strong>Sodio Acetato (mEq/mL) - Alcalinizzante</strong></td><td>' + electrolyteAdditions.sodium_acetate.toFixed(1) + '</td><td><strong>' + (electrolyteAdditions.sodium_acetate * ratio).toFixed(1) + '</strong></td></tr>';+        preparationHtml += '<tr><td><strong>Sodio Acetato (mEq/mL) - Alcalinizzante</strong></td><td>' + electrolyteAdditions.sodium_acetate.toFixed(1) + '</td><td><strong>' + (electrolyteAdditions.sodium_acetate * ratio).toFixed(1) + '</strong></td></tr>';
     }     }
     if (electrolyteAdditions.kcl > 0) {     if (electrolyteAdditions.kcl > 0) {
Linea 1925: Linea 3479:
     }     }
          
 +    // VITAMINE con denominazioni complete
     if (residualNeeds.vitalipid > 0) {     if (residualNeeds.vitalipid > 0) {
         const vitalipidVolume = residualNeeds.vitalipid * currentWeightKg;         const vitalipidVolume = residualNeeds.vitalipid * currentWeightKg;
Linea 1938: Linea 3493:
     }     }
          
 +    // CARNITINA con denominazione completa
     if (residualNeeds.carnitine > 0) {     if (residualNeeds.carnitine > 0) {
         preparationHtml += '<tr><td><strong>Carnitene (100 mg/ml)</strong></td><td>' + carnitineVolume.toFixed(1) + '</td><td><strong>' + (carnitineVolume * ratio).toFixed(1) + '</strong></td></tr>';         preparationHtml += '<tr><td><strong>Carnitene (100 mg/ml)</strong></td><td>' + carnitineVolume.toFixed(1) + '</td><td><strong>' + (carnitineVolume * ratio).toFixed(1) + '</strong></td></tr>';
Linea 1947: Linea 3503:
          
     preparationHtml += '<tr class="energy-highlight"><td><strong>TOTALE</strong></td><td><strong>' + totalVolume + ' ml</strong></td><td><strong>' + totalVolumeWithDeflector + ' ml</strong></td></tr>';     preparationHtml += '<tr class="energy-highlight"><td><strong>TOTALE</strong></td><td><strong>' + totalVolume + ' ml</strong></td><td><strong>' + totalVolumeWithDeflector + ' ml</strong></td></tr>';
 +    preparationHtml += '<tr style="background-color: #e3f2fd;"><td><strong>Osmolarità Finale</strong></td><td><strong>' + osmolarityData.total + ' mOsm/L</strong></td><td><strong>-</strong></td></tr>';
 +    preparationHtml += '<tr><td><strong>Velocità infusione</strong></td><td><strong>' + (totalVolume / 24).toFixed(2) + ' ml/h</strong></td><td><strong>-</strong></td></tr>';
 +
 +// Aggiungi avvertenze osmolarità nella tabella di preparazione
 +if (osmolarityData.isHypertonic) {
 +    preparationHtml += '<tr style="background-color: #ffebee; color: #d32f2f; font-weight: bold;"><td colspan="3"><strong>⚠️ OSMOLARITÀ IPERTONICA (' + osmolarityData.total + ' mOsm/L) - SOLO ACCESSO VENOSO CENTRALE</strong></td></tr>';
 +} else if (osmolarityData.requiresCVC) {
 +    preparationHtml += '<tr style="background-color: #fff3e0; color: #f57c00; font-weight: bold;"><td colspan="3"><strong>⚠️ OSMOLARITÀ ELEVATA (' + osmolarityData.total + ' mOsm/L) - RACCOMANDATO ACCESSO VENOSO CENTRALE</strong></td></tr>';
 +} else {
 +    preparationHtml += '<tr style="background-color: #e8f5e8; color: #2e7d32;"><td colspan="3"><strong>✅ OSMOLARITÀ NORMALE (' + osmolarityData.total + ' mOsm/L) - COMPATIBILE CON ACCESSO PERIFERICO</strong></td></tr>';
 +}
     preparationHtml += '</table>';     preparationHtml += '</table>';
          
Linea 1952: Linea 3519:
     document.getElementById('parenteralResults').classList.remove('hidden');     document.getElementById('parenteralResults').classList.remove('hidden');
          
-    // Salva i dati per report +    document.getElementById('calculateParenteralBtn').className = 'button config-update-completed'; 
-    window.nptCalculationData = { +    document.getElementById('calculateParenteralBtn').innerHTML = 'NPT CALCOLATA ✓'; 
-        currentWeight, currentWeightKg, totalVolume, electrolyteAdditions+     
-        proteinVolume, lipidVolume, vitaminsVolumecarnitineVolume+    // Salva i dati per il report 
-        glucose50VolumewaterVolumeneededGlucoseresidualNeeds+    window.nptCalculation = { 
 +        totalVolume: totalVolume, 
 +        waterVolume: waterVolume, 
 +        glucose50Volume: glucose50Volume
 +        proteinVolume: proteinVolume, 
 +        lipidVolume: lipidVolume, 
 +        gir: gir, 
 +        neededGlucose: neededGlucose
 +        electrolyteAdditions: electrolyteAdditions, 
 +        vitaminsVolume: vitaminsVolume, 
 +        carnitineVolume: carnitineVolume, 
 +        deflectorVolume: deflectorVolume, 
 +        osmolarityData: osmolarityData
     };     };
 +}
 +
 +// FUNZIONI CONFIGURAZIONE (DA VERSIONE 17)
 +function populateEnteralConfigTable() {
 +    const tbody = document.getElementById('enteralConfigTable');
 +    if (!tbody) return;
          
-    const parenteralBtn document.getElementById('calculateParenteralBtn')+    tbody.innerHTML = ''; 
-    if (parenteralBtn) { +    Object.keys(formulaData).forEach(key => 
-        parenteralBtn.className = 'button config-update-completed'; +        const formula = formulaData[key]; 
-        parenteralBtn.innerHTML = 'NPT CALCOLATA ✓'; +        const row = tbody.insertRow(); 
-    }+        row.innerHTML = '<td class="component-name">+ formula.name + '</td>' + 
 +            '<td><input type="number" id="config_' + key + '_protein" value="' + formula.protein + '" step="0.1" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_carbs" value="' + formula.carbs + '" step="0.1" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_lipids" value="' + formula.lipids + '" step="0.1" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_sodium" value="' + formula.sodium + '" step="0.001" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_potassium" value="' + formula.potassium + '" step="0.001" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_calcium" value="' + formula.calcium + '" step="0.1" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_phosphorus" value="' + formula.phosphorus + '" step="0.1" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_magnesium" value="' + formula.magnesium + '" step="0.1" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_energy" value="' + formula.energy + '" step="1" oninput="markConfigChanged(\'enteral\')"></td>'
 +            '<td><button class="button secondary" onclick="removeEnteralFormula(\'' + key + '\')" style="padding: 5px 10px; font-size: 12px;">Rimuovi</button></td>'; 
 +    });
 } }
  
-// FUNZIONI REPORT +function populateParenteralConfigTable() { 
-function generateAndShowWorkReport() { +    const tbody = document.getElementById('parenteralConfigTable'); 
-    if (!window.nptCalculationData) { +    if (!tbody) return;
-        alert('Prima calcolare la NPT!'); +
-        return; +
-    }+
          
-    const reportHtml generateWorkReportHTML(); +    tbody.innerHTML = ''; 
-    document.getElementById('nptWorkReport').innerHTML reportHtml; +    Object.keys(parenteralConfig).forEach(function(key) { 
-    document.getElementById('nptWorkReport').classList.remove('hidden'); +        const component parenteralConfig[key]; 
-    document.getElementById('nptFinalReport').classList.add('hidden'); +        const row = tbody.insertRow(); 
-    document.getElementById('printReportBtn').classList.remove('hidden'); +        row.innerHTML = '<td class="component-name">' + component.name + '</td>'
-    document.getElementById('savePdfBtn').classList.remove('hidden'); +            '<td><input type="number" id="config_' + key + '_protein" value="' + component.protein + '" step="0.1" oninput="markConfigChanged(\'parenteral\')"></td>'
-    window.currentActiveReport = 'work';+            '<td><input type="number" id="config_' + key + '_carbs" value="' + component.carbs + '" step="0.1" oninput="markConfigChanged(\'parenteral\')"></td>' + 
 +            '<td><input type="number" id="config_' + key + '_lipids" value="' + component.lipids + '" step="0.1" oninput="markConfigChanged(\'parenteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_sodium" value="' + component.sodium + '" step="0.1" oninput="markConfigChanged(\'parenteral\')"></td>' + 
 +            '<td><input type="number" id="config_' + key + '_potassium" value="' + component.potassium + '" step="0.1" oninput="markConfigChanged(\'parenteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_calcium" value="' + component.calcium + '" step="1" oninput="markConfigChanged(\'parenteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_phosphorus" value="' + component.phosphorus + '" step="1" oninput="markConfigChanged(\'parenteral\')"></td>' + 
 +            '<td><input type="number" id="config_' + key + '_magnesium" value="' + component.magnesium + '" step="0.1" oninput="markConfigChanged(\'parenteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_energy" value="' + component.energy + '" step="1" oninput="markConfigChanged(\'parenteral\')"></td>'
 +            '<td><input type="number" id="config_' + key + '_water" value="' + component.water + '" step="1" oninput="markConfigChanged(\'parenteral\')"></td>' + 
 +            '<td><input type="number" id="config_' + key + '_osmolarity" value="' + (component.osmolarity || 0) + '" step="10" oninput="markConfigChanged(\'parenteral\')" style="background-color: #e8f5e8;"></td>'
 +            '<td style="font-size: 11px; color: #7f8c8d; max-width: 200px;">' + (component.description || 'Componente') + '<br><em>' + (component.notes || 'Note') + '</em></td>'
 +            '<td><button class="button secondary" onclick="removeParenteralComponent(\'' + key + '\')" style="padding: 5px 10px; font-size: 12px;">Rimuovi</button></td>'
 +    }); 
 +
 + 
 +function populateDoctorsConfigTable() { 
 +    const tbody document.getElementById('doctorsConfigTable'); 
 +    if (!tbody) return;
          
-    const generateBtn document.getElementById('generateWorkReportBtn'); +    tbody.innerHTML = ''; 
-    generateBtn.innerHTML = 'Foglio di Lavoro Generato ✓'; +    Object.keys(doctorsData).forEach(key => { 
-    generateBtn.className = 'button config-update-completed';+        const doctor = doctorsData[key]; 
 +        const row tbody.insertRow(); 
 +        row.innerHTML = '<td><input type="text" id="doctor_+ key + '_name" value="' + doctor.name + '" style="width: 100px;" oninput="markConfigChanged(\'doctors\')"></td>' + 
 +            '<td><input type="text" id="doctor_' + key + '_surname" value="' + doctor.surname + '" style="width: 100px;" oninput="markConfigChanged(\'doctors\')"></td>'
 +            '<td><select id="doctor_' + key + '_title" style="width: 70px;" oninput="markConfigChanged(\'doctors\')">'
 +                '<option value="Dr."' + (doctor.title === 'Dr.' ? ' selected' : '') + '>Dr.</option>'
 +                '<option value="Dr.ssa"' + (doctor.title === 'Dr.ssa' ? ' selected' : '') + '>Dr.ssa</option>'
 +                '<option value="Prof."' + (doctor.title === 'Prof.' ? ' selected' : '') + '>Prof.</option>'
 +                '<option value="Prof.ssa"' + (doctor.title === 'Prof.ssa' ? ' selected' : '') + '>Prof.ssa</option>'
 +            '</select></td>'
 +            '<td style="font-weight: bold; color: #2c3e50;">' + doctor.fullName + '</td>'
 +            '<td><button class="button secondary" onclick="removeDoctor(\'' + key + '\')" style="padding: 5px 10px; font-size: 12px;">Rimuovi</button></td>'
 +    });
 } }
  
-function generateAndShowFinalReport() { +function populateNursesConfigTable() { 
-    if (!window.nptCalculationData) { +    const tbody = document.getElementById('nursesConfigTable'); 
-        alert('Prima calcolare la NPT!'); +    if (!tbody) return;
-        return; +
-    }+
          
-    const reportHtml generateFinalReportHTML()+    tbody.innerHTML ''
-    document.getElementById('nptFinalReport').innerHTML reportHtml+    Object.keys(nursesData).forEach(key => { 
-    document.getElementById('nptFinalReport').classList.remove('hidden'); +        const nurse nursesData[key]
-    document.getElementById('nptWorkReport').classList.add('hidden'); +        const row = tbody.insertRow(); 
-    document.getElementById('printReportBtn').classList.remove('hidden'); +        row.innerHTML = '<td><input type="text" id="nurse_+ key + '_name" value="' + nurse.name + '" style="width: 100px;" oninput="markConfigChanged(\'nurses\')"></td>' + 
-    document.getElementById('savePdfBtn').classList.remove('hidden'); +            '<td><input type="text" id="nurse_' + key + '_surname" value="' + nurse.surname + '" style="width: 100px;" oninput="markConfigChanged(\'nurses\')"></td>'
-    window.currentActiveReport = 'final';+            '<td><select id="nurse_' + key + '_title" style="width: 70px;" oninput="markConfigChanged(\'nurses\')">' + 
 +                '<option value="Inf."'(nurse.title === 'Inf.' ? ' selected'''+ '>Inf.</option>'
 +                '<option value="InfCoord."'(nurse.title === 'Inf. Coord.' ? ' selected'''+ '>Inf. Coord.</option>' + 
 +                '<option value="InfSpec."'(nurse.title === 'Inf. Spec.' ? ' selected'''+ '>InfSpec.</option>'
 +            '</select></td>'
 +            '<td style="font-weight: bold; color: #2c3e50;">' + nurse.fullName + '</td>'
 +            '<td><button class="button secondary" onclick="removeNurse(\'' + key + '\')" style="padding: 5px 10px; font-size: 12px;">Rimuovi</button></td>'
 +    }); 
 +
 + 
 +function populatePharmacistsConfigTable() { 
 +    const tbody document.getElementById('pharmacistsConfigTable'); 
 +    if (!tbody) return;
          
-    const generateBtn document.getElementById('generateFinalReportBtn'); +    tbody.innerHTML = ''; 
-    generateBtn.innerHTML = 'Report Parenterale Generato ✓'; +    Object.keys(pharmacistsData).forEach(key => { 
-    generateBtn.className = 'button config-update-completed';+        const pharmacist = pharmacistsData[key]; 
 +        const row tbody.insertRow(); 
 +        row.innerHTML = '<td><input type="text" id="pharmacist_+ key + '_name" value="' + pharmacist.name + '" style="width: 100px;" oninput="markConfigChanged(\'pharmacists\')"></td>' + 
 +            '<td><input type="text" id="pharmacist_' + key + '_surname" value="' + pharmacist.surname + '" style="width: 100px;" oninput="markConfigChanged(\'pharmacists\')"></td>'
 +            '<td><select id="pharmacist_' + key + '_title" style="width: 90px;" oninput="markConfigChanged(\'pharmacists\')">'
 +                '<option value="Dr. Farm."' + (pharmacist.title === 'Dr. Farm.' ? ' selected' : '') + '>Dr. Farm.</option>'
 +                '<option value="Dr.ssa Farm."' + (pharmacist.title === 'Dr.ssa Farm.' ? ' selected' : '') + '>Dr.ssa Farm.</option>'
 +                '<option value="Farm."' + (pharmacist.title === 'Farm.' ? ' selected' : '') + '>Farm.</option>'
 +            '</select></td>'
 +            '<td style="font-weight: bold; color: #2c3e50;">' + pharmacist.fullName + '</td>'
 +            '<td><button class="button secondary" onclick="removePharmacist(\'' + key + '\')" style="padding: 5px 10px; font-size: 12px;">Rimuovi</button></td>'
 +    });
 } }
  
-function generateWorkReportHTML() { +function populateTechniciansConfigTable() { 
-    const data window.nptCalculationData; +    const tbody = document.getElementById('techniciansConfigTable'); 
-    const deflectorVolume = parseInt(document.getElementById('deflectorVolume').value) || 30+    if (!tbody) return;
-    const totalVolumeWithDeflector = data.totalVolume + deflectorVolume; +
-    const ratio = totalVolumeWithDeflector / data.totalVolume;+
          
-    const today new Date(); +    tbody.innerHTML ''; 
-    const dateStr today.toLocaleDateString('it-IT');+    Object.keys(technicianData).forEach(key => { 
 +        const technician = technicianData[key]
 +        const row tbody.insertRow(); 
 +        row.innerHTML = '<td><input type="text" id="technician_' + key + '_name" value="' + technician.name + '" style="width: 100px;" oninput="markConfigChanged(\'technicians\')"></td>'
 +            '<td><input type="text" id="technician_' + key + '_surname" value="' + technician.surname + '" style="width: 100px;" oninput="markConfigChanged(\'technicians\')"></td>'
 +            '<td><select id="technician_' + key + '_title" style="width: 70px;" oninput="markConfigChanged(\'technicians\')">'
 +                '<option value="Tec."' + (technician.title === 'Tec.' ? ' selected' : '') + '>Tec.</option>'
 +                '<option value="Tec. Spec."' + (technician.title === 'Tec. Spec.' ? ' selected' : '') + '>Tec. Spec.</option>'
 +                '<option value="Coord. Tec."' + (technician.title === 'Coord. Tec.' ? ' selected' : '') + '>Coord. Tec.</option>'
 +            '</select></td>'
 +            '<td style="font-weight: bold; color: #2c3e50;">' + technician.fullName + '</td>'
 +            '<td><button class="button secondary" onclick="removeTechnician(\'' + key + '\')" style="padding: 5px 10px; font-size: 12px;">Rimuovi</button></td>'; 
 +    }); 
 +
 + 
 +function markConfigChanged(configType) { 
 +    let buttonId = ''; 
 +    let buttonText = '';
          
-    const doctorName patientData.prescribingDoctor ?  +    switch(configType) { 
-        doctorsData[patientData.prescribingDoctor]?.fullName || 'N/A' : 'N/A';+        case 'enteral': 
 +            buttonId 'updateEnteralBtn'; 
 +            buttonText = 'SALVA MODIFICHE ENTERALI'; 
 +            break; 
 +        case 'parenteral': 
 +            buttonId = 'updateParenteralBtn'; 
 +            buttonText = 'SALVA MODIFICHE PARENTERALI'; 
 +            break; 
 +        case 'fortifier': 
 +            buttonId = 'updateFortifierBtn'; 
 +            buttonText = 'SALVA MODIFICHE FORTIFICANTI'; 
 +            break; 
 +        case 'doctors': 
 +            buttonId = 'updateDoctorsBtn'; 
 +            buttonText = 'SALVA MODIFICHE MEDICI'; 
 +            break; 
 +        case 'nurses': 
 +            buttonId = 'updateNursesBtn'; 
 +            buttonText = 'SALVA MODIFICHE INFERMIERE'; 
 +            break; 
 +        case 'pharmacists': 
 +            buttonId = 'updatePharmacistsBtn'; 
 +            buttonText = 'SALVA MODIFICHE FARMACISTI'; 
 +            break; 
 +        case 'technicians': 
 +            buttonId = 'updateTechniciansBtn'; 
 +            buttonText = 'SALVA MODIFICHE TECNICI'; 
 +            break; 
 +        case 'system': 
 +            buttonId = 'updateSystemBtn'; 
 +            buttonText = 'SALVA PARAMETRI SISTEMA'; 
 +            break; 
 +    }
          
-    const infusionRate (data.totalVolume / 24).toFixed(2); +    const button document.getElementById(buttonId); 
-    const finalConcentration = data.neededGlucose > 0 ? (data.neededGlucose * 100/ data.totalVolume : 0+    if (button
-    const estimatedOsmolarity = (finalConcentration * 55).toFixed(0);+        button.className = 'button config-update-pending'
 +        button.innerHTML buttonText; 
 +    } 
 +
 + 
 + 
 +function updateEnteralConfig() {  
 +    let changesCount = 0;
          
-    let html = '<div class="npt-report">';+    Object.keys(formulaData).forEach(key => { 
 +        const oldValues = Object.assign({}, formulaData[key]); 
 +         
 +        const proteinEl = document.getElementById('config_' + key + '_protein'); 
 +        if (proteinEl) { 
 +            formulaData[key].protein parseFloat(proteinEl.value); 
 +            formulaData[key].carbs = parseFloat(document.getElementById('config_' + key + '_carbs').value); 
 +            formulaData[key].lipids = parseFloat(document.getElementById('config_' + key + '_lipids').value); 
 +            formulaData[key].sodium = parseFloat(document.getElementById('config_' + key + '_sodium').value); 
 +            formulaData[key].potassium = parseFloat(document.getElementById('config_' + key + '_potassium').value); 
 +            formulaData[key].calcium = parseFloat(document.getElementById('config_' + key + '_calcium').value); 
 +            formulaData[key].phosphorus = parseFloat(document.getElementById('config_' + key + '_phosphorus').value); 
 +            formulaData[key].magnesium = parseFloat(document.getElementById('config_' + key + '_magnesium').value); 
 +            formulaData[key].energy = parseFloat(document.getElementById('config_' + key + '_energy').value); 
 +             
 +            if (JSON.stringify(oldValues) !== JSON.stringify(formulaData[key])) { 
 +                changesCount++; 
 +            } 
 +        } 
 +    });
          
-    // Header +    const button document.getElementById('updateEnteralBtn')
-    html += '<div class="report-header">'; +    if (button) { 
-    html += '<div class="report-header-left">'; +        button.className = 'button config-update-completed'; 
-    html += '<div style="font-weight: bold; font-size: 13px;">CALCOLO NUTRIZIONALE PARENTERALE Data: ' + dateStr + '</div>'; +        button.innerHTML = 'ENTERALI SALVATE ✓ (' + changesCount + ' modifiche)'; 
-    html +'<div style="font-size: 11px; color: #666;">FOGLIO DI LAVORO</div>'; +        setTimeout(() => { 
-    html += '</div>'; +            button.className = 'button'; 
-    html += '<div class="report-header-right">LOGO OSPEDALE</div>'; +            button.innerHTML = 'Aggiorna Formule Enterali'
-    html +'</div>';+        }, 3000)
 +    
 +
 + 
 +function updateParenteralConfig() {  
 +    let changesCount 0;
          
-    // Info Paziente +    Object.keys(parenteralConfig).forEach(function(key) { 
-    html +'<div class="report-section">'+        const oldValues Object.assign({}, parenteralConfig[key])
-    html += '<div class="report-section-title">INFO Paziente</div>'; +         
-    html +'<table class="report-table">'; +        const proteinEl document.getElementById('config_+ key + '_protein')
-    html += '<tr><td class="label-col">Medico Prescrittore</td><td class="value-col">' + doctorName + '</td></tr>'; +        if (proteinEl) { 
-    html += '<tr><td class="label-col">Data Prescrizione</td><td class="value-col">' + dateStr + '</td></tr>'; +            parenteralConfig[key].protein parseFloat(proteinEl.value); 
-    html += '<tr><td class="label-col">Paziente</td><td class="value-col">' + (patientData.medicalRecord || 'N/A'+ '</td></tr>'; +            parenteralConfig[key].carbs parseFloat(document.getElementById('config_' + key + '_carbs').value)
-    html += '<tr><td class="label-col">Giorni di Vita</td><td class="value-col">' + patientData.daysOfLife + '</td></tr>'; +            parenteralConfig[key].lipids parseFloat(document.getElementById('config_' + key + '_lipids').value)
-    html +'<tr><td class="label-col">Peso (g)</td><td class="value-col">' + data.currentWeight + '</td></tr>'; +            parenteralConfig[key].sodium parseFloat(document.getElementById('config_' + key + '_sodium').value)
-    html += '</table>'; +            parenteralConfig[key].potassium parseFloat(document.getElementById('config_' + key + '_potassium').value); 
-    html += '</div>';+            parenteralConfig[key].calcium = parseFloat(document.getElementById('config_+ key + '_calcium').value)
 +            parenteralConfig[key].phosphorus parseFloat(document.getElementById('config_' + key + '_phosphorus').value)
 +            parenteralConfig[key].magnesium parseFloat(document.getElementById('config_' + key + '_magnesium').value); 
 +            parenteralConfig[key].energy = parseFloat(document.getElementById('config_' + key + '_energy').value)
 +            parenteralConfig[key].water parseFloat(document.getElementById('config_+ key + '_water').value)
 +            parenteralConfig[key].osmolarity parseFloat(document.getElementById('config_+ key + '_osmolarity').value); 
 +             
 +            if (JSON.stringify(oldValues) !== JSON.stringify(parenteralConfig[key])) { 
 +                changesCount++; 
 +            } 
 +        } 
 +    });
          
-    // Composizione +    const button document.getElementById('updateParenteralBtn')
-    html += '<div class="report-section">'; +    if (button) { 
-    html += '<div class="report-section-title">Composizione Parenterale (numero sacche: 1)</div>'; +        button.className = 'button config-update-completed'; 
-    html += '<table class="composition-table">'+        button.innerHTML = 'PARENTERALI SALVATE ✓ (' + changesCount + modifiche)'; 
-    html +'<tr><th class="component-name-col"></th><th>Teorici</th><th>Con Deflussore</th><th></th></tr>'; +        setTimeout(() => { 
-     +            button.className = 'button'
-    if (data.waterVolume 0) +            button.innerHTML = 'Aggiorna Componenti Parenterali'
-        html += '<tr><td class="component-name-col">Acqua bidistillata</td><td>+ data.waterVolume.toFixed(2) + '</td><td>+ (data.waterVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+        }, 3000);
     }     }
-    if (data.glucose50Volume > 0) { +
-        html += '<tr><td class="component-name-col">glucosata 50% (parenterale)</td><td>+ data.glucose50Volume.toFixed(2'</td><td>(data.glucose50Volume * ratio).toFixed(2'</td><td>ml</td></tr>';+ 
 +function updateFortifierConfig() {  
 +    // Aggiorna Prenidina FM85 predefinita 
 +    const proteinEl = document.getElementById('fortifier_prenidina_fm85_protein'); 
 +    if (proteinEl) { 
 +        fortifierData.prenidina_fm85.protein parseFloat(proteinEl.value); 
 +        fortifierData.prenidina_fm85.carbs = parseFloat(document.getElementById('fortifier_prenidina_fm85_carbs').value); 
 +        fortifierData.prenidina_fm85.lipids parseFloat(document.getElementById('fortifier_prenidina_fm85_lipids').value); 
 +        fortifierData.prenidina_fm85.sodium = parseFloat(document.getElementById('fortifier_prenidina_fm85_sodium').value); 
 +        fortifierData.prenidina_fm85.potassium = parseFloat(document.getElementById('fortifier_prenidina_fm85_potassium').value); 
 +        fortifierData.prenidina_fm85.calcium = parseFloat(document.getElementById('fortifier_prenidina_fm85_calcium').value); 
 +        fortifierData.prenidina_fm85.phosphorus = parseFloat(document.getElementById('fortifier_prenidina_fm85_phosphorus').value); 
 +        fortifierData.prenidina_fm85.magnesium = parseFloat(document.getElementById('fortifier_prenidina_fm85_magnesium').value); 
 +        fortifierData.prenidina_fm85.energy = parseFloat(document.getElementById('fortifier_prenidina_fm85_energy').value);
     }     }
-    if (data.electrolyteAdditions.ca_gluconato > 0) { +     
-        html += '<tr><td class="component-name-col">Calcio gluconato (1g/10mL,0,44mEq/mL)</td><td>+ data.electrolyteAdditions.ca_gluconato.toFixed(2) + '</td><td>(data.electrolyteAdditions.ca_gluconato * ratio).toFixed(2+ '</td><td>ml</td></tr>';+    const button = document.getElementById('updateFortifierBtn'); 
 +    if (button) { 
 +        button.className = 'button config-update-completed'
 +        button.innerHTML = 'FORTIFICANTI SALVATE ✓'
 +        setTimeout(() =
 +            button.className = 'button'; 
 +            button.innerHTML = 'Aggiorna Fortificanti'; 
 +        }, 3000);
     }     }
-    if (data.electrolyteAdditions.nacl 0) +
-        html += '<tr><td class="component-name-col">Sodio cloruro (3mEq/mL)</td><td>' + data.electrolyteAdditions.nacl.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.nacl * ratio).toFixed(2) + '</td><td>ml</td></tr>';+ 
 +function updateDoctorsConfig() { 
 +    let changesCount = 0; 
 +     
 +    Object.keys(doctorsData).forEach(key => { 
 +        const oldValues Object.assign({}, doctorsData[key]); 
 +         
 +        const nameEl = document.getElementById('doctor_' + key + '_name'); 
 +        if (nameEl) { 
 +            const newName nameEl.value.trim()
 +            const newSurname = document.getElementById('doctor_' + key + '_surname').value.trim(); 
 +            const newTitle = document.getElementById('doctor_' + key + '_title').value; 
 +             
 +            doctorsData[key].name = newName; 
 +            doctorsData[key].surname = newSurname; 
 +            doctorsData[key].title = newTitle; 
 +            doctorsData[key].fullName = newTitle + ' ' + newName + ' ' + newSurname; 
 +             
 +            if (JSON.stringify(oldValues) !== JSON.stringify(doctorsData[key])) { 
 +                changesCount++; 
 +            } 
 +        } 
 +    }); 
 +     
 +    updateDoctorsDropdown(); 
 +    populateDoctorsConfigTable(); 
 +     
 +    const button = document.getElementById('updateDoctorsBtn')
 +    if (button) { 
 +        button.className = 'button config-update-completed'; 
 +        button.innerHTML = 'MEDICI SALVATI ✓ (' + changesCount + ' modifiche)'; 
 +        setTimeout(() =
 +            button.className = 'button'; 
 +            button.innerHTML = 'Aggiorna Lista Medici'; 
 +        }, 3000);
     }     }
-    if (data.electrolyteAdditions.sodium_acetate 0) +
-        html += '<tr><td class="component-name-col">Sodio acetato (2mEq/mL)</td><td>' + data.electrolyteAdditions.sodium_acetate.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.sodium_acetate * ratio).toFixed(2) + '</td><td>ml</td></tr>';+ 
 +function updateNursesConfig() { 
 +    let changesCount = 0; 
 +     
 +    Object.keys(nursesData).forEach(key => { 
 +        const oldValues Object.assign({}, nursesData[key]); 
 +         
 +        const nameEl = document.getElementById('nurse_' + key + '_name'); 
 +        if (nameEl) { 
 +            const newName nameEl.value.trim()
 +            const newSurname = document.getElementById('nurse_' + key + '_surname').value.trim(); 
 +            const newTitle = document.getElementById('nurse_' + key + '_title').value; 
 +             
 +            nursesData[key].name = newName; 
 +            nursesData[key].surname = newSurname; 
 +            nursesData[key].title = newTitle; 
 +            nursesData[key].fullName = newTitle + ' ' + newName + ' ' + newSurname; 
 +             
 +            if (JSON.stringify(oldValues) !== JSON.stringify(nursesData[key])) { 
 +                changesCount++; 
 +            } 
 +        } 
 +    }); 
 +     
 +    populateNursesConfigTable(); 
 +     
 +    const button = document.getElementById('updateNursesBtn')
 +    if (button) { 
 +        button.className = 'button config-update-completed'; 
 +        button.innerHTML = 'INFERMIERE SALVATE ✓ (' + changesCount + ' modifiche)'; 
 +        setTimeout(() =
 +            button.className = 'button'; 
 +            button.innerHTML = 'Aggiorna Lista Infermiere'; 
 +        }, 3000);
     }     }
-    if (data.electrolyteAdditions.kcl 0) +
-        html +'<tr><td class="component-name-col">Potassio cloruro (2mEq/mL)</td><td>' + data.electrolyteAdditions.kcl.toFixed(2'</td><td>' + (data.electrolyteAdditions.kcl * ratio).toFixed(2) + '</td><td>ml</td></tr>'; + 
-    } +function updatePharmacistsConfig() { 
-    if (data.electrolyteAdditions.mg_sulfate > 0) { +    let changesCount = 0; 
-        html +'<tr><td class="component-name-col">Magnesio solfato (2g/10mL,1.6mEq/mL)</td><td>' + data.electrolyteAdditions.mg_sulfate.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.mg_sulfate * ratio).toFixed(2) + '</td><td>ml</td></tr>'+     
-    } +    Object.keys(pharmacistsData).forEach(key => { 
-    if (data.carnitineVolume > 0) { +        const oldValues Object.assign({}, pharmacistsData[key])
-        html += '<tr><td class="component-name-col">Carnitene f</td><td>+ data.carnitineVolume.toFixed(2) + '</td><td>(data.carnitineVolume * ratio).toFixed(2+ '</td><td>ml</td></tr>';+         
 +        const nameEl = document.getElementById('pharmacist_' + key + '_name'); 
 +        if (nameEl) { 
 +            const newName = nameEl.value.trim()
 +            const newSurname = document.getElementById('pharmacist_' + key + '_surname').value.trim()
 +            const newTitle = document.getElementById('pharmacist_' + key + '_title').value
 +             
 +            pharmacistsData[key].name = newName; 
 +            pharmacistsData[key].surname = newSurname; 
 +            pharmacistsData[key].title newTitle; 
 +            pharmacistsData[key].fullName = newTitle + ' ' + newName + ' ' + newSurname; 
 +             
 +            if (JSON.stringify(oldValues!== JSON.stringify(pharmacistsData[key])) { 
 +                changesCount++; 
 +            } 
 +        } 
 +    }); 
 +     
 +    populatePharmacistsConfigTable(); 
 +     
 +    const button = document.getElementById('updatePharmacistsBtn'); 
 +    if (button) { 
 +        button.className = 'button config-update-completed'
 +        button.innerHTML = 'FARMACISTI SALVATI ✓ (' + changesCount + ' modifiche)'
 +        setTimeout(() =
 +            button.className = 'button'; 
 +            button.innerHTML = 'Aggiorna Lista Farmacisti'; 
 +        }, 3000);
     }     }
 +}
 +
 +function updateTechniciansConfig() {
 +    let changesCount = 0;
          
-    html +'<tr><td class="component-name-col">Trophamine 6%</td><td>' + data.proteinVolume.toFixed(2'</td><td>' + (data.proteinVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    Object.keys(technicianData).forEach(key => 
 +        const oldValues Object.assign({}, technicianData[key]); 
 +         
 +        const nameEl = document.getElementById('technician_' + key + '_name'); 
 +        if (nameEl) { 
 +            const newName = nameEl.value.trim()
 +            const newSurname = document.getElementById('technician_' + key + '_surname').value.trim()
 +            const newTitle = document.getElementById('technician_' + key + '_title').value; 
 +             
 +            technicianData[key].name = newName; 
 +            technicianData[key].surname = newSurname; 
 +            technicianData[key].title = newTitle; 
 +            technicianData[key].fullName = newTitle + ' ' + newName + ' ' + newSurname; 
 +             
 +            if (JSON.stringify(oldValues) !== JSON.stringify(technicianData[key])) { 
 +                changesCount++; 
 +            } 
 +        } 
 +    });
          
-    if (data.electrolyteAdditions.esafosfina > 0) { +    populateTechniciansConfigTable(); 
-        html += '<tr><td class="component-name-col">Esafosfina f 5g</td><td>+ data.electrolyteAdditions.esafosfina.toFixed(2) + '</td><td>(data.electrolyteAdditions.esafosfina * ratio).toFixed(2+ '</td><td>ml</td></tr>';+     
 +    const button = document.getElementById('updateTechniciansBtn'); 
 +    if (button) { 
 +        button.className = 'button config-update-completed'
 +        button.innerHTML = 'TECNICI SALVATI ✓ (' + changesCount + ' modifiche)'
 +        setTimeout(() =
 +            button.className = 'button'; 
 +            button.innerHTML = 'Aggiorna Lista Tecnici'; 
 +        }, 3000);
     }     }
-    if (data.residualNeeds.peditrace > 0) { +
-        const peditraceVolume data.residualNeeds.peditrace * data.currentWeightKg; + 
-        html += '<tr><td class="component-name-col">Peditrace</td><td>' + peditraceVolume.toFixed(2) + '</td><td>+ (peditraceVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +function updateSystemConfig() { 
-    } +    const button document.getElementById('updateSystemBtn'); 
-    if (data.residualNeeds.soluvit > 0) { +    if (button) { 
-        const soluvitVolume = data.residualNeeds.soluvit * data.currentWeightKg; +        button.className = 'button config-update-completed'
-        html += '<tr><td class="component-name-col">Soluvit</td><td>+ soluvitVolume.toFixed(2) + '</td><td>(soluvitVolume * ratio).toFixed(2+ '</td><td>ml</td></tr>'; +        button.innerHTML = 'PARAMETRI SALVATI ✓'
-    } +        setTimeout(() => { 
-    if (data.residualNeeds.vitalipid > 0) +            button.className = 'button'
-        const vitalipidVolume = data.residualNeeds.vitalipid * data.currentWeightKg; +            button.innerHTML = 'Aggiorna Parametri Sistema'
-        html += '<tr><td class="component-name-col">Vitalipid N</td><td>+ vitalipidVolume.toFixed(2) + '</td><td>+ (vitalipidVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+        }, 3000);
     }     }
          
-    html += '<tr><td class="component-name-col">Intralipid 20%</td><td>+ Math.max(0, data.lipidVolume).toFixed(2'</td><td>(Math.max(0, data.lipidVolume) * ratio).toFixed(2'</td><td>ml</td></tr>';+    resetParenteralButton(); 
 +
 + 
 +// FUNZIONI CONFIGURAZIONE CLINICA AVANZATA (NUOVE) 
 +function updateClinicalConfig() { 
 +    clinicalConfig.calciumReq parseFloat(document.getElementById('calciumReq').value); 
 +    clinicalConfig.phosphorusReq = parseFloat(document.getElementById('phosphorusReq').value)
 +    clinicalConfig.magnesiumReq = parseFloat(document.getElementById('magnesiumReq').value); 
 +    clinicalConfig.maxGIR = parseFloat(document.getElementById('maxGIR').value)
 +    clinicalConfig.maxLipids = parseFloat(document.getElementById('maxLipids').value); 
 +    clinicalConfig.maxProtein = parseFloat(document.getElementById('maxProtein').value);
          
-    // Totali +    alert('Parametri clinici aggiornati:\n' + 
-    html += '<tr class="composition-total"><td class="component-name-col"><strong>Totale</strong></td><td><strong>' + data.totalVolume.toFixed(2) + '</strong></td><td><strong>' + totalVolumeWithDeflector.toFixed(2) + '</strong></td><td><strong>ml</strong></td></tr>'; +          '• Calcio standard: ' + clinicalConfig.calciumReq + ' mg/kg/die\n' + 
-    html += '<tr><td class="component-name-col"><strong>Deflussore</strong></td><td><strong>' + deflectorVolume + '</strong></td><td><strong>-</strong></td><td><strong>ml</strong></td></tr>'+          '• Fosforo standard: ' + clinicalConfig.phosphorusReq + ' mg/kg/die\n+ 
-    html +'<tr><td class="component-name-col"><strong>Velocità infusione</strong></td><td><strong>' + infusionRate + '</strong></td><td><strong>-</strong></td><td><strong>ml/h</strong></td></tr>'; +          '• GIR massimo: ' + clinicalConfig.maxGIR + ' mg/kg/min\n' + 
-    html += '<tr><td class="component-name-col"><strong>Osmolarità Totale</strong></td><td><strong>+ estimatedOsmolarity + '</strong></td><td><strong>-</strong></td><td><strong>mOsm/ml</strong></td></tr>'; +          '• Lipidi massimi: ' + clinicalConfig.maxLipids + ' g/kg/die'); 
-    html += '</table>'; +
-    html += '</div>';+ 
 +function resetConfiguration() { 
 +    // Reset configurazione clinica 
 +    document.getElementById('calciumReq').value = 160; 
 +    document.getElementById('phosphorusReq').value = 84
 +    document.getElementById('magnesiumReq').value 0.6; 
 +    document.getElementById('maxGIR').value = 12.0
 +    document.getElementById('maxLipids').value 3.0; 
 +    document.getElementById('maxProtein').value = 4.5;
          
-    html += '<div class="report-footer">'+    // Reset configurazione sistema 
-    html += 'NPT Calculator v2.0 - Foglio di Lavoro generato il ' + new Date().toLocaleString('it-IT'); +    document.getElementById('deflectorVolume').value 30; 
-    html += '</div>';+    document.getElementById('hospitalName').value = "ASST LECCO"; 
 +    document.getElementById('departmentName').value = "S.C. Neonatologia e TIN"
 +    document.getElementById('directorName').value = "Dott. Roberto Bellù";
          
-    html += '</div>';+    // Reset configurazione clinica globale 
 +    clinicalConfig = { 
 +        calciumReq: 160, 
 +        phosphorusReq: 84, 
 +        magnesiumReq: 0.6, 
 +        maxGIR: 12.0, 
 +        maxLipids: 3.0, 
 +        maxProtein: 4.5, 
 +        hospitalName: "ASST LECCO", 
 +        departmentName: "S.C. Neonatologia e TIN", 
 +        directorName: "Dott. Roberto Bellù" 
 +    };
          
-    return html;+    alert('Configurazione ripristinata ai valori predefiniti');
 } }
  
-function generateFinalReportHTML() { +function saveConfiguration() { 
-    const data window.nptCalculationData; +    const config { 
-    const deflectorVolume = parseInt(document.getElementById('deflectorVolume').value) || 30; +        deflectorVolumedocument.getElementById('deflectorVolume').value
-    const totalVolumeWithDeflector = data.totalVolume + deflectorVolume; +        hospitalName: document.getElementById('hospitalName').value, 
-    const ratio = totalVolumeWithDeflector / data.totalVolume;+        departmentName: document.getElementById('departmentName').value, 
 +        directorName: document.getElementById('directorName').value, 
 +        autoSave: document.getElementById('autoSave').value, 
 +        decimalPlaces: document.getElementById('decimalPlaces').value, 
 +        clinicalConfig: clinicalConfig, 
 +        doctorsData: doctorsData, 
 +        nursesData: nursesData, 
 +        pharmacistsData: pharmacistsData, 
 +        technicianData: technicianData 
 +    };
          
-    const today new Date()+    // Aggiorna configurazione clinica 
-    const dateStr today.toLocaleDateString('it-IT');+    clinicalConfig.hospitalName config.hospitalName
 +    clinicalConfig.departmentName = config.departmentName; 
 +    clinicalConfig.directorName config.directorName;
          
-    const medicalRecord = patientData.medicalRecord || 'N/A'; +    // Simula salvataggio configurazione 
-    const birthDate patientData.prescriptionDate ?  +    window.savedConfig config; 
-        new Date(new Date(patientData.prescriptionDate).getTime() - (patientData.daysOfLife * 24 * 60 * 60 * 1000)).toLocaleDateString('it-IT') :  +    alert('Configurazione salvata con successo!\n\n'
-        'N/A'; +          'Inclusi:\n'
-    const doctorName = patientData.prescribingDoctor ?  +          '• ' + Object.keys(doctorsData).length + ' medici\n'
-        doctorsData[patientData.prescribingDoctor]?.fullName || 'N/A' : 'N/A';+          '• ' + Object.keys(nursesData).length + ' infermiere\n'
 +          '• ' + Object.keys(pharmacistsData).length + farmacisti\n+ 
 +          '• + Object.keys(technicianData).length + ' tecnici di farmacia'); 
 +
 + 
 +function generatePrescription() { 
 +    if (!window.residualNeeds || !patientData.currentWeight) { 
 +        alert('Prima completare tutti i calcoli precedenti'); 
 +        return; 
 +    }
          
-    const infusionRate = (data.totalVolume / 24).toFixed(2); +    const currentDate new Date().toLocaleDateString('it-IT'); 
-    const finalConcentration data.neededGlucose > 0 ? (data.neededGlucose * 100) data.totalVolume : 0+    const currentTime new Date().toLocaleTimeString('it-IT'); 
-    const estimatedOsmolarity (finalConcentration * 55 + data.electrolyteAdditions.totalVolume * 10).toFixed(0);+    const prescriptionPatientWeightKg = patientData.currentWeight 1000
 +    const calc window.nptCalculation;
          
-    let html = '<div class="npt-report">';+    if (!calc) { 
 +        alert('Prima calcolare la NPT nel TAB 4'); 
 +        return; 
 +    } 
 +     
 +    const birthDate = new Date(); 
 +    birthDate.setDate(birthDate.getDate() - patientData.daysOfLife); 
 +     
 +        // Genera ID prescrizione univoco (una sola volta per sessione) 
 +    if (!window.currentPrescriptionID) { 
 +        window.currentPrescriptionID = generatePreparationID(); 
 +    } 
 +    const prescriptionID = window.currentPrescriptionID; 
 +     
 +    // Recupera il medico attualmente selezionato 
 +    const currentPrescribingDoctor = document.getElementById('prescribingDoctor').value; 
 +    const doctorName = currentPrescribingDoctor && doctorsData[currentPrescribingDoctor] ?  
 +                  doctorsData[currentPrescribingDoctor].fullName :  
 +                  (patientData.prescribingDoctorName || 'Non specificato'); 
 +     
 +    let html = '<div class="report-output">'; 
 +     
 +    // INTESTAZIONE MEDICA (già OK secondo le tue indicazioni) 
 +    html += '<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #2c3e50; padding-bottom: 15px; margin-bottom: 25px;">';
          
-    // INTESTAZIONE +    // PARTE SINISTRA INFO OSPEDALE 
-    html += '<div class="report-header">'; +    html += '<div style="text-align: left;">'; 
-    html += '<div class="report-header-left">'; +    html += '<h2 style="margin0; font-size: 16px; color: #2c3e50;">Dipartimento Area della Donna e Materno Infantile</h2>'; 
-    html += '<div style="font-weightbold; font-size: 13px;">Dipartimento Area della Donna e Materno Infantile</div>'; +    html += '<h3 style="margin: 5px 0; font-size: 14px; color: #34495e;">S.C. Neonatologia e Terapia Intensiva Neonatale</h3>'; 
-    html += '<div style="font-size: 11px; color: #666;">S.C. Neonatologia e Terapia Intensiva Neonatale</div>';+    html += '<p style="margin: 5px 0; font-size: 12px; color: #7f8c8d;">Direttore: ' + clinicalConfig.directorName + '</p>';
     html += '</div>';     html += '</div>';
-    html += '<div class="report-header-right">LOGO OSPEDALE</div>';+     
 +    // PARTE DESTRA - LOGO ASST 
 +    html += '<div style="text-align: right;">'; 
 +    html += '<h1 style="margin: 0; font-size: 24px; color: #2c3e50; font-weight: bold;">' + clinicalConfig.hospitalName + '</h1>';
     html += '</div>';     html += '</div>';
          
-    html += '<div class="report-title">CALCOLO NUTRIZIONALE PARENTERALE Data: ' + dateStr + '</div>'; +    html += '</div>';
-    html += '<div class="report-subtitle">REPORT PARENTERALE</div>';+
          
-    // INFO PAZIENTE +    // TITOLO DOCUMENTO 
-    html += '<div class="report-section">'; +    html += '<div style="text-align: centermargin: 20px 0;">'; 
-    html += '<div class="report-section-title">INFO Paziente</div>'; +    html += '<h2 style="font-size: 18pxfont-weight: boldcolor: #2c3e50margin: 10px 0;">CALCOLO NUTRIZIONALE PARENTERALE Data' + currentDate + '</h2>'; 
-    html += '<table class="report-table">'; +    html += '<h3 style="font-size: 16px; color: #2c3e50; margin: 10px 0;">REPORT PARENTERALE</h3>';
-    html += '<tr><td class="label-col">Medico Prescrittore</td><td class="value-col">' + doctorName + '</td></tr>'; +
-    html += '<tr><td class="label-col">Data Prescrizione</td><td class="value-col">' + dateStr + '</td></tr>'; +
-    html += '<tr><td class="label-col">Data Somministrazione</td><td class="value-col">' + dateStr + '</td></tr>'; +
-    html += '<tr><td class="label-col">Paziente</td><td class="value-col">' + medicalRecord + '</td></tr>'; +
-    html += '<tr><td class="label-col">Data di Nascita</td><td class="value-col">' + birthDate + '</td></tr>'; +
-    html += '<tr><td class="label-col">Giorni di Vita</td><td class="value-col">' + patientData.daysOfLife + '</td></tr>'; +
-    html += '<tr><td class="label-col">Peso (g)</td><td class="value-col">' + data.currentWeight + '</td></tr>'; +
-    html += '</table>';+
     html += '</div>';     html += '</div>';
          
-    // LISTA APPORTI ENTERALI +    // INFO PAZIENTE (con cartella clinica e ID prescrizione) 
-    html += '<div class="report-section">'; +    html += '<div style="border: 2px solid #000; margin: 15px 0;">'; 
-    html += '<div class="report-section-title">Lista Degli Apporti per la Giornata Corrente</div>'; +    html += '<div style="background-color: #000; color: white; padding: 5px; font-weight: bold; font-size: 12px;">INFO Paziente</div>'; 
-    if (enteralData && enteralData.volume > 0) { +    html += '<table style="width: 100%; font-size: 11px; border-collapse: collapse;">'; 
-        const formulaName = document.getElementById('formulaType').value; +    html += '<tr><td style="padding3px; width: 200px;">Medico Prescrittore</td><td style="padding3px;">' + doctorName + '</td></tr>'; 
-        const formulaDisplayName = formulaData[formulaName]?.name || 'Formula enterale'; +    html += '<tr><td style="padding: 3px;">Data Prescrizione</td><td style="padding3px;">'(patientData.prescriptionDate || currentDate) + '</td></tr>'; 
-        html += '<table class="report-table">'; +    html += '<tr><td style="padding3px;">Data Somministrazione</td><td style="padding: 3px;">' + currentDate + '</td></tr>'; 
-        html += '<tr><td class="label-col">Apporto</td><td style="text-aligncenter; width: 60px;"><strong>Quant.</strong></td><td style="text-alignleft;"><strong>Somministrazione</strong></td></tr>'; +    html += '<tr><td style="padding3px;">ID Paziente</td><td style="padding3px;">' + (patientData.medicalRecord || 'N/A') + '</td></tr>'; 
-        html += '<tr><td class="label-col">' + formulaDisplayName + '</td><td style="text-aligncenter;">'enteralData.volume + '</td><td style="text-alignleft;">oro-naso-gastrica intermittente</td></tr>'+    if (prescriptionID) { 
-        html +'</table>'; +        html += '<tr><td style="padding: 3px;">ID Prescrizione</td><td style="padding3px;"><strong>' + prescriptionID + '</strong></td></tr>';
-    } else { +
-        html += '<table class="report-table">'; +
-        html += '<tr><td class="label-col">Apporto</td><td style="text-aligncenter; width: 60px;"><strong>Quant.</strong></td><td style="text-alignleft;"><strong>Somministrazione</strong></td></tr>'; +
-        html += '<tr><td class="label-col">Nessun apporto enterale</td><td style="text-aligncenter;">-</td><td style="text-align: left;">-</td></tr>'; +
-        html += '</table>';+
     }     }
 +    
 +    
 +    html += '<tr><td style="padding: 3px;">Data di Nascita</td><td style="padding: 3px;">' + birthDate.toLocaleDateString('it-IT') + '</td></tr>';
 +        html += '<tr><td style="padding: 3px;">Giorni di Vita</td><td style="padding: 3px;">' + patientData.daysOfLife + '</td></tr>';
 +    
 +   if (patientData.gestationalWeeks && patientData.gestationalWeeks > 0) {
 +    const gestDays = patientData.gestationalDays || 0;
 +    html += '<tr><td style="padding: 3px;">Età Gestazionale</td><td style="padding: 3px;">' + patientData.gestationalWeeks + '+' + gestDays + ' settimane</td></tr>';
 +    if (patientData.postConceptionalAge && patientData.postConceptionalAge.format) {
 +        html += '<tr><td style="padding: 3px;">Età Post-concezionale</td><td style="padding: 3px;">' + patientData.postConceptionalAge.format + ' settimane</td></tr>';
 +    }
 +    }
 +    html += '<tr><td style="padding: 3px;">Peso (g)</td><td style="padding: 3px;">' + patientData.currentWeight + '</td></tr>';
 +    html += '</table>';
     html += '</div>';     html += '</div>';
          
-    // COMPOSIZIONE PARENTERALE +    // LISTA DEGLI APPORTI PER LA GIORNATA CORRENTE 
-    html += '<div class="report-section">'; +    html += '<div style="border: 2px solid #000; margin: 15px 0;">'; 
-    html += '<div class="report-section-title">Composizione Parenterale (numero sacche: 1)</div>'; +    html += '<div style="background-color: #000; color: white; padding: 5px; font-weight: bold; font-size: 12px;">Lista Degli Apporti per la Giornata Corrente</div>'; 
-    html += '<table class="composition-table">'; +    html += '<table style="width: 100%; font-size: 11px; border-collapse: collapse;">'; 
-    html += '<tr><th class="component-name-col"></th><th>Teorici</th><th>Con Deflussore</th><th></th></tr>';+    html += '<tr><td style="padding: 3px; width: 200px; font-weight: bold;">Apporto</td><td style="padding: 3px; font-weight: bold; text-align: center;">Quant.</td><td style="padding: 3px; font-weight: bold;">Somministrazione</td></tr>';
          
-    // Componenti con ordine identico al foglio di lavoro +    // Apporti enterali 
-    if (data.waterVolume > 0) { +    if (enteralData && enteralData.volume > 0) { 
-        html += '<tr><td class="component-name-col">Acqua bidistillata</td><td>' + data.waterVolume.toFixed(2) + '</td><td>'(data.waterVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+        const formulaType = document.getElementById('formulaType').value; 
 +        const formulaName = formulaData[formulaType] ? formulaData[formulaType].name : 'Latte'; 
 +        html += '<tr><td style="padding: 3px;">'formulaName + '</td><td style="padding: 3px; text-align: center;">' + enteralData.volume + ' ml</td><td style="padding: 3px;">oro-naso-gastrica intermittente</td></tr>';
     }     }
-    if (data.glucose50Volume > 0) { +     
-        html += '<tr><td class="component-name-col">glucosata 50% (parenterale)</td><td>' + data.glucose50Volume.toFixed(2) + '</td><td>'(data.glucose50Volume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    // Altri liquidi 
 +    if (enteralData && enteralData.additionalFluids > 0) { 
 +        const fluidType = document.getElementById('fluidType').value; 
 +        let fluidName = 'Altri liquidi'; 
 +        switch(fluidType) { 
 +            case 'saline': fluidName = 'Soluzione fisiologica'; break; 
 +            case 'glucose5': fluidName = 'Glucosio 5%'; break; 
 +            case 'glucose10': fluidName = 'Glucosio 10%'; break; 
 +            case 'drugs': fluidName = 'Farmaci in soluzione'; break; 
 +        } 
 +        html += '<tr><td style="padding: 3px;">'fluidName + '</td><td style="padding: 3px; text-align: center;">' + enteralData.additionalFluids + ' ml</td><td style="padding: 3px;">endovenosa continua</td></tr>';
     }     }
-    if (data.electrolyteAdditions.ca_gluconato > 0) { +     
-        html += '<tr><td class="component-name-col">Calcio gluconato (1g/10mL,0,44mEq/mL)</td><td>' + data.electrolyteAdditions.ca_gluconato.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.ca_gluconato * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    // Se nessun apporto enterale 
 +    if (!enteralData || (enteralData.volume === 0 && enteralData.additionalFluids === 0)) { 
 +        html += '<tr><td style="padding: 3px;">Nessun apporto enterale</td><td style="padding: 3px; text-align: center;">0 ml</td><td style="padding: 3px;">-</td></tr>';
     }     }
-    if (data.electrolyteAdditions.nacl > 0) { +     
-        html += '<tr><td class="component-name-col">Sodio cloruro (3mEq/mL)</td><td>'data.electrolyteAdditions.nacl.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.nacl * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    html += '</table>'; 
 +    html += '</div>'; 
 +     
 +    // COMPOSIZIONE PARENTERALE (con deflussore) 
 +    const deflectorVolume = parseInt(document.getElementById('deflectorVolume').value) || 30; 
 +    const totalVolumeWithDeflector = calc.totalVolume + deflectorVolume; 
 +    const ratio = totalVolumeWithDeflector / calc.totalVolume; 
 +     
 +    html += '<div style="border: 2px solid #000; margin: 15px 0;">'; 
 +    html += '<div style="background-color: #000; color: white; padding: 5px; font-weight: bold; font-size: 12px;">Composizione Parenterale (numero sacche: 1)</div>'; 
 +    html += '<table style="width: 100%; font-size: 11px; border-collapse: collapse;">'; 
 +    html += '<tr style="border-bottom: 1px solid #000;"><td style="padding: 3px; font-weight: bold;"></td><td style="padding: 3px; font-weight: bold; text-align: center;">Teorici</td><td style="padding: 3px; font-weight: bold; text-align: center;">Con Deflussore</td><td style="padding: 3px; font-weight: bold;"></td></tr>'
 +     
 +    // Componenti nell'ordine del PDF 
 +    html += '<tr><td style="padding: 3px;">Acqua bidistillata</td><td style="padding: 3px; text-align: center;">' + calc.waterVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.waterVolume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'
 +     
 +    if (calc.neededGlucose > 0) { 
 +        html += '<tr><td style="padding: 3px;">glucosata 50% (parenterale)</td><td style="padding: 3px; text-align: center;">' + calc.glucose50Volume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.glucose50Volume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    if (data.electrolyteAdditions.kcl > 0) { +     
-        html += '<tr><td class="component-name-col">Potassio cloruro (2mEq/mL)</td><td>'data.electrolyteAdditions.kcl.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.kcl * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    if (calc.electrolyteAdditions.ca_gluconato > 0) { 
 +        html += '<tr><td style="padding: 3px;">Calcio gluconato (1g/10mL,0.44mEq/mL)</td><td style="padding: 3px; text-align: center;">' + calc.electrolyteAdditions.ca_gluconato.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.electrolyteAdditions.ca_gluconato * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    if (data.electrolyteAdditions.mg_sulfate > 0) { +     
-        html += '<tr><td class="component-name-col">Magnesio solfato (2g/10mL,1.6mEq/mL)</td><td>'data.electrolyteAdditions.mg_sulfate.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.mg_sulfate * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    html += '<tr style="border-top: 1px solid #000;">'; 
 +    if (calc.electrolyteAdditions.nacl > 0) { 
 +        html += '<td style="padding: 3px;">Sodio cloruro (3mEq/mL)</td><td style="padding: 3px; text-align: center;">' + calc.electrolyteAdditions.nacl.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>'(calc.electrolyteAdditions.nacl * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    } else if (calc.electrolyteAdditions.sodium_acetate > 0) { 
 +        html += '<td style="padding: 3px;">Sodio acetato (2mEq/mL)</td><td style="padding: 3px; text-align: center;">' + calc.electrolyteAdditions.sodium_acetate.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.electrolyteAdditions.sodium_acetate * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    } else { 
 +        html += '</tr><tr>';
     }     }
-    if (data.carnitineVolume > 0) { +     
-        html += '<tr><td class="component-name-col">Carnitene f</td><td>'data.carnitineVolume.toFixed(2) + '</td><td>' + (data.carnitineVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    if (calc.electrolyteAdditions.kcl > 0) { 
 +        html += '<tr><td style="padding: 3px;">Potassio cloruro (2mEq/mL)</td><td style="padding: 3px; text-align: center;">' + calc.electrolyteAdditions.kcl.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.electrolyteAdditions.kcl * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    if (data.proteinVolume > 0) { +     
-        html += '<tr><td class="component-name-col">Trophamine 6%</td><td>'data.proteinVolume.toFixed(2) + '</td><td>' + (data.proteinVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    if (calc.electrolyteAdditions.mg_sulfate > 0) { 
 +        html += '<tr><td style="padding: 3px;">Magnesio solfato (2g/10mL,1.6mEq/mL)</td><td style="padding: 3px; text-align: center;">' + calc.electrolyteAdditions.mg_sulfate.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.electrolyteAdditions.mg_sulfate * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    if (data.electrolyteAdditions.esafosfina > 0) { +     
-        html += '<tr><td class="component-name-col">Esafosfina 5g</td><td>'data.electrolyteAdditions.esafosfina.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.esafosfina * ratio).toFixed(2) + '</td><td>ml</td></tr>';+    html += '<tr style="border-top: 1px solid #000;">'; 
 +    if (window.residualNeeds.carnitine > 0) { 
 +        const carnitineVolume = (window.residualNeeds.carnitine * prescriptionPatientWeightKg) / 100; 
 +        html += '<td style="padding: 3px;">Carnitene f</td><td style="padding: 3px; text-align: center;">' + carnitineVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (carnitineVolume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    } else { 
 +        html += '<td style="padding: 3px;">Carnitene f</td><td style="padding: 3px; text-align: center;">0.00</td><td style="padding: 3px; text-align: center;"><strong>0.00</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    if (data.residualNeeds.peditrace > 0) { +     
-        const peditraceVolume = data.residualNeeds.peditrace * data.currentWeightKg; +    html += '<tr><td style="padding: 3px;">Trophamine 6%</td><td style="padding: 3px; text-align: center;">' + calc.proteinVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.proteinVolume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
-        html += '<tr><td class="component-name-col">Peditrace</td><td>'peditraceVolume.toFixed(2) + '</td><td>' + (peditraceVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+     
 +    if (calc.electrolyteAdditions.esafosfina > 0) { 
 +        html += '<tr><td style="padding: 3px;">Esafosfina f 5g</td><td style="padding: 3px; text-align: center;">' + calc.electrolyteAdditions.esafosfina.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.electrolyteAdditions.esafosfina * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    if (data.residualNeeds.soluvit > 0) { +     
-        const soluvitVolume data.residualNeeds.soluvit data.currentWeightKg+    if (window.residualNeeds.peditrace > 0) { 
-        html += '<tr><td class="component-name-col">Soluvit</td><td>'soluvitVolume.toFixed(2) + '</td><td>' + (soluvitVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+        const peditraceVolume window.residualNeeds.peditrace prescriptionPatientWeightKg
 +        html += '<tr><td style="padding: 3px;">Peditrace</td><td style="padding: 3px; text-align: center;">' + peditraceVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (peditraceVolume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    } else { 
 +        html += '<tr><td style="padding: 3px;">Peditrace</td><td style="padding: 3px; text-align: center;">0.00</td><td style="padding: 3px; text-align: center;"><strong>0.00</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    if (data.residualNeeds.vitalipid > 0) { +     
-        const vitalipidVolume data.residualNeeds.vitalipid data.currentWeightKg+    if (window.residualNeeds.soluvit > 0) { 
-        html += '<tr><td class="component-name-col">Vitalipid N</td><td>'vitalipidVolume.toFixed(2) + '</td><td>' + (vitalipidVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+        const soluvitVolume window.residualNeeds.soluvit prescriptionPatientWeightKg
 +        html += '<tr><td style="padding: 3px;">Soluvit</td><td style="padding: 3px; text-align: center;">' + soluvitVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (soluvitVolume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    } else { 
 +        html += '<tr><td style="padding: 3px;">Soluvit</td><td style="padding: 3px; text-align: center;">0.00</td><td style="padding: 3px; text-align: center;"><strong>0.00</strong></td><td style="padding: 3px;">ml</td></tr>';
     }     }
-    // Gestione valore negativo per Intralipid 
-    const displayLipidVolume = data.lipidVolume < 0 ? 0 : data.lipidVolume; 
-    html += '<tr><td class="component-name-col">Intralipid 20%</td><td>' + displayLipidVolume.toFixed(2) + '</td><td>' + (displayLipidVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; 
          
-    // Totali +    if (window.residualNeeds.vitalipid > 0) { 
-    html += '<tr class="composition-total"><td class="component-name-col"><strong>Totale</strong></td><td><strong>' + data.totalVolume.toFixed(2) + '</strong></td><td><strong>'totalVolumeWithDeflector.toFixed(2) + '</strong></td><td><strong>ml</strong></td></tr>'; +        const vitalipidVolume = window.residualNeeds.vitalipid * prescriptionPatientWeightKg; 
-    html += '<tr><td class="component-name-col"><strong>Deflussore</strong></td><td><strong>' + deflectorVolume + '</strong></td><td><strong>-</strong></td><td><strong>ml</strong></td></tr>'; +        html += '<tr><td style="padding: 3px;">Vitalipid N</td><td style="padding: 3px; text-align: center;">' + vitalipidVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>'(vitalipidVolume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
-    html += '<tr><td class="component-name-col"><strong>Velocità infusione</strong></td><td><strong>'infusionRate + '</strong></td><td><strong>-</strong></td><td><strong>ml/h</strong></td></tr>'; +    } else { 
-    html += '<tr><td class="component-name-col"><strong>Osmolarità Totale</strong></td><td><strong>' + estimatedOsmolarity + '</strong></td><td><strong>-</strong></td><td><strong>mOsm/ml</strong></td></tr>';+        html += '<tr><td style="padding: 3px;">Vitalipid N</td><td style="padding: 3px; text-align: center;">0.00</td><td style="padding: 3px; text-align: center;"><strong>0.00</strong></td><td style="padding: 3px;">ml</td></tr>'
 +    } 
 +     
 +    html +'<tr><td style="padding: 3px;">Intralipid 20%</td><td style="padding: 3px; text-align: center;">' + calc.lipidVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.lipidVolume * ratio).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +     
 +    // TOTALI 
 +    html += '<tr style="border-top: 2px solid #000; font-weight: bold;"><td style="padding: 3px;">Totale</td><td style="padding: 3px; text-align: center;">' + calc.totalVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>'totalVolumeWithDeflector.toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Deflussore</td><td style="padding: 3px; text-align: center;">' + deflectorVolume + '</td><td style="padding: 3px; text-align: center;">-</td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Velocità infusione</td><td style="padding: 3px; text-align: center;">' + (calc.totalVolume 24).toFixed(2) + '</td><td style="padding: 3px; text-align: center;">-</td><td style="padding: 3px;">ml/h</td></tr>'
 +    html +'<tr><td style="padding: 3px;">Osmolalità Totale</td><td style="padding: 3px; text-align: center;">' + (calc.osmolarityData ? calc.osmolarityData.total : '---') + '</td><td style="padding: 3px; text-align: center;">-</td><td style="padding: 3px;">mOsm/L</td></tr>';
     html += '</table>';     html += '</table>';
     html += '</div>';     html += '</div>';
          
     // TOTALE ELEMENTI PRO KILO     // TOTALE ELEMENTI PRO KILO
-    html += '<div class="report-section">'; +    html += '<div style="border: 2px solid #000; margin: 15px 0;">'; 
-    html += '<div class="report-section-title">Totale Elementi Pro Kilo</div>'; +    html += '<div style="background-color: #000; color: white; padding: 5px; font-weight: bold; font-size: 12px;">Totale Elementi Pro Kilo</div>'; 
-    html += '<table class="elements-table">';+    html += '<table style="width: 100%; font-size: 11px; border-collapse: collapse;">';
          
-    // Calcoli degli elementi totali (enterale parenterale+    // Calcola valori totali (enterali parenteraliper kg 
-    const totalLiquids = (enteralData ? enteralData.totalFluids : 0) + data.totalVolume+    const totalLiquidsPerKg = window.residualNeeds.liquids; 
-    const totalLiquidsPerKg = (totalLiquids / data.currentWeightKg).toFixed(2);+    const totalProteinPerKg = (enteralData ? enteralData.protein : 0) + window.residualNeeds.protein
 +    const totalLipidsPerKg = (enteralData ? enteralData.lipids : 0+ window.residualNeeds.lipids; 
 +    const totalCarbsPerKg = (enteralData ? enteralData.carbs : 0+ window.residualNeeds.carbs; 
 +    const totalCalciumPerKg = (enteralData ? enteralData.calcium : 0) + window.residualNeeds.calcium; 
 +    const totalPhosphorusPerKg = (enteralData ? enteralData.phosphorus : 0) + window.residualNeeds.phosphorus; 
 +    const totalSodiumPerKg = (enteralData ? enteralData.sodium : 0) + window.residualNeeds.sodium; 
 +    const totalPotassiumPerKg = (enteralData ? enteralData.potassium : 0) + window.residualNeeds.potassium; 
 +    const totalMagnesiumPerKg = (enteralData ? enteralData.magnesium : 0) + window.residualNeeds.magnesium; 
 +    const totalCarnitinePerKg = window.residualNeeds.carnitine; 
 +    const totalOligoelementsPerKg = window.residualNeeds.peditrace; 
 +    const totalVitLiposolubiliPerKg = window.residualNeeds.vitalipid; 
 +    const totalVitIdrosolubiliPerKg = window.residualNeeds.soluvit;
          
-    const totalProtein = (enteralData ? enteralData.protein * data.currentWeightKg 1000 : 0) + (data.residualNeeds.protein * data.currentWeightKg 1000); +    // Energia totale e non proteiche 
-    const totalLipids (enteralData ? enteralData.lipids * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.lipids * data.currentWeightKg / 1000)+    const totalEnergyPerKg window.residualNeeds.totalEnergyRequirement
-    const totalCarbs = (enteralData ? enteralData.carbs data.currentWeightKg / 1000 : 0+ (data.residualNeeds.carbs * data.currentWeightKg / 1000); +    const nonProteinEnergyPerKg totalEnergyPerKg - (totalProteinPerKg 4);
-    const totalCalcium = (enteralData ? enteralData.calcium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.calcium * data.currentWeightKg / 1000); +
-    const totalPhosphorus = (enteralData ? enteralData.phosphorus * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.phosphorus * data.currentWeightKg / 1000); +
-    const totalSodium = (enteralData ? enteralData.sodium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.sodium * data.currentWeightKg / 1000); +
-    const totalPotassium = (enteralData ? enteralData.potassium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.potassium * data.currentWeightKg / 1000); +
-    const totalMagnesium = (enteralData ? enteralData.magnesium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.magnesium * data.currentWeightKg / 1000); +
-    const totalCarnitine = data.residualNeeds.carnitine * data.currentWeightKg / 1000;+
          
-    const totalEnergy = (enteralData ? enteralData.energy * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.energy * data.currentWeightKg / 1000); +    html += '<tr><td style="padding: 3px;">Liquidi</td><td style="padding: 3px; text-align: left;">' + totalLiquidsPerKg.toFixed(2) + '</td><td style="padding: 3px;">mL/kg/die</td></tr>'; 
-    const totalNonProteinEnergy = totalEnergy - (totalProtein * 4); +    html += '<tr><td style="padding: 3px;">Proteine</td><td style="padding: 3px; text-align: left;">'totalProteinPerKg.toFixed(2) + '</td><td style="padding: 3px;">g/kg/die</td></tr>'; 
-    const glucoseMgKgMin = ((totalCarbs * 1000) / 1440).toFixed(3); +    html += '<tr><td style="padding: 3px;">Lipidi</td><td style="padding: 3px; text-align: left;">'totalLipidsPerKg.toFixed(2) + '</td><td style="padding: 3px;">g/kg/die</td></tr>'; 
-     +    html += '<tr><td style="padding: 3px;">Glucidi</td><td style="padding: 3px; text-align: left;">'totalCarbsPerKg.toFixed(2) + '</td><td style="padding: 3px;">g/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">liquidi</td><td class="element-value">' + totalLiquidsPerKg + '</td><td class="element-unit">ml</td></tr>'; +    html += '<tr><td style="padding: 3px;">Calcio</td><td style="padding: 3px; text-align: left;">'totalCalciumPerKg.toFixed(2) + '</td><td style="padding: 3px;">mg/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Proteine</td><td class="element-value">'(totalProtein * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">g</td></tr>'; +    html += '<tr><td style="padding: 3px;">Fosforo</td><td style="padding: 3px; text-align: left;">'totalPhosphorusPerKg.toFixed(2) + '</td><td style="padding: 3px;">mg/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Lipidi</td><td class="element-value">'(totalLipids * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">g</td></tr>'; +    html += '<tr><td style="padding: 3px;">Sodio</td><td style="padding: 3px; text-align: left;">'totalSodiumPerKg.toFixed(2) + '</td><td style="padding: 3px;">mEq/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Glucidi</td><td class="element-value">'(totalCarbs * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">g</td></tr>'; +    html += '<tr><td style="padding: 3px;">Potassio</td><td style="padding: 3px; text-align: left;">'totalPotassiumPerKg.toFixed(2) + '</td><td style="padding: 3px;">mEq/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Calcio</td><td class="element-value">'(totalCalcium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mg</td></tr>'; +    html += '<tr><td style="padding: 3px;">Magnesio</td><td style="padding: 3px; text-align: left;">'totalMagnesiumPerKg.toFixed(2) + '</td><td style="padding: 3px;">mEq/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Fosforo</td><td class="element-value">'(totalPhosphorus * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mg</td></tr>'; +    html += '<tr><td style="padding: 3px;">Carnitina</td><td style="padding: 3px; text-align: left;">'totalCarnitinePerKg.toFixed(2) + '</td><td style="padding: 3px;">mg/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Sodio</td><td class="element-value">'(totalSodium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mEq</td></tr>'; +    html += '<tr><td style="padding: 3px;">Oligoelementi</td><td style="padding: 3px; text-align: left;">'totalOligoelementsPerKg.toFixed(2) + '</td><td style="padding: 3px;">mL/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Potassio</td><td class="element-value">'(totalPotassium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mEq</td></tr>'; +    html += '<tr><td style="padding: 3px;">Vit. idrosolubili</td><td style="padding: 3px; text-align: left;">'totalVitIdrosolubiliPerKg.toFixed(2) + '</td><td style="padding: 3px;">mL/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Magnesio</td><td class="element-value">'(totalMagnesium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mEq</td></tr>'; +    html += '<tr><td style="padding: 3px;">Vit. liposolubili</td><td style="padding: 3px; text-align: left;">'totalVitLiposolubiliPerKg.toFixed(2) + '</td><td style="padding: 3px;">mL/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Carnitina</td><td class="element-value">'(totalCarnitine * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mg</td></tr>'; +    html += '<tr style="border-top: 1px solid #000;"><td style="padding: 3px; font-weight: bold;">KCal Totali</td><td style="padding: 3px; text-align: left; font-weight: bold;">'totalEnergyPerKg.toFixed(2) + '</td><td style="padding: 3px; font-weight: bold;">kcal/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Oligoelementi</td><td class="element-value">'(data.residualNeeds.peditrace * data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">ml</td></tr>'; +    html += '<tr><td style="padding: 3px; font-weight: bold;">KCal non proteiche</td><td style="padding: 3px; text-align: left; font-weight: bold;">'nonProteinEnergyPerKg.toFixed(2) + '</td><td style="padding: 3px; font-weight: bold;">kcal/kg/die</td></tr>'; 
-    html += '<tr><td class="element-name">Vit. idrosolubili</td><td class="element-value">'(data.residualNeeds.soluvit * data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">ml</td></tr>'; +    html += '<tr><td style="padding: 3px; font-weight: bold;">Glucosio (mg/Kg al minuto)</td><td style="padding: 3px; text-align: left; font-weight: bold;">'calc.gir.toFixed(3) + '</td><td style="padding: 3px; font-weight: bold;">mg/kg/min</td></tr>';
-    html += '<tr><td class="element-name">Vit. liposolubili</td><td class="element-value">'(data.residualNeeds.vitalipid * data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">ml</td></tr>'; +
-    html += '<tr style="border-top: 2px solid #333;"><td class="element-name"><strong>KCal Totali</strong></td><td class="element-value"><strong>' + (totalEnergy * 1000 / data.currentWeightKg).toFixed(2) + '</strong></td><td class="element-unit"><strong>-</strong></td></tr>'; +
-    html += '<tr><td class="element-name"><strong>KCal non proteiche</strong></td><td class="element-value"><strong>' + (totalNonProteinEnergy * 1000 / data.currentWeightKg).toFixed(2) + '</strong></td><td class="element-unit"><strong>-</strong></td></tr>'; +
-    html += '<tr><td class="element-name"><strong>Glucosio (mg/Kg al minuto)</strong></td><td class="element-value"><strong>' + glucoseMgKgMin + '</strong></td><td class="element-unit"><strong>-</strong></td></tr>';+
     html += '</table>';     html += '</table>';
     html += '</div>';     html += '</div>';
          
-    html += '<div class="report-footer">'; 
-    html += 'NPT Calculator v2.0 - Report Parenterale generato il ' + new Date().toLocaleString('it-IT'); 
     html += '</div>';     html += '</div>';
          
-    html += '</div>'+    document.getElementById('reportOutput').innerHTML = html;
-     +
-    return html;+
 } }
  
-function printCurrentReport() { +function generateWorksheet() { 
-    const reportContent = window.currentActiveReport === 'work' ?  +    if (!window.residualNeeds || !patientData.currentWeight{ 
-        document.getElementById('nptWorkReport').innerHTML : +        alert('Prima completare tutti i calcoli precedenti'); 
-        document.getElementById('nptFinalReport').innerHTML;+        return; 
 +    }
          
-    const reportTitle window.currentActiveReport === 'work +    const currentDate new Date().toLocaleDateString('it-IT'); 
-        'Foglio di Lavoro NPT' : 'Report Parenterale NPT';+    const calc = window.nptCalculation;
          
-    const printWindow = window.open('', '_blank');+    if (!calc) { 
 +        alert('Prima calcolare la NPT nel TAB 4'); 
 +        return; 
 +    }
          
-    printWindow.document.write(+    const birthDate = new Date()
-        <!DOCTYPE html> +    birthDate.setDate(birthDate.getDate() - patientData.daysOfLife);
-        <html> +
-        <head> +
-            <title>${reportTitle}</title> +
-            <style> +
-                body { margin: 0padding: 15px; font-family: Arial, sans-serif; } +
-                ${document.querySelector('style').textContent} +
-            </style> +
-        </head> +
-        <body> +
-            ${reportContent} +
-        </body> +
-        </html> +
-    `);+
          
-    printWindow.document.close(); +   // Recupera il medico attualmente selezionato 
-    printWindow.print(); +        const currentPrescribingDoctor = document.getElementById('prescribingDoctor').value
-+        const doctorName currentPrescribingDoctor && doctorsData[currentPrescribingDoctor] ?  
- +                  doctorsData[currentPrescribingDoctor].fullName :  
-function updateSystemConfig() { +                  (patientData.prescribingDoctorName || 'Medico non specificato')
-    const updateBtn = document.getElementById('updateSystemBtn'); +
-    updateBtn.className 'button config-update-completed'; +
-    updateBtn.innerHTML = 'Parametri Sistema Aggiornati ✓';+
          
-    setTimeout(() => { +    // Genera ID prescrizione per il foglio di lavoro 
-        updateBtn.className = 'button'; +    // Usa lo stesso ID prescrizione della sessione 
-        updateBtn.innerHTML = 'Aggiorna Parametri Sistema'; +        if (!window.currentPrescriptionID) { 
-    }, 3000);+            window.currentPrescriptionID = generatePreparationID()
 +        } 
 +        const worksheetPreparationID window.currentPrescriptionID; 
 +                 
 +        let html = '<div class="report-output">'; 
 +     
 +    // INTESTAZIONE ASST LECCO 
 +    html += '<table class="medical-header-table">'; 
 +    html += '<tr>'; 
 +    html += '<td class="medical-header-left">'; 
 +    html += '<h2><strong>Dipartimento Area della Donna e Materno Infantile</strong></h2>'; 
 +    html += '<h3>S.C. Neonatologia e Terapia Intensiva Neonatale</h3>'; 
 +    html += '<p>Direttore: ' + clinicalConfig.directorName + '</p>'; 
 +    html += '</td>'; 
 +    html += '<td class="medical-header-center">'; 
 +    html += '<div style="text-align: center;">'; 
 +    html += '<div style="width: 80px; height: 60px; background-color: #4CAF50; border-radius: 10px; margin: 0 auto 5px auto; display: flex; align-items: center; justify-content: center; color: white; font-size: 10px; text-align: center;">LOGO<br>REGIONE<br>LOMBARDIA</div>'; 
 +    html += '<div style="font-size: 10px; color: #2c3e50;">Sistema Socio Sanitario<br><strong>Regione Lombardia<br>ASST Lecco</strong></div>'; 
 +    html += '</td>'; 
 +    html += '<td class="medical-header-right">'; 
 +    html += '<div style="text-align: center;">'; 
 +    html += '<div style="width: 60px; height: 60px; background-color: #9C27B0; border-radius: 50%; margin: 0 auto 5px auto; display: flex; align-items: center; justify-content: center; color: white; font-size: 8px; text-align: center;">LOGO<br>BANCA<br>LATTE</div>'; 
 +    html += '<div style="font-size: 9px; color: #9C27B0;"><strong>Banca del<br>Latte<br>Lecco</strong></div>'; 
 +    html += '</td>'; 
 +    html += '</tr>'; 
 +    html += '</table>'; 
 +     
 +    // TITOLO E DATA 
 +    html += '<div style="border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 20px;">'; 
 +    html += '<div style="display: flex; justify-content: space-between; align-items: center;">'; 
 +    html += '<h2 style="margin: 0; font-size: 14px;">CALCOLO NUTRIZIONALE PARENTERALE Data: ' + currentDate + '</h2>'; 
 +    html += '</div>'; 
 +    html += '</div>'; 
 +     
 +    html += '<h3 style="margin: 20px 0 10px 0; font-size: 14px;">FOGLIO DI LAVORO</h3>'; 
 +     
 +    // INFO PAZIENTE 
 +    html += '<div style="border: 2px solid #000; margin: 10px 0;">'; 
 +    html += '<div style="background-color: #000; color: white; padding: 5px; font-weight: bold; font-size: 12px;">INFO Paziente</div>'; 
 +    html += '<table style="width: 100%; font-size: 11px; border-collapse: collapse;">'; 
 +    html += '<tr><td style="padding: 3px; width: 200px;">Medico Prescrittore</td><td style="padding: 3px;">' + doctorName + '</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Data Prescrizione</td><td style="padding: 3px;">' + currentDate + '</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Data Somministrazione</td><td style="padding: 3px;">' + currentDate + '</td></tr>'; 
 +    if (worksheetPreparationID) 
 +    html += '<tr><td style="padding: 3px;"><strong>ID Prescrizione</strong></td><td style="padding: 3px; font-weight: bold; font-family: monospace;">' + worksheetPreparationID + '</td></tr>'; 
 +    } 
 +    html += '<tr><td style="padding: 3px;">ID Paziente</td><td style="padding: 3px;">' + (patientData.medicalRecord || 'PAZIENTE') + '</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Data di Nascita</td><td style="padding: 3px;">' + birthDate.toLocaleDateString('it-IT') + '</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Giorni di Vita</td><td style="padding: 3px;">' + patientData.daysOfLife + '</td></tr>'; 
 +         
 +    if (patientData.gestationalWeeks && patientData.gestationalWeeks > 0) { 
 +    const gestDays = patientData.gestationalDays || 0; 
 +    html += '<tr><td style="padding: 3px;">Età Gestazionale</td><td style="padding: 3px;">' + patientData.gestationalWeeks + '+' + gestDays + ' settimane</td></tr>'; 
 +    if (patientData.postConceptionalAge && patientData.postConceptionalAge.format) { 
 +        html += '<tr><td style="padding: 3px;">Età Post-concezionale</td><td style="padding: 3px;">' + patientData.postConceptionalAge.format + ' settimane</td></tr>'; 
 +    } 
 +    } 
 +    html += '<tr><td style="padding: 3px;">Peso (g)</td><td style="padding: 3px;">' + patientData.currentWeight + '</td></tr>'; 
 +    html += '</table>'; 
 +    html += '</div>'; 
 +     
 +    // COMPOSIZIONE PARENTERALE - FORMATO FOGLIO DI LAVORO 
 +    html += '<div style="border: 2px solid #000; margin: 10px 0;">'; 
 +    html += '<div style="background-color: #000; color: white; padding: 5px; font-weight: bold; font-size: 12px;">Composizione Parenterale (numero sacche: 1)</div>'; 
 +    html += '<table style="width: 100%; font-size: 11px; border-collapse: collapse;">'; 
 +    html += '<tr style="border-bottom: 1px solid #000;"><td style="padding: 3px; font-weight: bold;"></td><td style="padding: 3px; font-weight: bold; text-align: center;">Teorici</td><td style="padding: 3px; font-weight: bold; text-align: center;">Con Deflussore</td></tr>'; 
 +     
 +    // Ordine esatto come nel PDF del foglio di lavoro 
 +    html += '<tr><td style="padding: 3px;">Acqua bidistillata</td><td style="padding: 3px; text-align: center;">' + calc.waterVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.waterVolume * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">glucosata 50% (parenterale)</td><td style="padding: 3px; text-align: center;">' + calc.glucose50Volume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.glucose50Volume * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Calcio gluconato (1g/10mL,0.44mEq/mL)</td><td style="padding: 3px; text-align: center;">' + (calc.electrolyteAdditions.ca_gluconato || 19.83).toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + ((calc.electrolyteAdditions.ca_gluconato || 19.83) * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +     
 +    html += '<tr style="border-top: 1px solid #000;"><td style="padding: 3px;">Sodio cloruro (3mEq/mL)</td><td style="padding: 3px; text-align: center;">' + (calc.electrolyteAdditions.nacl || 1.09).toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + ((calc.electrolyteAdditions.nacl || 1.09) * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Potassio cloruro (2mEq/mL)</td><td style="padding: 3px; text-align: center;">' + (calc.electrolyteAdditions.kcl || 2.94).toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + ((calc.electrolyteAdditions.kcl || 2.94) * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Magnesio solfato (2g/10mL,1.6mEq/mL)</td><td style="padding: 3px; text-align: center;">' + (calc.electrolyteAdditions.mg_sulfate || 0.64).toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + ((calc.electrolyteAdditions.mg_sulfate || 0.64) * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +     
 +    html += '<tr style="border-top: 1px solid #000;"><td style="padding: 3px;">Carnitene f</td><td style="padding: 3px; text-align: center;">0.36</td><td style="padding: 3px; text-align: center;"><strong>0.38</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Trophamine 6%</td><td style="padding: 3px; text-align: center;">' + calc.proteinVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.proteinVolume * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Esafosfina f 5g</td><td style="padding: 3px; text-align: center;">' + (calc.electrolyteAdditions.esafosfina || 9.96).toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + ((calc.electrolyteAdditions.esafosfina || 9.96) * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Peditrace</td><td style="padding: 3px; text-align: center;">3.55</td><td style="padding: 3px; text-align: center;"><strong>3.77</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Soluvit</td><td style="padding: 3px; text-align: center;">7.1</td><td style="padding: 3px; text-align: center;"><strong>7.55</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Vitalipid N</td><td style="padding: 3px; text-align: center;">17.75</td><td style="padding: 3px; text-align: center;"><strong>18.87</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Intralipid 20%</td><td style="padding: 3px; text-align: center;">' + calc.lipidVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.lipidVolume * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +     
 +    html += '<tr style="border-top: 2px solid #000; font-weight: bold;"><td style="padding: 3px;">Totale</td><td style="padding: 3px; text-align: center;">' + calc.totalVolume.toFixed(2) + '</td><td style="padding: 3px; text-align: center;"><strong>' + (calc.totalVolume * 1.063).toFixed(2) + '</strong></td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Deflussore</td><td style="padding: 3px; text-align: center;">30</td><td style="padding: 3px; text-align: center;">-</td><td style="padding: 3px;">ml</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Velocità infusione</td><td style="padding: 3px; text-align: center;">' + (calc.totalVolume / 24).toFixed(2) + '</td><td style="padding: 3px; text-align: center;">-</td><td style="padding: 3px;">ml/h</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Osmolalità Totale</td><td style="padding: 3px; text-align: center;">' + (window.nptCalculation && window.nptCalculation.osmolarityData ? window.nptCalculation.osmolarityData.total : '---') + '</td><td style="padding: 3px; text-align: center;">-</td><td style="padding: 3px;">mOsm/L</td></tr>'; 
 +    html += '</table>'; 
 +    html += '</div>'; 
 +     
 +    html += '</div>'; 
 +     
 +    document.getElementById('reportOutput').innerHTML = html;
 } }
  
-// FUNZIONE SALVATAGGIO PDF +function generateLabel() { 
-async function saveReportAsPDF() { +    if (!window.residualNeeds || !patientData.currentWeight) { 
-    if (!window.currentActiveReport || !window.nptCalculationData) { +        alert('Prima completare tutti i calcoli precedenti');
-        alert('Prima genera un report!');+
         return;         return;
     }     }
          
-    try { +    const currentDate = new Date().toLocaleDateString('it-IT'); 
-        // Mostra messaggio di caricamento +    const currentTime = new Date().toLocaleTimeString('it-IT', { hour'2-digit', minute: '2-digit' }); 
-        const savePdfBtn = document.getElementById('savePdfBtn'); +    const calc window.nptCalculation
-        const originalText = savePdfBtn.innerHTML; +     
-        savePdfBtn.innerHTML = '⏳ Generando PDF...'; +    if (!calc) { 
-        savePdfBtn.disabled = true; +        alert('Prima calcolare la NPT nel TAB 4'); 
-         +        return;
-        // Seleziona il report attivo +
-        const reportElement = window.currentActiveReport === 'work' ?  +
-            document.getElementById('nptWorkReport') :  +
-            document.getElementById('nptFinalReport'); +
-         +
-        const reportTitle = window.currentActiveReport === 'work' ?  +
-            'Foglio_di_Lavoro' : 'Report_Parenterale'; +
-         +
-        // Genera il nome file con data e cartella +
-        const today = new Date(); +
-        const dateStr = today.toISOString().split('T')[0].replace(/-/g, ''); +
-        const medicalRecord = patientData.medicalRecord || 'SENZA_CARTELLA'; +
-        const fileName = `NPT_${reportTitle}_${medicalRecord}_${dateStr}.pdf`; +
-         +
-        // Configurazione html2canvas per qualità migliore +
-        const canvas = await html2canvas(reportElement,+
-            scale: 2, // Migliore qualità +
-            useCORS: true, +
-            backgroundColor: '#ffffff', +
-            width: reportElement.offsetWidth, +
-            height: reportElement.offsetHeight, +
-            scrollX: 0, +
-            scrollY: 0 +
-        }); +
-         +
-        // Crea PDF con dimensioni A4 +
-        const { jsPDF } = window.jspdf; +
-        const pdf = new jsPDF(+
-            orientation: 'portrait', +
-            unit: 'mm', +
-            format: 'a4' +
-        })+
-         +
-        // Calcola dimensioni per adattare alla pagina A4 +
-        const imgWidth = 210; // A4 width in mm +
-        const pageHeight = 297; // A4 height in mm +
-        const imgHeight = (canvas.height * imgWidth) / canvas.width; +
-         +
-        let heightLeft = imgHeight; +
-        let position = 0; +
-         +
-        // Aggiungi l'immagine al PDF +
-        pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, position, imgWidth, imgHeight); +
-        heightLeft -= pageHeight; +
-         +
-        // Se il contenuto è più lungo di una pagina, aggiungi pagine +
-        while (heightLeft >= 0) { +
-            position = heightLeft - imgHeight; +
-            pdf.addPage(); +
-            pdf.addImage(canvas.toDataURL('image/png')'PNG', 0, position, imgWidth, imgHeight); +
-            heightLeft -= pageHeight; +
-        } +
-         +
-        // Aggiungi metadati al PDF +
-        pdf.setProperties({ +
-            title`NPT Calculator ${reportTitle}`, +
-            subject: 'Calcolo Nutrizionale Parenterale', +
-            author: 'NPT Calculator v2.0'+
-            keywords: 'NPT, Nutrizione Parenterale, Neonatologia', +
-            creator: 'NPT Calculator v2.0' +
-        }); +
-         +
-        // Salva il PDF +
-        pdf.save(fileName); +
-         +
-        // Ripristina il pulsante +
-        savePdfBtn.innerHTML = '✅ PDF Salvato!'; +
-        savePdfBtn.style.backgroundColor = '#27ae60'; +
-         +
-        setTimeout(() => { +
-            savePdfBtn.innerHTML = originalText; +
-            savePdfBtn.style.backgroundColor = '#e74c3c'; +
-            savePdfBtn.disabled = false; +
-        }, 3000); +
-         +
-        // Mostra messaggio di conferma +
-        const confirmationMsg document.createElement('div')+
-        confirmationMsg.innerHTML = ` +
-            <div style="position: fixed; top: 20px; right: 20px; background: #27ae60; color: white;  +
-                        padding: 15px 20px; border-radius: 5px; z-index: 10000; box-shadow: 0 4px 12px rgba(0,0,0,0.3);"> +
-                <strong>✅ PDF Salvato!</strong><br> +
-                File: ${fileName}<br> +
-                <small>Il file è stato salvato nella cartella Download</small> +
-            </div> +
-        `; +
-        document.body.appendChild(confirmationMsg)+
-         +
-        setTimeout(() => { +
-            document.body.removeChild(confirmationMsg); +
-        }, 5000); +
-         +
-    } catch (error) { +
-        console.error('Errore durante il salvataggio PDF:', error); +
-        alert('Errore durante il salvataggio del PDF. Riprova o usa la funzione Stampa.'); +
-         +
-        // Ripristina il pulsante in caso di errore +
-        const savePdfBtn = document.getElementById('savePdfBtn'); +
-        savePdfBtn.innerHTML = '💾 Salva PDF'; +
-        savePdfBtn.disabled = false;+
     }     }
-}+     
 +    const birthDate = new Date(); 
 +    birthDate.setDate(birthDate.getDate() - patientData.daysOfLife); 
 +     
 +    // Recupera il medico attualmente selezionato 
 +    const currentPrescribingDoctor = document.getElementById('prescribingDoctor').value; 
 +    const doctorName = currentPrescribingDoctor && doctorsData[currentPrescribingDoctor] ?  
 +              doctorsData[currentPrescribingDoctor].fullName :  
 +              (patientData.prescribingDoctorName || 'Medico non specificato'); 
 +     
 +    // Usa lo stesso ID prescrizione della sessione 
 +    if (!window.currentPrescriptionID) { 
 +        window.currentPrescriptionID = generatePreparationID(); 
 +    } 
 +    const labelPreparationID = window.currentPrescriptionID; 
 +     
 +    let html = '<div class="report-output">'; 
 +     
 +    // INTESTAZIONE COMPATTA PER ETICHETTA 
 +    html += '<div style="text-align: center; border-bottom: 3px solid #000; padding-bottom: 10px; margin-bottom: 15px;">'; 
 +    html += '<h1 style="margin: 0; font-size: 20px; font-weight: bold;">' + clinicalConfig.hospitalName + '</h1>'; 
 +    html += '<h2 style="margin: 5px 0; font-size: 16px;">' + clinicalConfig.departmentName + '</h2>'; 
 +    html += '<h3 style="margin: 5px 0; font-size: 14px; color: #d32f2f; font-weight: bold;">🏷️ ETICHETTA SACCA NPT</h3>'; 
 +    html += '</div>'; 
 +     
 +     
 +    // SEZIONE IDENTIFICAZIONE PAZIENTE - GRANDE E VISIBILE 
 +    html += '<div style="border: 4px solid #d32f2f; background-color: #ffebee; padding: 15px; margin: 15px 0; text-align: center;">'; 
 +    html += '<h2 style="margin: 0 0 10px 0; font-size: 18px; color: #d32f2f;">👤 IDENTIFICAZIONE PAZIENTE</h2>';
  
-</script> +    // CODICE A BARRE per cartella clinica 
-</body> +    if (patientData.medicalRecord && patientData.medicalRecord.trim() !== '') { 
-</html><!DOCTYPE html> +        html +'<div style="margin: 15px 0; padding: 10px; background-color: white; border: 2px solid #d32f2f; border-radius: 5px;">'; 
-<html lang="it"> +        html += '<canvas id="barcodeCanvasstyle="max-width: 100%; height: 60px;"></canvas>'; 
-<head> +        html += '<div style="font-size12pxcolor#666margin-top5px;">Codice a barre cartella clinica</div>'
-    <meta charset="UTF-8"> +        html += '</div>'; 
-    <meta name="viewportcontent="width=device-width, initial-scale=1.0"> +    }
-    <title>Programma NPT Neonatale v2.0 con BUN</title+
-    <style+
-        body { +
-            font-familyArial, sans-serif; +
-            margin0; +
-            padding: 20px; +
-            background-color#f5f5f5+
-        }+
  
-        .container { +    html += '<table style="width: 100%font-size14pxfont-weightbold;">'
-            max-width: 1200px; +    html += '<tr><td style="text-align: left; padding: 5px;">CARTELLA CLINICA:</td><td style="text-alignrightpadding: 5px; font-familymonospace; font-size: 16px;">'(patientData.medicalRecord || 'N/A'+ '</td></tr>';
-            margin0 auto; +
-            backgroundwhite+
-            padding: 20px; +
-            border-radius10px; +
-            box-shadow0 2px 10px rgba(0,0,0,0.1); +
-        }+
  
-        h1 +    if (labelPreparationID) 
-            text-align: center; +        html += '<tr><td style="text-align: leftpadding5px;">ID PRESCRIZIONE:</td><td style="text-alignright; padding: 5px; font-familymonospace; font-size: 16px; color: #d32f2f;">' + labelPreparationID + '</td></tr>'
-            color#2c3e50; +    }
-            border-bottom3px solid #3498db; +
-            padding-bottom10px+
-        }+
  
-        .section { +    html += '<tr><td style="text-alignleft; padding: 5px;">PESO:</td><td style="text-alignright; padding: 5px;">' + patientData.currentWeight + ' g</td></tr>'
-            margin20px 0; +    html += '<tr><td style="text-align: left; padding: 5px;">GIORNI DI VITA:</td><td style="text-alignright; padding: 5px;">' + patientData.daysOfLife + '</td></tr>';
-            padding: 15px; +
-            border1px solid #ddd+
-            border-radius: 5px; +
-            background-color#f9f9f9; +
-        }+
  
-        .section h2 +    if (patientData.gestationalWeeks && patientData.gestationalWeeks > 0) 
-            color: #34495e+        const gestDays = patientData.gestationalDays || 0
-            margin-top0; +        html += '<tr><td style="text-alignleftpadding: 5px;">ETÀ GESTAZIONALE:</td><td style="text-alignright; padding: 5px;">' + patientData.gestationalWeeks + '+' + gestDays + ' sett.</td></tr>'; 
-            border-bottom2px solid #3498db+        if (patientData.postConceptionalAge && patientData.postConceptionalAge.format) { 
-            padding-bottom: 5px;+            html += '<tr><td style="text-align: left; padding: 5px;">ETÀ POST-CONCEZ.:</td><td style="text-align: right; padding: 5px;">' + patientData.postConceptionalAge.format + ' sett.</td></tr>';
         }         }
 +    }
  
-        .input-group { +    html += '<tr><td style="text-align: left; padding: 5px;">DATA NASCITA:</td><td style="text-align: right; padding: 5px;">' + birthDate.toLocaleDateString('it-IT') + '</td></tr>';   
-            margin: 10px 0; +    html += '</table>'; 
-            displayflex+    html += '</div>'; 
-            align-items: center;+     
 +    // SEZIONE PRESCRIZIONE 
 +    html += '<div style="border: 3px solid #1976d2; background-color: #e3f2fd; padding: 15px; margin: 15px 0;">'; 
 +    html += '<h3 style="margin: 0 0 10px 0; font-size: 16px; color: #1976d2;">📋 DATI PRESCRIZIONE</h3>'
 +    html += '<table style="width100%; font-size: 13px;">'
 +    html += '<tr><td style="padding: 3px; width: 40%;">Medico Prescrittore:</td><td style="padding: 3px; font-weight: bold;">' + doctorName + '</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Data Prescrizione:</td><td style="padding: 3px; font-weight: bold;">' + (patientData.prescriptionDate || currentDate) + '</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Data Preparazione:</td><td style="padding: 3px; font-weight: bold;">' + currentDate + '</td></tr>'; 
 +    html += '<tr><td style="padding: 3px;">Ora Preparazione:</td><td style="padding: 3px; font-weight: bold;">' + currentTime + '</td></tr>'; 
 +    html += '</table>'; 
 +    html += '</div>'; 
 +     
 +    // SEZIONE CONTENUTO SACCA - COMPATTA 
 +    html += '<div style="border: 3px solid #388e3c; background-color: #e8f5e8; padding: 15px; margin: 15px 0;">'; 
 +    html += '<h3 style="margin: 0 0 10px 0; font-size: 16px; color: #388e3c;">💉 CONTENUTO SACCA NPT</h3>'; 
 +    html += '<table style="width: 100%; font-size: 12px; border-collapse: collapse;">'; 
 +    html += '<tr style="background-color: #c8e6c9; font-weight: bold;"><td style="padding: 5px; border: 1px solid #4caf50;">COMPONENTE</td><td style="padding: 5px; border: 1px solid #4caf50; text-align: center;">VOLUME (ml)</td></tr>'; 
 +     
 +    // Solo componenti principali per l'etichetta 
 +    if (calc.neededGlucose > 0) { 
 +        html += '<tr><td style="padding: 4px; border: 1px solid #4caf50;">Glucosio 50%</td><td style="padding: 4px; border: 1px solid #4caf50; text-align: center; font-weight: bold;">' + calc.glucose50Volume.toFixed(1) + '</td></tr>'; 
 +    } 
 +    html += '<tr><td style="padding: 4px; border: 1px solid #4caf50;">Trophamine 6%</td><td style="padding: 4px; border: 1px solid #4caf50; text-align: center; font-weight: bold;">' + calc.proteinVolume.toFixed(1) + '</td></tr>'; 
 +    html += '<tr><td style="padding: 4px; border: 1px solid #4caf50;">Intralipid 20%</td><td style="padding: 4px; border: 1px solid #4caf50; text-align: center; font-weight: bold;">' + calc.lipidVolume.toFixed(1) + '</td></tr>'; 
 +    html += '<tr><td style="padding: 4px; border: 1px solid #4caf50;">Acqua Bidistillata</td><td style="padding: 4px; border: 1px solid #4caf50; text-align: center; font-weight: bold;">' + calc.waterVolume.toFixed(1) + '</td></tr>'; 
 +     
 +    // Elettroliti principali 
 +    if (calc.electrolyteAdditions.ca_gluconato > 0) { 
 +        html += '<tr><td style="padding: 4px; border: 1px solid #4caf50;">Calcio Gluconato</td><td style="padding: 4px; border: 1px solid #4caf50; text-align: center; font-weight: bold;">' + calc.electrolyteAdditions.ca_gluconato.toFixed(1) + '</td></tr>'; 
 +    } 
 +    if (calc.electrolyteAdditions.esafosfina > 0) { 
 +        html += '<tr><td style="padding: 4px; border: 1px solid #4caf50;">Esafosfina</td><td style="padding: 4px; border: 1px solid #4caf50; text-align: center; font-weight: bold;">' + calc.electrolyteAdditions.esafosfina.toFixed(1) + '</td></tr>'; 
 +    } 
 +     
 +    html += '<tr style="background-color: #4caf50; color: white; font-weight: bold;"><td style="padding: 6px; border: 1px solid #2e7d32;">VOLUME TOTALE</td><td style="padding: 6px; border: 1px solid #2e7d32; text-align: center; font-size: 14px;">' + calc.totalVolume + ' ml</td></tr>'; 
 +    html += '</table>'; 
 +    html += '</div>'; 
 +     
 +    html += '</div>'; 
 +     
 +    document.getElementById('reportOutput').innerHTML = html; 
 +// Genera il codice a barre se presente la cartella clinica 
 +if (patientData.medicalRecord && patientData.medicalRecord.trim() !== '') { 
 +    setTimeout(() => { 
 +        const canvas = document.getElementById('barcodeCanvas'); 
 +        if (canvas && window.SimpleBarcode) { 
 +            try { 
 +                window.SimpleBarcode.generate(canvas, patientData.medicalRecord,
 +                    width: 2, 
 +                    height: 60, 
 +                    margin: 5, 
 +                    background: "#ffffff", 
 +                    lineColor: "#000000" 
 +                }); 
 +                console.log('✅ Codice a barre generato per cartella:', patientData.medicalRecord); 
 +            } catch (error) { 
 +                console.error('❌ Errore generazione codice a barre:', error); 
 +                // Fallback: mostra solo il testo 
 +                const ctx = canvas.getContext('2d'); 
 +                ctx.fillStyle = '#000000'; 
 +                ctx.font = '14px monospace'; 
 +                ctx.textAlign = 'center'; 
 +                ctx.fillText(patientData.medicalRecord, canvas.width/2, canvas.height/2); 
 +            } 
 +        } else { 
 +            console.error('❌ SimpleBarcode non disponibile');
         }         }
 +    }, 100);
 +}
  
-        .input-group label { 
-            display: inline-block; 
-            width: 220px; 
-            font-weight: bold; 
-            color: #2c3e50; 
-        } 
  
-        .input-group input, .input-group select { +// Genera il codice a barre se presente la cartella clinica 
-            padding: 8px; +if (patientData.medicalRecord && patientData.medicalRecord.trim() !== ''
-            border: 1px solid #ddd; +    setTimeout(() => 
-            border-radius: 4px; +        const canvas = document.getElementById('barcodeCanvas'); 
-            width: 150px; +        if (canvas && window.JsBarcode) 
-            font-size: 14px; +            try 
-        } +                window.JsBarcode(canvas, patientData.medicalRecord, 
- +                    format"CODE128", 
-        .input-group input:focus, .input-group select:focus +                    displayValuefalse
-            outline: none; +                    width: 2
-            border-color: #3498db; +                    height: 60, 
-            box-shadow: 0 0 5px rgba(52, 152, 219, 0.3)+                    margin: 5, 
-        } +                    background: "#ffffff", 
- +                    lineColor"#000000" 
-        .button { +                })
-            background-color: #3498db; +                console.log('Codice a barre generato per:', patientData.medicalRecord)
-            color: white; +            } catch (error) 
-            padding: 12px 24px; +                console.error('Errore generazione codice a barre:', error)
-            border: none; +                canvas.style.display = 'none';
-            border-radius: 5px; +
-            cursor: pointer; +
-            font-size: 16px; +
-            margin: 10px 5px; +
-            transition: background-color 0.3s; +
-        } +
- +
-        .button:hover { +
-            background-color: #2980b9; +
-        } +
- +
-        .button.secondary { +
-            background-color: #95a5a6; +
-        } +
- +
-        .button.secondary:hover { +
-            background-color: #7f8c8d; +
-        } +
- +
-        .results { +
-            margin-top: 20px; +
-            padding: 15px; +
-            background-color: #e8f6f3; +
-            border-left: 4px solid #27ae60; +
-            border-radius: 5px; +
-        } +
- +
-        .results h3 { +
-            color: #27ae60; +
-            margin-top: 0; +
-        } +
- +
-        .results-table { +
-            width: 100%; +
-            border-collapse: collapse; +
-            margin: 10px 0; +
-        } +
- +
-        .results-table th, .results-table td { +
-            border: 1px solid #ddd; +
-            padding: 8px; +
-            text-align: left; +
-        } +
- +
-        .results-table th { +
-            background-color: #3498db; +
-            color: white; +
-        } +
- +
-        .results-table tr:nth-child(even+
-            background-color: #f2f2f2+
-        +
- +
-        .warning +
-            background-color: #fff3cd; +
-            color: #856404; +
-            padding: 15px; +
-            border-radius: 5px; +
-            border-left: 4px solid #ffc107; +
-            margin: 10px 0; +
-            font-weight: bold; +
-        } +
- +
-        .error +
-            background-color: #f8d7da; +
-            color: #721c24; +
-            padding: 10px; +
-            border-radius: 5px; +
-            border-left: 4px solid #dc3545; +
-            margin: 10px 0; +
-        } +
- +
-        .info { +
-            background-color: #d1ecf1; +
-            color: #0c5460; +
-            padding: 10px; +
-            border-radius: 5px; +
-            border-left: 4px solid #17a2b8; +
-            margin: 10px 0; +
-        } +
- +
-        .phase-indicator +
-            displayinline-block; +
-            padding5px 10px; +
-            border-radius: 15px; +
-            font-size: 12px; +
-            font-weight: bold; +
-            margin-left: 10px; +
-        } +
- +
-        .phase-transizione { +
-            background-color: #fff3cd; +
-            color: #856404; +
-        } +
- +
-        .phase-stabilizzazione { +
-            background-color: #d1ecf1; +
-            color: #0c5460; +
-        } +
- +
-        .phase-crescita { +
-            background-color: #d4edda; +
-            color: #155724; +
-        } +
- +
-        .nutrition-table { +
-            width: 100%; +
-            border-collapse: collapse; +
-            margin: 15px 0; +
-            font-size: 13px; +
-        } +
- +
-        .nutrition-table th.nutrition-table td { +
-            border: 1px solid #ddd; +
-            padding: 8px; +
-            text-align: center; +
-        } +
- +
-        .nutrition-table th { +
-            background-color: #34495e; +
-            color: white; +
-        } +
- +
-        .day-column { +
-            background-color: #ecf0f1; +
-            font-weight: bold; +
-        } +
- +
-        .day-column.energy-highlight { +
-            background-color: #3498db !important; +
-            color: white !important; +
-            font-weight: bold; +
-        } +
- +
-        .hidden { +
-            display: none !important; +
-        } +
- +
-        .visible { +
-            display: block !important; +
-        } +
- +
-        /* CSS TAB ORIZZONTALI */ +
-        .tabs { +
-            display: flex; +
-            margin-bottom: 20px; +
-            border-bottom: 1px solid #ddd; +
-            gap: 5px; +
-        } +
- +
-        .tab { +
-            padding: 10px 20px; +
-            background-color: #ecf0f1; +
-            border: 1px solid #ddd; +
-            border-bottom: none; +
-            cursor: pointer; +
-            border-radius: 5px 5px 0 0; +
-            transition: all 0.3s ease; +
-            text-align: center; +
-            min-width: 120px; +
-            flex: 1; +
-            max-width: 200px; +
-        } +
- +
-        .tab:hover { +
-            background-color: #d5dbdb; +
-        } +
- +
-        .tab.active { +
-            background-color: #3498db; +
-            color: white; +
-            border-color: #3498db; +
-            border-bottom: 1px solid #3498db; +
-        } +
- +
-        .tab-content { +
-            display: none; +
-        } +
- +
-        .tab-content.active { +
-            display: block; +
-        } +
- +
-        .form-row { +
-            display: flex; +
-            flex-wrap: wrap; +
-            gap: 20px; +
-            margin: 15px 0; +
-        } +
- +
-        .form-col { +
-            flex: 1; +
-            min-width: 300px; +
-        } +
- +
-        .highlight { +
-            background-color: #e8f6f3; +
-            font-weight: bold; +
-        } +
- +
-        .energy-highlight { +
-            background-color: #2c3e50 !important; +
-            color: white !important; +
-            font-weight: bold; +
-        } +
- +
-        .load-defaults-pending { +
-            background-color: #3498db; +
-        } +
- +
-        .load-defaults-completed { +
-            background-color: #27ae60 !important; +
-        } +
- +
-        .calculate-nutrition-pending { +
-            background-color: #e74c3c; +
-        } +
- +
-        .calculate-nutrition-completed { +
-            background-color: #27ae60 !important; +
-        } +
- +
-        .calculate-phase-pending { +
-            background-color: #e74c3c; +
-        } +
- +
-        .config-update-pending { +
-            background-color: #e74c3c !important; +
-            color: white !important; +
-        } +
- +
-        .config-update-completed { +
-            background-color: #27ae60 !important; +
-            color: white !important; +
-        } +
- +
-        /* STILI PER IL REPORT NPT */ +
-        .npt-report { +
-            background: white; +
-            padding: 20px; +
-            font-family: Arialsans-serif; +
-            font-size: 12px; +
-            line-height: 1.4; +
-            max-width: 800px; +
-            margin: 0 auto; +
-            border: 1px solid #ddd; +
-        } +
- +
-        .report-header { +
-            display: flex; +
-            justify-content: space-between; +
-            align-items: center; +
-            border-bottom: 2px solid #333; +
-            padding-bottom: 10px; +
-            margin-bottom: 20px; +
-        } +
- +
-        .report-header-left { +
-            flex: 1; +
-        } +
- +
-        .report-header-right { +
-            width: 100px; +
-            height: 60px; +
-            background-color: #e8f4f8; +
-            border1px solid #ccc; +
-            display: flex; +
-            align-items: center; +
-            justify-content: center; +
-            font-size: 10px; +
-            color: #666; +
-        } +
- +
-        .report-title { +
-            font-size: 14px+
-            font-weight: bold; +
-            margin-bottom: 5px; +
-        } +
- +
-        .report-subtitle { +
-            font-size11px; +
-            color: #666; +
-            margin-bottom: 15px; +
-        } +
- +
-        .report-section { +
-            margin-bottom: 20px; +
-        } +
- +
-        .report-section-title { +
-            background-color: #333; +
-            color: white; +
-            padding: 5px 10px; +
-            font-weight: bold; +
-            font-size: 12px; +
-            margin-bottom: 0; +
-        } +
- +
-        .report-table +
-            width: 100%; +
-            border-collapse: collapse; +
-            font-size: 11px; +
-        } +
- +
-        .report-table td { +
-            padding3px 8px; +
-            border-bottom: 1px solid #ddd; +
-            vertical-align: top; +
-        } +
- +
-        .report-table .label-col { +
-            width: 200px; +
-            font-weight: normal; +
-        } +
- +
-        .report-table .value-col { +
-            text-align: right; +
-            font-weight: bold; +
-        } +
- +
-        .composition-table { +
-            width: 100%; +
-            border-collapse: collapse; +
-            font-size: 11px; +
-            margin-top: 0; +
-        } +
- +
-        .composition-table th { +
-            background-color: #f0f0f0; +
-            padding: 5px 8px; +
-            text-align: center; +
-            font-weight: bold; +
-            border: 1px solid #ddd; +
-        } +
- +
-        .composition-table td { +
-            padding: 3px 8px; +
-            border: 1px solid #ddd; +
-            text-align: right; +
-        } +
- +
-        .composition-table .component-name-col { +
-            text-align: left !important; +
-            width: 60%; +
-        } +
- +
-        .composition-total { +
-            background-color: #f8f8f8; +
-            font-weight: bold; +
-        } +
- +
-        .elements-table { +
-            width: 100%; +
-            border-collapse: collapse; +
-            font-size: 11px; +
-            margin-top: 0; +
-        } +
- +
-        .elements-table td { +
-            padding: 3px 8px; +
-            border-bottom: 1px solid #ddd; +
-        } +
- +
-        .elements-table .element-name { +
-            width: 200px; +
-        } +
- +
-        .elements-table .element-value { +
-            text-align: right; +
-            font-weight: bold; +
-            width: 80px; +
-        } +
- +
-        .elements-table .element-unit { +
-            text-align: left; +
-            width: 40px; +
-            font-size: 10px; +
-        } +
- +
-        .report-footer { +
-            margin-top: 30px; +
-            padding-top: 10px; +
-            border-top: 1px solid #ddd; +
-            font-size: 10px; +
-            color: #666; +
-            text-align: center; +
-        } +
- +
-        @media print { +
-            .npt-report { +
-                box-shadow: none; +
-                border: none; +
-                margin: 0; +
-                padding: 15px; +
-            } +
-             +
-            .button { +
-                display: none; +
-            } +
-             +
-            .tabs, .tab-content:not(.active) { +
-                displaynone !important;+
             }             }
         }         }
-    </style> +    }, 100); 
-    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script> +}
-    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script> +
-</head> +
-<body>+
  
-<div class="container"> +}
-    <h1>Programma NPT Neonatale v2.0</h1> +
-     +
-    <!-- TAB ORIZZONTALI --> +
-    <div class="tabs"> +
-        <div class="tab active" onclick="showTab('patient-data')"> +
-            <span style="font-size: 18px;">1</span><br>Dati Paziente +
-        </div> +
-        <div class="tab" onclick="showTab('enteral')"> +
-            <span style="font-size: 18px;">2</span><br>Nutrizione Enterale +
-        </div> +
-        <div class="tab" onclick="showTab('nutrition-calc')"> +
-            <span style="font-size: 18px;">3</span><br>Calcolo Fabbisogni +
-        </div> +
-        <div class="tab" onclick="showTab('parenteral')"> +
-            <span style="font-size: 18px;">4</span><br>Nutrizione Parenterale +
-        </div> +
-        <div class="tab" onclick="showTab('config')"> +
-            <span style="font-size: 18px;">5</span><br>Configurazione +
-        </div> +
-    </div>+
  
-    <!-- TAB 1: DATI PAZIENTE --> +// FUNZIONE GENERAZIONE PDF COMPLETA 
-    <div id="patient-data" class="tab-content active"> +function generatePDF(type) { 
-        <div class="info"> +    if (!window.residualNeeds || !patientData.currentWeight{ 
-            <strong>PASSO 1 - DATI PAZIENTE</strong><br> +        alert('Prima calcolare la NPT completa'); 
-            <strong>Obiettivo:</strong> Inserire i dati antropometrici ed ematochimici del neonato +        return;
-        </div> +
-        <div class="section"> +
-            <h2>Dati Prescrizione</h2> +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="prescriptionDate">Data di prescrizione:</label> +
-                        <input type="date" id="prescriptionDate" style="width: 180px;"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="prescribingDoctor">Medico prescrittore:</label> +
-                        <select id="prescribingDoctor" style="width: 200px;"> +
-                            <option value="">Seleziona medico</option> +
-                            <option value="dr_bellu">Dr. Roberto Bellù</option> +
-                            <option value="dr_condo">Dr.ssa Manuela Condò</option> +
-                            <option value="dr_maccioni">Dr.ssa Carla Maccioni</option> +
-                            <option value="dr_meroni">Dr.ssa Federica Meroni</option> +
-                            <option value="dr_calzatini">Dr. Francesco Calzatini</option> +
-                            <option value="dr_ferrari">Dr.ssa Elisabetta Ferrari</option> +
-                        </select> +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <div class="info" style="margin-top: 0; font-size: 13px;"> +
-                        <strong>Info Prescrizione:</strong><br> +
-                        • La data viene impostata automaticamente ad oggi<br> +
-                        • Selezionare il medico responsabile della prescrizione<br> +
-                        • Questi dati appariranno nel riepilogo finale +
-                    </div> +
-                </div> +
-            </div> +
-        </div> +
-         +
-        <div class="section"> +
-            <h2>Dati Paziente</h2> +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="medicalRecord">N° Cartella Clinica:</label> +
-                        <input type="text" id="medicalRecord" maxlength="10" placeholder="2025000001" style="width: 120px; font-family: monospace;"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="birthWeight">Peso alla nascita (g):</label> +
-                        <input type="number" id="birthWeight" min="400" max="5000" value="1000"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="currentWeight">Peso attuale (g):</label> +
-                        <input type="number" id="currentWeight" min="400" max="5000" value="3550"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="daysOfLife">Giorni di vita:</label> +
-                        <input type="number" id="daysOfLife" min="1" max="365" value="9"> +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="bun">BUN - Azotemia (mg/dL):</label> +
-                        <input type="number" id="bun" min="5" max="100" step="1" placeholder="8-25 normale"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="glucose">Glicemia (mg/dL):</label> +
-                        <input type="number" id="glucose" min="40" max="400" step="1" placeholder="70-110 normale"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="sodium">Natremia (mEq/L):</label> +
-                        <input type="number" id="sodium" min="120" max="160" step="1" placeholder="135-145 normale"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="ph">pH ematico:</label> +
-                        <input type="number" id="ph" min="7.0" max="7.6" step="0.01" placeholder="7.35-7.45 normale"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="baseExcess">BE - Base Excess (mEq/L):</label> +
-                        <input type="number" id="baseExcess" min="-15" max="10" step="0.1" placeholder="-4 +2 normale"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="diuresis">Diuresi (mL/kg/die):</label> +
-                        <input type="number" id="diuresis" min="0" max="10" step="0.1" placeholder="1-3 normale"> +
-                    </div> +
-                    <div class="info"> +
-                        <strong>Range Normali:</strong><br> +
-                        <strong>BUN:</strong> 9-14 mg/dL<br> +
-                        <strong>Glicemia:</strong> 70-110 mg/dL<br> +
-                        <strong>Natremia:</strong> 135-145 mEq/L<br> +
-                        <strong>pH:</strong> 7.35-7.45<br> +
-                        <strong>BE:</strong> -4 a +2 mEq/L<br> +
-                        <strong>Diuresi:</strong> 1-3 mL/kg/die +
-                    </div> +
-                </div> +
-            </div> +
-             +
-            <button id="calculatePhaseBtn" class="button calculate-phase-pending" onclick="calculatePhase()">CALCOLA FASE NUTRIZIONALE</button> +
-        </div> +
- +
-        <div id="phaseResults" class="results hidden"> +
-            <h3>Fase Nutrizionale Attuale</h3> +
-            <div id="phaseInfo"></div> +
-        </div> +
-    </div> +
- +
-    <!-- TAB 2: NUTRIZIONE ENTERALE --> +
-    <div id="enteral" class="tab-content"> +
-        <div class="info"> +
-            <strong>PASSO 2 - NUTRIZIONE ENTERALE E LIQUIDI</strong><br> +
-            <strong>Obiettivo:</strong> Calcolare i nutrienti e liquidi forniti dalla nutrizione enterale e altri apporti +
-        </div> +
-         +
-        <div class="section"> +
-            <h2>Altri Liquidi per Via Parenterale o Enterale</h2> +
-            <div class="warning"> +
-                <strong>💧 LIQUIDI AGGIUNTIVI:</strong> Inserire qui liquidi diversi dal latte (soluzioni, farmaci, flebo) +
-            </div> +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="additionalFluids">Volume altri liquidi (ml/die):</label> +
-                        <input type="number" id="additionalFluids" min="0" max="500" value="0" step="5"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="fluidType">Tipo di liquido:</label> +
-                        <select id="fluidType"> +
-                            <option value="saline">Soluzione fisiologica</option> +
-                            <option value="glucose5">Glucosio 5%</option> +
-                            <option value="glucose10">Glucosio 10%</option> +
-                            <option value="drugs">Farmaci in soluzione</option> +
-                            <option value="other">Altri liquidi</option> +
-                        </select> +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="fluidRoute">Via di somministrazione:</label> +
-                        <select id="fluidRoute"> +
-                            <option value="iv">Endovenosa</option> +
-                            <option value="oral">Orale</option> +
-                            <option value="ng">Sonda nasogastrica</option> +
-                        </select> +
-                    </div> +
-                    <div class="info" style="margin-top: 10px; font-size: 12px;"> +
-                        <strong>Esempi:</strong><br> +
-                        • Antibiotici in soluzione<br> +
-                        • Flebo di mantenimento<br> +
-                        • Soluzioni elettrolitiche +
-                    </div> +
-                </div> +
-            </div> +
-        </div> +
-         +
-        <div class="section"> +
-            <h2>Tipo di Latte e Volume</h2> +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="formulaType">Tipo di latte:</label> +
-                        <select id="formulaType" onchange="updateFortifierOptions()"> +
-                            <option value="none">Nessun apporto enterale</option> +
-                            <option value="maternal">Latte materno</option> +
-                            <option value="maternal_fortified">Latte materno + Prenidina FM85</option> +
-                            <option value="nan_supreme">Nestle NAN Supreme Pro 1</option> +
-                            <option value="humana1">Humana 1</option> +
-                            <option value="bbmilk_zero">BBmilk Zero</option> +
-                            <option value="bbmilk_pdf">BBmilk PDF</option> +
-                            <option value="prenan">Nestle PreNan POST</option> +
-                            <option value="alfare">Alfare</option> +
-                            <option value="infatrini">Infatrini</option> +
-                        </select> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="dailyVolume">Volume giornaliero (ml):</label> +
-                        <input type="number" id="dailyVolume" min="0" max="300" value="0"> +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <div id="fortifierSection" class="hidden"> +
-                        <h4>Fortificazione Aggiuntiva</h4> +
-                        <div class="input-group"> +
-                            <label for="fortifierType">Tipo fortificante:</label> +
-                            <select id="fortifierType"> +
-                                <option value="none">Nessun fortificante</option> +
-                            </select> +
-                        </div> +
-                        <div class="input-group"> +
-                            <label for="fortifierConcentration">Concentrazione (%):</label> +
-                            <input type="range" id="fortifierConcentration" min="2" max="6" step="1" value="2" oninput="updateConcentrationDisplay()"> +
-                            <span id="concentrationValue" style="margin-left: 10px; font-weight: bold;">2%</span> +
-                        </div> +
-                    </div> +
-                </div> +
-            </div> +
- +
-            <button id="calculateEnteralBtn" class="button calculate-nutrition-pending" onclick="calculateEnteral()">Calcola Apporti Enterali</button> +
-        </div> +
- +
-        <div id="enteralResults" class="results hidden"> +
-            <h3>Apporti Nutrizionali da Nutrizione Enterale</h3> +
-            <div id="enteralTable"></div> +
-        </div> +
-    </div> +
- +
-    <!-- TAB 3: CALCOLO FABBISOGNI --> +
-    <div id="nutrition-calc" class="tab-content"> +
-        <div class="info"> +
-            <strong>PASSO 3 - DETERMINAZIONE FABBISOGNI</strong><br> +
-            <strong>Obiettivo:</strong> Determinare i fabbisogni nutrizionali totali del neonato +
-        </div> +
-        <div class="section"> +
-            <h2>Determinazione Fabbisogni</h2> +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="targetDay">Giornata di vita:</label> +
-                        <input type="number" id="targetDay" min="1" max="30" value="9" readonly style="background-color: #f0f0f0;"> +
-                    </div> +
-                    <button id="loadDefaultsBtn" class="button load-defaults-pending" onclick="loadNutritionDefaults()">Carica Valori Standard</button> +
-                </div> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="weightCategory">Categoria peso:</label> +
-                        <select id="weightCategory" onchange="updateWeightCategory()"> +
-                            <option value="">Seleziona categoria</option> +
-                            <option value="≤1500g">≤1500g (ELBW/VLBW)</option> +
-                            <option value=">1500g">>1500g (Peso normale)</option> +
-                        </select> +
-                    </div> +
-                    <button id="calculateNutritionBtn" class="button calculate-nutrition-pending" onclick="calculateNutrition()">CALCOLA FABBISOGNI</button> +
-                </div> +
-            </div> +
-             +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="reqLiquids">Liquidi (ml/kg/die):</label> +
-                        <input type="number" id="reqLiquids" min="0" max="250" step="5" value="120"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqProtein">Proteine (g/kg/die):</label> +
-                        <input type="number" id="reqProtein" min="0" max="8" step="0.1" value="3.0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="carbUnit">Unità glucidi:</label> +
-                        <select id="carbUnit" onchange="updateCarbUnit()"> +
-                            <option value="g">g/kg/die</option> +
-                            <option value="mg">mg/kg/min</option> +
-                        </select> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqCarbs" id="carbLabel">Glucidi (g/kg/die):</label> +
-                        <input type="number" id="reqCarbs" min="0" max="20" step="0.1" value="6.0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqLipids">Lipidi (g/kg/die):</label> +
-                        <input type="number" id="reqLipids" min="0" max="5" step="0.1" value="1.0"> +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="reqCalcium">Calcio elementare (mg/kg/die):</label> +
-                        <input type="number" id="reqCalcium" min="0" max="200" step="5" value="0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqPhosphorus">Fosforo (mg/kg/die):</label> +
-                        <input type="number" id="reqPhosphorus" min="0" max="100" step="2" value="0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqMagnesium">Magnesio (mEq/kg/die):</label> +
-                        <input type="number" id="reqMagnesium" min="0" max="10" step="0.1" value="0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqSodium">Sodio (mEq/kg/die):</label> +
-                        <input type="number" id="reqSodium" min="0" max="10" step="0.1" value="0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="sodiumType">Tipo di sodio:</label> +
-                        <select id="sodiumType" onchange="updateSodiumChoice()"> +
-                            <option value="nacl">Sodio Cloruro (NaCl)</option> +
-                            <option value="sodium_acetate">Sodio Acetato (alcalinizzante)</option> +
-                        </select> +
-                    </div> +
-                    <div id="sodiumRecommendation" class="hidden" style="margin-top: 5px;"> +
-                        <!-- Popolato dinamicamente --> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqPotassium">Potassio (mEq/kg/die):</label> +
-                        <input type="number" id="reqPotassium" min="0" max="5" step="0.1" value="0"> +
-                    </div> +
-                </div> +
-            </div> +
-             +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <h4>Vitamine e Oligoelementi (dal 3° giorno)</h4> +
-                    <div class="input-group"> +
-                        <label for="reqVitalipid">Vitalipid (ml/kg/die):</label> +
-                        <input type="number" id="reqVitalipid" min="0" max="10" step="0.5" value="0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqSoluvit">Soluvit (ml/kg/die):</label> +
-                        <input type="number" id="reqSoluvit" min="0" max="5" step="0.5" value="0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqPeditrace">Peditrace (ml/kg/die):</label> +
-                        <input type="number" id="reqPeditrace" min="0" max="10" step="0.5" value="0"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="reqCarnitine">Carnitina (mg/kg/die):</label> +
-                        <input type="number" id="reqCarnitine" min="0" max="20" step="1" value="0"> +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <div class="info" style="margin-top: 0; font-size: 13px;"> +
-                        <strong>Regole Vitamine/Oligoelementi:</strong><br> +
-                        <strong>• Dal 3° giorno:</strong> Vitalipid 4 ml/kg/die, Soluvit 1 ml/kg/die, Peditrace 1 ml/kg/die<br> +
-                        <strong>• Sospensione automatica:</strong> Se enterale ≥100 ml/kg/die<br> +
-                        <strong>• Modificabili manualmente:</strong> Campi editabili per personalizzazione<br><br> +
-                        <strong>Regole Carnitina:</strong><br> +
-                        <strong>• NPT > 1 mese:</strong> Carnitina 5 mg/kg/die<br> +
-                        <strong>• NPT < 1 mese:</strong> Non necessaria<br> +
-                        <strong>• Fonte:</strong> Carnitene (100 mg/ml) +
-                    </div> +
-                </div> +
-            </div> +
-        </div> +
- +
-        <div id="nutritionResults" class="results hidden"> +
-            <h3>Fabbisogni Nutrizionali Totali vs Enterali</h3> +
-            <div id="nutritionTable"></div> +
-        </div> +
-    </div> +
- +
-    <!-- TAB 4: NUTRIZIONE PARENTERALE --> +
-    <div id="parenteral" class="tab-content"> +
-        <div class="info"> +
-            <strong>PASSO 4 - NUTRIZIONE PARENTERALE (FINALE)</strong><br> +
-            <strong>Obiettivo:</strong> Definire la composizione della sacca NPT +
-        </div> +
-        <div class="section"> +
-            <h2>Composizione NPT Automatica</h2> +
-             +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="calculatedTotalVolume">Volume totale (ml):</label> +
-                        <input type="text" id="calculatedTotalVolume" readonly style="background-color: #e8f6f3; font-weight: bold;" value="Premere 'Calcola NPT'"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="suggestedGlucose">Glucosio (%):</label> +
-                        <input type="text" id="suggestedGlucose" readonly style="background-color: #e8f6f3font-weight: bold;" value="Premere 'Calcola NPT'"> +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="calculatedProteinVol">Trophamine (ml):</label> +
-                        <input type="text" id="calculatedProteinVol" readonly style="background-color: #f0f0f0;" value="--"> +
-                    </div> +
-                    <div class="input-group"> +
-                        <label for="calculatedLipidVol">Intralipid (ml):</label> +
-                        <input type="text" id="calculatedLipidVol" readonly style="background-color: #f0f0f0;" value="--"> +
-                    </div> +
-                </div> +
-            </div> +
- +
-            <button id="calculateParenteralBtn" class="button" onclick="calculateParenteral()">CALCOLA NPT AUTOMATICA</button> +
-        </div> +
- +
-        <div id="parenteralResults" class="results hidden"> +
-            <h3>Prescrizione parenterale</h3> +
-            <div id="parenteralTable"></div> +
-             +
-            <h3 style="margin-top: 30px;">Ricetta per Preparazione (include volume deflussore)</h3> +
-            <div id="preparationTable"></div> +
-             +
-            <div style="margin-top: 30px; padding: 15px; background-color: #f0f8ff; border-left: 4px solid #3498db; border-radius: 5px;"> +
-                <h3 style="color: #2c3e50; margin-top: 0;">📋 Report Professionali</h3> +
-                <p style="margin-bottom: 15px;">Genera i report in formato ospedaliero per stampa e archiviazione:</p> +
-                <div style="display: flex; gap: 10px; flex-wrap: wrap;"> +
-                    <button id="generateWorkReportBtn" class="button" onclick="generateAndShowWorkReport()" style="background-color: #27ae60;">Genera Foglio di Lavoro</button> +
-                    <button id="generateFinalReportBtn" class="button" onclick="generateAndShowFinalReport()" style="background-color: #3498db;">Genera Report Parenterale</button> +
-                    <button id="printReportBtn" class="button secondary hidden" onclick="printCurrentReport()" style="margin-left: 10px;">Stampa Report Attivo</button> +
-                    <button id="savePdfBtn" class="button hidden" onclick="saveReportAsPDF()" style="background-color: #e74c3c; margin-left: 10px;">💾 Salva PDF</button> +
-                </div> +
-            </div> +
-             +
-            <div id="nptWorkReport" class="hidden" style="margin-top: 20px;"></div> +
-            <div id="nptFinalReport" class="hidden" style="margin-top: 20px;"></div> +
-        </div> +
-    </div> +
- +
-    <!-- TAB 5: CONFIGURAZIONE --> +
-    <div id="config" class="tab-content"> +
-        <div class="info"> +
-            <strong>CONFIGURAZIONE COMPONENTI</strong><br> +
-            <strong>Sistema:</strong> NPT Calculator v2.0 - Database completo componenti nutrizionali +
-        </div> +
-         +
-        <div class="section"> +
-            <h2>Parametri Sistema</h2> +
-            <div class="form-row"> +
-                <div class="form-col"> +
-                    <div class="input-group"> +
-                        <label for="deflectorVolume">Volume deflussore (ml):</label> +
-                        <input type="number" id="deflectorVolume" min="0" max="100" step="5" value="30"> +
-                    </div> +
-                    <div class="info" style="margin-top: 10px; font-size: 12px;"> +
-                        <strong>Info Volume Deflussore:</strong><br> +
-                        • Volume perso nel deflussore durante la preparazione<br> +
-                        • Viene aggiunto automaticamente alla ricetta di preparazione<br> +
-                        • Valore standard: 30 ml (modificabile) +
-                    </div> +
-                </div> +
-                <div class="form-col"> +
-                    <button id="updateSystemBtn" class="button" onclick="updateSystemConfig()">Aggiorna Parametri Sistema</button> +
-                </div> +
-            </div> +
-        </div> +
- +
-        <div class="section"> +
-            <h2>Formule Enterali (Valori per 100ml)</h2> +
-            <div style="overflow-x: auto;"> +
-                <table class="results-table" style="font-size: 12px;"> +
-                    <thead> +
-                        <tr> +
-                            <th style="min-width: 180px;">Formula</th> +
-                            <th>Proteine<br>(g)</th> +
-                            <th>Carboidrati<br>(g)</th> +
-                            <th>Lipidi<br>(g)</th> +
-                            <th>Sodio<br>(mEq)</th> +
-                            <th>Potassio<br>(mEq)</th> +
-                            <th>Calcio<br>(mg)</th> +
-                            <th>Fosforo<br>(mg)</th> +
-                            <th>Magnesio<br>(mg)</th> +
-                            <th>Energia<br>(kcal)</th> +
-                        </tr> +
-                    </thead> +
-                    <tbody> +
-                        <tr> +
-                            <td><strong>Latte Materno</strong></td> +
-                            <td>1.2</td> +
-                            <td>7.0</td> +
-                            <td>4.0</td> +
-                            <td>0.007</td> +
-                            <td>0.035</td> +
-                            <td>28.0</td> +
-                            <td>15.0</td> +
-                            <td>3.0</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Latte Materno + Prenidina FM85</strong></td> +
-                            <td>2.6</td> +
-                            <td>7.4</td> +
-                            <td>4.25</td> +
-                            <td>0.009</td> +
-                            <td>0.050</td> +
-                            <td>63.0</td> +
-                            <td>35.0</td> +
-                            <td>4.5</td> +
-                            <td>87</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Nestle NAN Supreme Pro 1</strong></td> +
-                            <td>1.3</td> +
-                            <td>7.6</td> +
-                            <td>3.5</td> +
-                            <td>0.024</td> +
-                            <td>0.075</td> +
-                            <td>44.1</td> +
-                            <td>24.4</td> +
-                            <td>6.56</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Humana 1</strong></td> +
-                            <td>1.4</td> +
-                            <td>7.6</td> +
-                            <td>3.2</td> +
-                            <td>0.020</td> +
-                            <td>0.070</td> +
-                            <td>59.0</td> +
-                            <td>33.0</td> +
-                            <td>5.0</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>BBmilk Zero</strong></td> +
-                            <td>1.8</td> +
-                            <td>7.8</td> +
-                            <td>3.6</td> +
-                            <td>0.022</td> +
-                            <td>0.075</td> +
-                            <td>65.0</td> +
-                            <td>36.0</td> +
-                            <td>6.0</td> +
-                            <td>70</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>BBmilk PDF</strong></td> +
-                            <td>1.7</td> +
-                            <td>7.9</td> +
-                            <td>3.7</td> +
-                            <td>0.025</td> +
-                            <td>0.078</td> +
-                            <td>68.0</td> +
-                            <td>38.0</td> +
-                            <td>6.5</td> +
-                            <td>71</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Nestle PreNan POST</strong></td> +
-                            <td>2.0</td> +
-                            <td>8.2</td> +
-                            <td>4.0</td> +
-                            <td>0.030</td> +
-                            <td>0.085</td> +
-                            <td>75.0</td> +
-                            <td>42.0</td> +
-                            <td>7.5</td> +
-                            <td>73</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Alfare</strong></td> +
-                            <td>1.9</td> +
-                            <td>7.1</td> +
-                            <td>3.4</td> +
-                            <td>0.015</td> +
-                            <td>0.050</td> +
-                            <td>52.0</td> +
-                            <td>35.0</td> +
-                            <td>5.5</td> +
-                            <td>67</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Infatrini</strong></td> +
-                            <td>2.6</td> +
-                            <td>10.8</td> +
-                            <td>5.4</td> +
-                            <td>0.028</td> +
-                            <td>0.082</td> +
-                            <td>85.0</td> +
-                            <td>58.0</td> +
-                            <td>9.2</td> +
-                            <td>101</td> +
-                        </tr> +
-                    </tbody> +
-                </table> +
-            </div> +
-            <div class="info" style="margin-top: 15px;"> +
-                <strong>ℹ️ Informazioni:</strong> Questi valori sono configurati nel database e vengono utilizzati per i calcoli nutrizionali. Sono basati su letteratura e schede tecniche ufficiali. +
-            </div> +
-        </div> +
- +
-        <div class="section"> +
-            <h2>Componenti Parenterali (Valori per 100ml)</h2> +
-            <div style="overflow-x: auto;"> +
-                <table class="results-table" style="font-size: 12px;"> +
-                    <thead> +
-                        <tr> +
-                            <th style="min-width: 200px;">Componente</th> +
-                            <th>Calcio<br>(mg)</th> +
-                            <th>Fosforo<br>(mg)</th> +
-                            <th>Magnesio<br>(mEq)</th> +
-                            <th>Sodio<br>(mEq)</th> +
-                            <th>Potassio<br>(mEq)</th> +
-                            <th style="min-width: 250px;">Descrizione</th> +
-                        </tr> +
-                    </thead> +
-                    <tbody> +
-                        <tr> +
-                            <td><strong>Calcio Gluconato 10%</strong></td> +
-                            <td>840</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>1g/10mL, 0.44 mEq/mL - Sale di calcio organico</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Esafosfina</strong></td> +
-                            <td>0</td> +
-                            <td>1600</td> +
-                            <td>0</td> +
-                            <td>130</td> +
-                            <td>0</td> +
-                            <td>5g/50mL - Glicerofosfato di sodio</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Magnesio Solfato</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>800</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>2g/10mL, 1.6 mEq/mL - Elettrolita essenziale</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Sodio Cloruro</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>1000</td> +
-                            <td>0</td> +
-                            <td>3mEq/mL - Prima scelta per sodio</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Sodio Acetato</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>667</td> +
-                            <td>0</td> +
-                            <td>2 mEq/mL - Alcalinizzante per acidosi</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Potassio Cloruro</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>1000</td> +
-                            <td>2 mEq/mL - Max vel. 0.5 mEq/kg/h</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Trophamine 6%</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>Aminoacidi pediatrici - 6g/100mL</td> +
-                        </tr> +
-                        <tr> +
-                            <td><strong>Intralipid 20%</strong></td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>0</td> +
-                            <td>Emulsione lipidica - 20g/100mL</td> +
-                        </tr> +
-                    </tbody> +
-                </table> +
-            </div> +
-            <div class="info" style="margin-top: 15px;"> +
-                <strong>ℹ️ Informazioni:</strong> Concentrazioni standard utilizzate per i calcoli elettrolitici. I valori sono basati su preparazioni farmaceutiche standard. +
-            </div> +
-        </div> +
- +
-        <div class="section"> +
-            <h2>Lista Medici Prescrittori</h2> +
-            <div class="info" style="margin-bottom: 15px;"> +
-                <strong>🩺 Database Medici:</strong> Lista dei medici autorizzati alla prescrizione NPT. Questi nomi appaiono nella dropdown del TAB 1. +
-            </div> +
-            <div style="overflow-x: auto;"> +
-                <table class="results-table" style="font-size: 12px;"> +
-                    <thead> +
-                        <tr> +
-                            <th>Nome</th> +
-                            <th>Cognome</th> +
-                            <th>Titolo</th> +
-                            <th>Nome Completo (Visualizzato)</th> +
-                        </tr> +
-                    </thead> +
-                    <tbody> +
-                        <tr><td>Roberto</td><td>Bellù</td><td>Dr.</td><td><strong>Dr. Roberto Bellù</strong></td></tr> +
-                        <tr><td>Manuela</td><td>Condò</td><td>Dr.ssa</td><td><strong>Dr.ssa Manuela Condò</strong></td></tr> +
-                        <tr><td>Carla</td><td>Maccioni</td><td>Dr.ssa</td><td><strong>Dr.ssa Carla Maccioni</strong></td></tr> +
-                        <tr><td>Federica</td><td>Meroni</td><td>Dr.ssa</td><td><strong>Dr.ssa Federica Meroni</strong></td></tr> +
-                        <tr><td>Francesco</td><td>Calzatini</td><td>Dr.</td><td><strong>Dr. Francesco Calzatini</strong></td></tr> +
-                        <tr><td>Elisabetta</td><td>Ferrari</td><td>Dr.ssa</td><td><strong>Dr.ssa Elisabetta Ferrari</strong></td></tr> +
-                    </tbody> +
-                </table> +
-            </div> +
-        </div> +
- +
-        <div class="section"> +
-            <h2>Informazioni Sistema</h2> +
-            <div class="info"> +
-                <strong>📊 NPT Calculator v2.0 - Stato Sistema</strong><br> +
-                <strong>• Database Formule:</strong> 9 formule enterali configurate<br> +
-                <strong>• Database Componenti:</strong> 8 componenti parenterali configurati<br> +
-                <strong>• Medici Prescrittori:</strong> 6 medici autorizzati<br> +
-                <strong>• Algoritmi:</strong> Calcoli BUN, fasi nutrizionali, elettroliti automatici<br> +
-                <strong>• Report:</strong> Foglio di lavoro + Report parenterale completo<br> +
-                <strong>• Ultimo Aggiornamento:</strong> Luglio 2025 +
-            </div> +
-        </div> +
-    </div> +
-</div> +
- +
-<script> +
-// DATI NUTRIZIONALI COMPLETI +
-const formulaData = { +
-    maternal: { name: "Latte Materno", protein: 1.2, carbs: 7.0, lipids: 4.0, sodium: 0.007, potassium: 0.035, calcium: 28.0, phosphorus: 15.0, magnesium: 3.0, energy: 67 }, +
-    maternal_fortified: { name: "Latte Materno + Prenidina FM85", protein: 2.6, carbs: 7.4, lipids: 4.25, sodium: 0.009, potassium: 0.050, calcium: 63.0, phosphorus: 35.0, magnesium: 4.5, energy: 87 }, +
-    nan_supreme: { name: "Nestle NAN Supreme Pro 1", protein: 1.3, carbs: 7.6, lipids: 3.5, sodium: 0.024, potassium: 0.0745, calcium: 44.1, phosphorus: 24.4, magnesium: 6.56, energy: 67 }, +
-    humana1: { name: "Humana 1", protein: 1.4, carbs: 7.6, lipids: 3.2, sodium: 0.020, potassium: 0.070, calcium: 59.0, phosphorus: 33.0, magnesium: 5.0, energy: 67 }, +
-    bbmilk_zero: { name: "BBmilk Zero", protein: 1.8, carbs: 7.8, lipids: 3.6, sodium: 0.022, potassium: 0.075, calcium: 65.0, phosphorus: 36.0, magnesium: 6.0, energy: 70 }, +
-    bbmilk_pdf: { name: "BBmilk PDF", protein: 1.7, carbs: 7.9, lipids: 3.7, sodium: 0.025, potassium: 0.078, calcium: 68.0, phosphorus: 38.0, magnesium: 6.5, energy: 71 }, +
-    prenan: { name: "Nestle PreNan POST", protein: 2.0, carbs: 8.2, lipids: 4.0, sodium: 0.030, potassium: 0.085, calcium: 75.0, phosphorus: 42.0, magnesium: 7.5, energy: 73 }, +
-    alfare: { name: "Alfare", protein: 1.9, carbs: 7.1, lipids: 3.4, sodium: 0.015, potassium: 0.050, calcium: 52.0, phosphorus: 35.0, magnesium: 5.5, energy: 67 }, +
-    infatrini: { name: "Infatrini", protein: 2.6, carbs: 10.8, lipids: 5.4, sodium: 0.028, potassium: 0.082, calcium: 85.0, phosphorus: 58.0, magnesium: 9.2, energy: 101 } +
-}; +
- +
-// CONFIGURAZIONI PARENTERALI COMPLETE +
-const parenteralConfig = { +
-    ca_gluconato:+
-        name: "Calcio Gluconato 10%", +
-        calcium: 840, phosphorus: 0, magnesium: 0, sodium: 0, potassium: 0, +
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 90 +
-    }, +
-    esafosfina: { +
-        name: "Esafosfina", +
-        calcium: 0, phosphorus: 1600, magnesium: 0, sodium: 130, potassium: 0, +
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 98 +
-    }, +
-    mg_sulfate: { +
-        name: "Magnesio Solfato", +
-        calcium: 0, phosphorus: 0, magnesium: 800, sodium: 0, potassium: 0, +
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 99 +
-    }, +
-    nacl: { +
-        name: "Sodio Cloruro", +
-        calcium: 0, phosphorus: 0, magnesium: 0, sodium: 1000, potassium: 0, +
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 99 +
-    }, +
-    sodium_acetate:+
-        name: "Sodio Acetato", +
-        calcium: 0, phosphorus: 0, magnesium: 0, sodium: 667, potassium: 0, +
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 99 +
-    }, +
-    kcl: { +
-        name: "Potassio Cloruro", +
-        calcium: 0, phosphorus: 0, magnesium: 0, sodium: 0, potassium: 1000, +
-        protein: 0, carbs: 0, lipids: 0, energy: 0, water: 99+
     }     }
-}; 
  
-// Database medici +    const { jsPDF } = window.jspdf
-const doctorsData = { +    const doc = new jsPDF();
-    dr_bellu: { name: "Roberto", surname: "Bellù", title: "Dr.", fullName: "Dr. Roberto Bellù" }+
-    dr_condo: { name: "Manuela", surname: "Condò", title: "Dr.ssa", fullName: "Dr.ssa Manuela Condò" }, +
-    dr_maccioni: { name: "Carla", surname: "Maccioni", title: "Dr.ssa", fullName: "Dr.ssa Carla Maccioni" }, +
-    dr_meroni: { name: "Federica", surname: "Meroni", title: "Dr.ssa", fullName: "Dr.ssa Federica Meroni" }, +
-    dr_calzatini: { name: "Francesco", surname: "Calzatini", title: "Dr.", fullName: "Dr. Francesco Calzatini" }, +
-    dr_ferrari: { name: "Elisabetta", surname: "Ferrari", title: "Dr.ssa", fullName: "Dr.ssa Elisabetta Ferrari"+
-}; +
- +
-// VARIABILI GLOBALI +
-let patientData {}; +
-let enteralData = null; +
-window.currentActiveReport = null; +
- +
-// INIZIALIZZAZIONE +
-document.addEventListener('DOMContentLoaded', function() { +
-    // Imposta data odierna +
-    const today = new Date().toISOString().split('T')[0]; +
-    document.getElementById('prescriptionDate').value = today; +
-}); +
- +
-// FUNZIONE TAB +
-function showTab(tabId) { +
-    // Rimuovi classe active da tutti i contenuti +
-    document.querySelectorAll('.tab-content').forEach(content => { +
-        content.classList.remove('active'); +
-    });+
          
-    // Rimuovi classe active da tutte le tab +    // INTESTAZIONE COMUNE 
-    document.querySelectorAll('.tab').forEach(tab => { +    doc.setFontSize(10); 
-        tab.classList.remove('active'); +    doc.text(clinicalConfig.departmentName, 20, 15); 
-    });+    doc.text('Direttore: ' + clinicalConfig.directorName, 20, 20);
          
-    // Mostra il contenuto selezionato +    // Logo ASST (posizionamento approssimativo) 
-    const targetContent document.getElementById(tabId); +    doc.text(clinicalConfig.hospitalName, 170, 20); 
-    if (targetContent) { +     
-        targetContent.classList.add('active');+    const currentDate new Date().toLocaleDateString('it-IT'); 
 +    doc.text('CALCOLO NUTRIZIONALE PARENTERALE Data: ' + currentDate, 20, 35); 
 +     
 +    if (type === 'foglio_lavoro') { 
 +        generateWorksheetPDFContent(doc); 
 +    } else if (type === 'report_parenterale') { 
 +        generatePrescriptionPDFContent(doc); 
 +    } else if (type === 'etichetta_sacca') { 
 +        generateLabelPDFContent(doc); 
 +    } 
 +     
 +    // Salva il PDF 
 +    let fileName = ''; 
 +    switch(type) { 
 +        case 'foglio_lavoro': 
 +            fileName = 'Foglio_Lavoro_NPT_' + currentDate.replace(/\//g, '-') + '.pdf'; 
 +            break; 
 +        case 'report_parenterale': 
 +            fileName = 'Report_Parenterale_NPT_' + currentDate.replace(/\//g, '-'+ '.pdf'; 
 +            break; 
 +        case 'etichetta_sacca': 
 +            fileName = 'Etichetta_Sacca_NPT_' + currentDate.replace(/\//g, '-') + '.pdf'; 
 +            break; 
 +        default: 
 +            fileName = 'NPT_Document.pdf';
     }     }
          
-    // Attiva la tab cliccata +    doc.save(fileName);
-    event.target.closest('.tab').classList.add('active');+
 } }
- +// CONTENUTO PDF PRESCRIZIONE MEDICA 
-// FUNZIONE CALCOLO FASE +function generatePrescriptionPDFContent(doc) { 
-function calculatePhase() { +    const currentDate new Date().toLocaleDateString('it-IT'); 
-    const medicalRecord document.getElementById('medicalRecord').value; +    const calc window.nptCalculation
-    const birthWeight = parseInt(document.getElementById('birthWeight').value); +    const prescriptionPatientWeightKg patientData.currentWeight / 1000;
-    const currentWeight parseInt(document.getElementById('currentWeight').value)+
-    const daysOfLife parseInt(document.getElementById('daysOfLife').value); +
-    const bun = document.getElementById('bun').value; +
-    const glucose = document.getElementById('glucose').value; +
-    const sodium = document.getElementById('sodium').value; +
-    const ph = document.getElementById('ph').value; +
-    const baseExcess = document.getElementById('baseExcess').value; +
-    const diuresis = document.getElementById('diuresis').value; +
-    const prescriptionDate = document.getElementById('prescriptionDate').value; +
-    const prescribingDoctor = document.getElementById('prescribingDoctor').value;+
          
-    patientData { +    // Recupera il medico attualmente selezionato 
-        medicalRecord: medicalRecord, +    const currentPrescribingDoctor document.getElementById('prescribingDoctor').value; 
-        birthWeightbirthWeight,  +    const doctorName = currentPrescribingDoctor && doctorsData[currentPrescribingDoctor] ?  
-        currentWeight: currentWeight,  +                  doctorsData[currentPrescribingDoctor].fullName :  
-        daysOfLife: daysOfLife, +                  (patientData.prescribingDoctorName || 'Non specificato');
-        bun: bun, +
-        glucose: glucose, +
-        sodium: sodium, +
-        ph: ph, +
-        baseExcess: baseExcess, +
-        diuresis: diuresis, +
-        prescriptionDate: prescriptionDate, +
-        prescribingDoctor: prescribingDoctor +
-    };+
          
-    document.getElementById('targetDay').value = daysOfLife;+    const birthDate = new Date(); 
 +    birthDate.setDate(birthDate.getDate() - patientData.daysOfLife);
          
-    let phase daysOfLife <= 5 ? 'Transizione' : daysOfLife <= 14 ? 'Stabilizzazione' : 'Crescita'+    if (!window.currentPrescriptionID) { 
-    let bunStatus = ''; +        window.currentPrescriptionID generatePreparationID()
-    let bunWarning '';+    } 
 +    const prescriptionID window.currentPrescriptionID;
          
-    // Analisi BUN +    let yPos = 50; 
-    if (bun && bun !== ''{ +     
-        const bunValue parseFloat(bun)+    doc.setFontSize(12); 
-        if (bunValue < 9{ +    doc.text('REPORT PARENTERALE', 20, yPos); 
-            bunStatus = 'Basso - Aumentare proteine'; +    yPos +20
-            bunWarning = 'BUN bassoconsiderare aumento proteine'; +     
-        } else if (bunValue > 14) { +    doc.setFontSize(10); 
-            bunStatus = 'Elevato - Ridurre proteine'; +    doc.text('Paziente: + (patientData.medicalRecord || 'N/A'), 20, yPos)
-            bunWarning = 'BUN elevatoridurre proteine'; +    yPos +10; 
-        } else { +    doc.text('Peso: ' + patientData.currentWeight + 'g', 20, yPos)
-            bunStatus 'Normale (9-14 mg/dL)'+    yPos +10; 
-        } +    doc.text('Giorni di vita: + patientData.daysOfLife, 20, yPos)
-    } else +    yPos +10; 
-        bunStatus = 'Non inserito';+    doc.text('Medico: ' + doctorName, 20, yPos)
 +    yPos +20
 +     
 +    if (prescriptionID) 
 +        doc.text('ID Prescrizione: + prescriptionID, 20, yPos); 
 +        yPos += 10;
     }     }
          
-    let phaseInfoHtml = '<div class="phase-indicator phase-' + phase.toLowerCase() + '">' + phase + '</div>'; +    // COMPOSIZIONE NPT 
-    phaseInfoHtml += '<div class="form-row" style="margin-top15px;">'; +    doc.text('COMPOSIZIONE NPT:', 20, yPos); 
-    phaseInfoHtml += '<div class="form-col">'+    yPos += 15; 
-    phaseInfoHtml +'<h4>Dati Paziente</h4>'; +     
-    if (medicalRecord) { +    doc.text('Volume totale NPT: ' + calc.totalVolume + ' ml', 20, yPos)
-        phaseInfoHtml += '<p><strong>Cartella:</strong> ' + medicalRecord + '</p>';+    yPos += 10; 
 +    doc.text('GIR: ' + calc.gir.toFixed(1) + ' mg/kg/min', 20, yPos)
 +    yPos += 10
 +    doc.text('Velocità infusione: ' + (calc.totalVolume / 24).toFixed(2) + ' ml/h', 20, yPos); 
 +    yPos += 10; 
 +     
 +    if (calc.osmolarityData) { 
 +        doc.text('Osmolarità: ' + calc.osmolarityData.total + ' mOsm/L', 20, yPos); 
 +        yPos += 10;
     }     }
-    phaseInfoHtml += '<p><strong>Peso:</strong> ' + currentWeight + 'g (nascita: ' + birthWeight + 'g)</p>'; 
-    phaseInfoHtml += '<p><strong>Giorni di vita:</strong> ' + daysOfLife + '</p>'; 
-    phaseInfoHtml += '<p><strong>Fase nutrizionale:</strong> ' + phase + '</p>'; 
-    phaseInfoHtml += '</div>'; 
-    phaseInfoHtml += '<div class="form-col">'; 
-    phaseInfoHtml += '<h4>Esami Ematochimici</h4>'; 
-    if (patientData.bun) { 
-        phaseInfoHtml += '<p><strong>BUN:</strong> ' + patientData.bun + ' mg/dL (' + bunStatus + ')</p>'; 
-    } 
-    phaseInfoHtml += '</div>'; 
-    phaseInfoHtml += '</div>'; 
          
-    if (bunWarning) { +    // Componenti principali 
-        phaseInfoHtml += '<div class="info"><strong>Nota BUN:</strong> ' + bunWarning + '</div>';+    yPos += 10; 
 +    doc.text('COMPONENTI PRINCIPALI:', 20, yPos); 
 +    yPos += 15; 
 +     
 +    if (calc.neededGlucose > 0) { 
 +        doc.text('Glucosio 50%: ' + calc.glucose50Volume.toFixed(1) + ' ml', 20, yPos); 
 +        yPos += 8;
     }     }
          
-    phaseInfoHtml += '<div class="info"><strong>Prossimo passo:</strong> Vai al TAB 2 per la nutrizione enterale</div>';+    doc.text('Trophamine 6%: ' + calc.proteinVolume.toFixed(1) + ' ml', 20, yPos); 
 +    yPos += 8; 
 +    doc.text('Intralipid 20%: ' + calc.lipidVolume.toFixed(1) + ' ml', 20, yPos); 
 +    yPos +8; 
 +    doc.text('Acqua Bidistillata: ' + calc.waterVolume.toFixed(1) + ' ml', 20, yPos); 
 +    yPos += 15;
          
-    document.getElementById('phaseInfo').innerHTML = phaseInfoHtml+    // Fabbisogni per kg 
-    document.getElementById('phaseResults').classList.remove('hidden');+    const totalProteinPerKg = (enteralData ? enteralData.protein : 0+ window.residualNeeds.protein
 +    const totalLipidsPerKg = (enteralData ? enteralData.lipids : 0+ window.residualNeeds.lipids; 
 +    const totalCarbsPerKg = (enteralData ? enteralData.carbs : 0+ window.residualNeeds.carbs; 
 +    const totalEnergyPerKg = window.residualNeeds.totalEnergyRequirement;
          
-    document.getElementById('calculatePhaseBtn').className = 'button config-update-completed'; +    doc.text('FABBISOGNI PER KG/DIE:', 20, yPos)
-    document.getElementById('calculatePhaseBtn').innerHTML = 'FASE CALCOLATA ✓'; +    yPos +15; 
-     +    doc.text('Proteine: + totalProteinPerKg.toFixed(2) + ' g/kg/die', 20, yPos)
-    updateSodiumRecommendation();+    yPos += 8; 
 +    doc.text('Lipidi: + totalLipidsPerKg.toFixed(2) + ' g/kg/die', 20, yPos); 
 +    yPos +8; 
 +    doc.text('Glucidi: + totalCarbsPerKg.toFixed(2) + ' g/kg/die', 20, yPos)
 +    yPos += 8; 
 +    doc.text('Energia: ' + totalEnergyPerKg.toFixed(0) + ' kcal/kg/die', 20, yPos);
 } }
  
-function updateSodiumRecommendation() { +// CONTENUTO PDF FOGLIO DI LAVORO 
-    // Implementazione vuota per ora +function generateWorksheetPDFContent(doc) { 
-+    const calc window.nptCalculation
- +     
-// FUNZIONE FORTIFICANTE +    let yPos 50;
-function updateFortifierOptions() { +
-    const formulaType document.getElementById('formulaType').value+
-    const fortifierSection document.getElementById('fortifierSection');+
          
-    if (formulaType === 'maternal'{ +    doc.setFontSize(12); 
-        fortifierSection.classList.remove('hidden'); +    doc.text('FOGLIO DI LAVORO NPT', 20, yPos); 
-    } else { +    yPos += 20; 
-        fortifierSection.classList.add('hidden'); +     
-    } +    doc.setFontSize(10); 
-} +    doc.text('Paziente: ' + (patientData.medicalRecord || 'N/A'), 20, yPos); 
- +    yPos += 10; 
-function updateConcentrationDisplay() { +    doc.text('Peso: + patientData.currentWeight + 'g', 20, yPos); 
-    const concentration = document.getElementById('fortifierConcentration').value; +    yPos += 10; 
-    document.getElementById('concentrationValue').textContent concentration + '%'; +    doc.text('Giorni di vita: ' + patientData.daysOfLife, 20, yPos); 
-} +    yPos += 20; 
- +     
-// FUNZIONE CALCOLO ENTERALE +    doc.text('PREPARAZIONE NPT:', 20, yPos)
-function calculateEnteral() { +    yPos += 15; 
-    if (!patientData.birthWeight) { +     
-        alert('Prima inserire i dati del paziente nel TAB 1'); +    const deflectorVolume parseInt(document.getElementById('deflectorVolume').value) || 30
-        return;+    const ratio = (calc.totalVolume + deflectorVolume) / calc.totalVolume; 
 +     
 +    doc.text('Volume prescrizione: + calc.totalVolume + ' ml', 20, yPos); 
 +    yPos +8; 
 +    doc.text('Volume deflussore: +' + deflectorVolume + ml', 20, yPos)
 +    yPos += 8; 
 +    doc.text('Volume totale preparazione: ' + (calc.totalVolume + deflectorVolume) + ' ml', 20, yPos); 
 +    yPos += 15; 
 +     
 +    doc.text('COMPONENTI DA PREPARARE:', 20, yPos)
 +    yPos += 15; 
 +     
 +    if (calc.neededGlucose > 0) { 
 +        doc.text('Glucosio 50%: ' + (calc.glucose50Volume * ratio).toFixed(1) + ml', 20, yPos); 
 +        yPos += 8;
     }     }
          
-    const formulaType = document.getElementById('formulaType').value+    doc.text('Trophamine 6%: + (calc.proteinVolume * ratio).toFixed(1) + ' ml', 20, yPos)
-    const dailyVolume parseFloat(document.getElementById('dailyVolume').value); +    yPos +8; 
-    const additionalFluids parseFloat(document.getElementById('additionalFluids').value|| 0;+    doc.text('Intralipid 20%: + (calc.lipidVolume * ratio).toFixed(1) + ' ml', 20, yPos); 
 +    yPos +8; 
 +    doc.text('Acqua Bidistillata: + (calc.waterVolume * ratio).toFixed(1+ ' ml', 20, yPos); 
 +    yPos += 15;
          
-    const currentWeight = patientData.currentWeight; +    if (calc.electrolyteAdditions.ca_gluconato > 0) { 
-    const totalFluids = dailyVolume additionalFluids+        doc.text('Calcio Gluconato: ' (calc.electrolyteAdditions.ca_gluconato * ratio).toFixed(1) + ' ml', 20, yPos)
-    const totalFluidsPerKg (totalFluids / currentWeight) * 1000;+        yPos +8; 
 +    }
          
-    if (formulaType === 'none' || dailyVolume === 0) { +    if (calc.electrolyteAdditions.esafosfina > 0) { 
-        enteralData = {  +        doc.text('Esafosfina: ' + (calc.electrolyteAdditions.esafosfina * ratio).toFixed(1) + ' ml', 20, yPos); 
-            volume: dailyVolume,  +        yPos += 8;
-            additionalFluids: additionalFluids, +
-            totalFluids: totalFluids, +
-            protein: 0, carbs: 0, lipids: 0, energy: 0, +
-            sodium: 0, potassium: 0, calcium: 0, phosphorus: 0, magnesium: 0 +
-        }; +
-         +
-        let tableHtml = '<div class="info">'; +
-        if (additionalFluids > 0) { +
-            tableHtml += '<strong>⚠️ Solo liquidi aggiuntivi:</strong> ' + additionalFluids + ' ml (' + ((additionalFluids/currentWeight)*1000).toFixed(1) + ' ml/kg/die)<br>'; +
-            tableHtml += '<strong>Nessun apporto nutrizionale dal latte</strong>'; +
-        } else { +
-            tableHtml += 'Nessun apporto enterale'; +
-        } +
-        tableHtml += '</div>'; +
-         +
-        document.getElementById('enteralTable').innerHTML = tableHtml; +
-    } else { +
-        const formula = formulaData[formulaType]; +
-        const volumePerKg = (dailyVolume / currentWeight) * 1000; +
-         +
-        enteralData = { +
-            volumedailyVolume, +
-            additionalFluids: additionalFluids, +
-            totalFluids: totalFluids, +
-            protein: (dailyVolume * formula.protein / 100) / (currentWeight / 1000), +
-            carbs: (dailyVolume * formula.carbs / 100) / (currentWeight / 1000), +
-            lipids: (dailyVolume * formula.lipids / 100) / (currentWeight / 1000), +
-            energy: (dailyVolume * formula.energy / 100) / (currentWeight / 1000), +
-            sodium: (dailyVolume * formula.sodium / 100) / (currentWeight / 1000), +
-            potassium: (dailyVolume * formula.potassium / 100) / (currentWeight / 1000), +
-            calcium: (dailyVolume * formula.calcium / 100) / (currentWeight / 1000), +
-            phosphorus: (dailyVolume * formula.phosphorus / 100) / (currentWeight / 1000), +
-            magnesium: (dailyVolume * formula.magnesium / 100) / (currentWeight / 1000) +
-        }; +
-         +
-        let tableHtml = '<div class="info">'; +
-        tableHtml += '<strong>Formula:</strong> ' + formula.name + '<br>'; +
-        tableHtml += '<strong>Volume latte:</strong> ' + dailyVolume + ' ml (' + volumePerKg.toFixed(1) + ' ml/kg/die)<br>'; +
-        if (additionalFluids > 0) { +
-            tableHtml += '<strong>Altri liquidi:</strong> ' + additionalFluids + ' ml<br>'; +
-            tableHtml += '<strong>💧 TOTALE LIQUIDI:</strong> ' + totalFluids + ' ml (' + totalFluidsPerKg.toFixed(1+ ' ml/kg/die)'; +
-        } else { +
-            tableHtml += '<strong>Liquidi totali:</strong> ' + totalFluids + ' ml (' + totalFluidsPerKg.toFixed(1) + ' ml/kg/die)'+
-        } +
-        tableHtml += '</div>'; +
-         +
-        tableHtml += '<table class="results-table">'; +
-        tableHtml += '<tr><th>Nutriente</th><th>Per 100ml</th><th>Per kg/die</th><th>Unita</th></tr>'; +
-        tableHtml += '<tr><td>Proteine</td><td>' + formula.protein.toFixed(1+ '</td><td>' + enteralData.protein.toFixed(1) + '</td><td>g</td></tr>'+
-        tableHtml += '<tr><td>Carboidrati</td><td>' + formula.carbs.toFixed(1) + '</td><td>' + enteralData.carbs.toFixed(1) + '</td><td>g</td></tr>'; +
-        tableHtml += '<tr><td>Lipidi</td><td>' + formula.lipids.toFixed(1) + '</td><td>' + enteralData.lipids.toFixed(1) + '</td><td>g</td></tr>'; +
-        tableHtml += '<tr class="energy-highlight"><td><strong>Energia</strong></td><td><strong>' + formula.energy.toFixed(0) + '</strong></td><td><strong>' + enteralData.energy.toFixed(0) + '</strong></td><td><strong>kcal</strong></td></tr>'; +
-        tableHtml += '</table>'; +
-         +
-        document.getElementById('enteralTable').innerHTML = tableHtml;+
     }     }
          
-    document.getElementById('enteralResults').classList.remove('hidden');+    doc.text('Velocità infusione: + (calc.totalVolume / 24).toFixed(2) + ml/h', 20, yPos)
 +    yPos += 8;
          
-    const enteralBtn = document.getElementById('calculateEnteralBtn'); +    if (calc.osmolarityData) { 
-    if (enteralBtn) { +        doc.text('Osmolarità: + calc.osmolarityData.total + ' mOsm/L', 20, yPos); 
-        enteralBtn.className 'button config-update-completed'+        if (calc.osmolarityData.isHypertonic) { 
-        enteralBtn.innerHTML = 'Apporti Enterali Calcolati ✓';+            yPos +8
 +            doc.text('ATTENZIONE: SOLO ACCESSO VENOSO CENTRALE', 20, yPos); 
 +        }
     }     }
 } }
  
-// FUNZIONE CARICAMENTO VALORI DEFAULT +// CONTENUTO PDF ETICHETTA SACCA 
-function loadNutritionDefaults() { +function generateLabelPDFContent(doc) { 
-    if (!patientData.birthWeight) { +    const currentDate = new Date().toLocaleDateString('it-IT')
-        alert('Prima inserire i dati del paziente nel TAB 1'); +    const currentTime = new Date().toLocaleTimeString('it-IT', hour: '2-digit', minute: '2-digit' }); 
-        return;+    const calc = window.nptCalculation; 
 +     
 +    const birthDate = new Date(); 
 +    birthDate.setDate(birthDate.getDate() - patientData.daysOfLife); 
 +     
 +    // Recupera il medico attualmente selezionato 
 +    const currentPrescribingDoctor = document.getElementById('prescribingDoctor').value; 
 +    const doctorName = currentPrescribingDoctor && doctorsData[currentPrescribingDoctor] ?  
 +              doctorsData[currentPrescribingDoctor].fullName :  
 +              (patientData.prescribingDoctorName || 'Medico non specificato'); 
 +     
 +    if (!window.currentPrescriptionID) { 
 +        window.currentPrescriptionID = generatePreparationID();
     }     }
 +    const labelPreparationID = window.currentPrescriptionID;
          
-    const targetDay parseInt(document.getElementById('targetDay').value); +    let yPos 50;
-    const birthWeight = patientData.birthWeight;+
          
-    const weightCategorySelect = document.getElementById('weightCategory'); +    doc.setFontSize(14); 
-    let selectedCategory = weightCategorySelect.value || (birthWeight <= 1500 ? '≤1500g' : '>1500g'); +    doc.setFont(undefined, 'bold'); 
-    weightCategorySelect.value selectedCategory;+    doc.text('ETICHETTA SACCA NPT', 20, yPos); 
 +    yPos +20;
          
-    let plan = {}+    // IDENTIFICAZIONE PAZIENTE 
-    if (selectedCategory === '≤1500g'{ +    doc.setFontSize(12)
-        plan = targetDay <= 3 ? {liquids: 100, protein: 3.5carbs: 8.0lipids: 1.0} :  +    doc.setFont(undefined, 'bold'); 
-                               {liquids: 140, protein: 4.0, carbs: 10.0lipids: 2.0}+    doc.text('IDENTIFICAZIONE PAZIENTE'20yPos); 
-    } else { +    yPos += 15; 
-        plan = targetDay <= 3 ? {liquids: 120, protein: 3.0, carbs8.0lipids: 2.0} :  +     
-                               {liquids: 150, protein: 3.5, carbs12.0lipids: 3.0};+    doc.setFontSize(10); 
 +    doc.setFont(undefined'normal')
 +    doc.text('Cartella Clinica' + (patientData.medicalRecord || 'N/A')20, yPos); 
 +    yPos += 10; 
 +     
 +    if (labelPreparationID) { 
 +        doc.text('ID Prescrizione' + labelPreparationID20, yPos); 
 +        yPos += 10;
     }     }
          
-    // Aggiustamento BUN +    doc.text('Peso: ' + patientData.currentWeight + 'g', 20, yPos); 
-    if (patientData.bun && patientData.bun !== '') { +    yPos += 10; 
-        const bunValue parseFloat(patientData.bun)+    doc.text('Giorni di vita: ' + patientData.daysOfLife, 20, yPos); 
-        if (bunValue < 9) { +    yPos += 10; 
-            plan.protein = Math.min(6.0, plan.protein 1.0); +     
-        } else if (bunValue > 14) { +    if (patientData.gestationalWeeks && patientData.gestationalWeeks > 0) { 
-            plan.protein = Math.max(2.0, plan.protein - 1.0);+        const gestDays = patientData.gestationalDays || 0
 +        doc.text('Età Gestazionale: ' + patientData.gestationalWeeks '+' + gestDays + ' sett.', 20, yPos); 
 +        yPos += 10; 
 +        if (patientData.postConceptionalAge && patientData.postConceptionalAge.format) { 
 +            doc.text('Età Post-concez.: ' + patientData.postConceptionalAge.format + ' sett.', 20, yPos)
 +            yPos += 10;
         }         }
     }     }
          
-    document.getElementById('reqLiquids').value = plan.liquids; +    doc.text('Data Nascita: ' + birthDate.toLocaleDateString('it-IT'), 20, yPos); 
-    document.getElementById('reqProtein').value = plan.protein; +    yPos +20;
-    document.getElementById('reqCarbs').value = plan.carbs; +
-    document.getElementById('reqLipids').value = plan.lipids; +
-    document.getElementById('reqCalcium').value = targetDay > 3 ? 160 0; +
-    document.getElementById('reqPhosphorus').value = targetDay > 3 ? 84 : 0; +
-    document.getElementById('reqMagnesium').value = targetDay > 3 ? 0.6 : 0; +
-    document.getElementById('reqSodium').value = targetDay > 2 ? 2.0 : 0+
-    document.getElementById('reqPotassium').value targetDay > 2 ? 1.5 : 0;+
          
-    // Vitamine/oligoelementi +    // DATI PRESCRIZIONE 
-    const currentWeight patientData.currentWeight+    doc.setFontSize(12); 
-    const enteralVolumePerKg enteralData ? (enteralData.totalFluids / currentWeight * 1000) : 0;+    doc.setFont(undefined, 'bold'); 
 +    doc.text('DATI PRESCRIZIONE', 20, yPos); 
 +    yPos +15; 
 +     
 +    doc.setFontSize(10)
 +    doc.setFont(undefined, 'normal'); 
 +    doc.text('Medico Prescrittore: ' + doctorName, 20, yPos); 
 +    yPos +8; 
 +    doc.text('Data Prescrizione: ' + (patientData.prescriptionDate || currentDate), 20, yPos); 
 +    yPos += 8; 
 +    doc.text('Data Preparazione' + currentDate, 20, yPos); 
 +    yPos += 8; 
 +    doc.text('Ora Preparazione: ' + currentTime, 20, yPos); 
 +    yPos += 20;
          
-    if (targetDay >= 3 && enteralVolumePerKg < 100{ +    // CONTENUTO SACCA 
-        document.getElementById('reqVitalipid').value = 4.0+    doc.setFontSize(12); 
-        document.getElementById('reqSoluvit').value 1.0+    doc.setFont(undefined, 'bold'); 
-        document.getElementById('reqPeditrace').value = 1.0+    doc.text('CONTENUTO SACCA NPT', 20, yPos)
-    } else +    yPos +15; 
-        document.getElementById('reqVitalipid').value = 0; +     
-        document.getElementById('reqSoluvit').value = 0+    doc.setFontSize(10)
-        document.getElementById('reqPeditrace').value 0;+    doc.setFont(undefined, 'normal'); 
 +     
 +    if (calc.neededGlucose > 0) 
 +        doc.text('Glucosio 50%: + calc.glucose50Volume.toFixed(1) + ml', 20, yPos); 
 +        yPos +8;
     }     }
          
-    document.getElementById('reqCarnitine').value 0;+    doc.text('Trophamine 6%: + calc.proteinVolume.toFixed(1+ ' ml', 20, yPos); 
 +    yPos += 8; 
 +    doc.text('Intralipid 20%: ' + calc.lipidVolume.toFixed(1) + ' ml', 20, yPos); 
 +    yPos +8; 
 +    doc.text('Acqua Bidistillata: ' + calc.waterVolume.toFixed(1) + ' ml', 20, yPos); 
 +    yPos += 15; 
 +     
 +    doc.setFont(undefined, 'bold'); 
 +    doc.text('VOLUME TOTALE: ' + calc.totalVolume + ' ml', 20, yPos); 
 +    yPos += 10; 
 +    doc.text('Velocità infusione: ' + (calc.totalVolume / 24).toFixed(2) + ' ml/h', 20, yPos);
          
-    const loadBtn document.getElementById('loadDefaultsBtn'); +    // Osmolarità se disponibile 
-    if (loadBtn) { +    if (calc.osmolarityData) { 
-        loadBtn.className 'button load-defaults-completed'+        yPos +15; 
-        loadBtn.innerHTML = 'Valori Standard Caricati ✓';+        doc.setFontSize(11); 
 +        doc.text('Osmolarità: + calc.osmolarityData.total + ' mOsm/L', 20, yPos); 
 +         
 +        if (calc.osmolarityData.isHypertonic) { 
 +            yPos +10
 +            doc.setTextColor(255, 0, 0); // Rosso 
 +            doc.text('ATTENZIONE: SOLO ACCESSO VENOSO CENTRALE', 20, yPos); 
 +            doc.setTextColor(0, 0, 0); // Torna nero 
 +        }
     }     }
 } }
  
-function updateCarbUnit() { + 
-    const unit = document.getElementById('carbUnit').value; + 
-    const carbLabel = document.getElementById('carbLabel'); +// FUNZIONI PLACEHOLDER 
-    const carbInput = document.getElementById('reqCarbs'); +function showAddEnteralForm() { 
-     +    alert('Aggiungi nuova formula enterale - Implementazione completa nel codice sorgente');
-    if (unit === 'mg') { +
-        carbLabel.textContent = 'Glucidi (mg/kg/min):'; +
-        carbInput.setAttribute('max', '15')+
-        carbInput.setAttribute('step', '0.1'); +
-    } else { +
-        carbLabel.textContent = 'Glucidi (g/kg/die):'+
-        carbInput.setAttribute('max', '20'); +
-        carbInput.setAttribute('step', '0.1'); +
-    }+
 } }
  
-function updateWeightCategory() { +function showAddFortifierForm() { 
-    // Placeholder+    alert('Aggiungi nuovo fortificante - Implementazione completa nel codice sorgente');
 } }
  
-function updateSodiumChoice() { +function showAddParenteralForm() { 
-    // Placeholder+    alert('Aggiungi nuovo componente parenterale - Implementazione completa nel codice sorgente');
 } }
  
-// FUNZIONE CALCOLO FABBISOGNI + 
-function calculateNutrition() { +function showAddDoctorForm() { 
-    if (!patientData.birthWeight) { +    const name = prompt('Inserisci il nome del medico:'); 
-        alert('Prima inserire i dati del paziente nel TAB 1')+    if (!name || name.trim() === '') return;
-        return; +
-    }+
          
-    const requirements +    const surname prompt('Inserisci il cognome del medico:'); 
-        liquids: parseFloat(document.getElementById('reqLiquids').value), +    if (!surname || surname.trim() === ''return;
-        proteinparseFloat(document.getElementById('reqProtein').value), +
-        carbs: parseFloat(document.getElementById('reqCarbs').value), +
-        carbUnit: document.getElementById('carbUnit').value, +
-        lipids: parseFloat(document.getElementById('reqLipids').value), +
-        calcium: parseFloat(document.getElementById('reqCalcium').value), +
-        phosphorus: parseFloat(document.getElementById('reqPhosphorus').value), +
-        magnesium: parseFloat(document.getElementById('reqMagnesium').value), +
-        sodium: parseFloat(document.getElementById('reqSodium').value), +
-        potassium: parseFloat(document.getElementById('reqPotassium').value), +
-        vitalipid: parseFloat(document.getElementById('reqVitalipid').value) || 0, +
-        soluvit: parseFloat(document.getElementById('reqSoluvit').value) || 0, +
-        peditrace: parseFloat(document.getElementById('reqPeditrace').value) || 0, +
-        carnitine: parseFloat(document.getElementById('reqCarnitine').value) || 0 +
-    };+
          
-    // Converti carboidrati sempre in g/kg/die per i calcoli +    const title prompt('Inserisci il titolo (Dro Dr.ssa):'); 
-    const carbsGPerKgDay requirements.carbUnit === 'mg?  +    if (!title || title.trim() === ''return;
-        (requirements.carbs * 1440 / 1000: requirements.carbs;+
          
-    const currentWeight patientData.currentWeight;+    const key 'dr_' + surname.toLowerCase().replace(/\s+/g, '_') + '_' + Date.now(); 
 +    const fullName = title.trim() + ' ' + name.trim() + ' ' + surname.trim();
          
-    const enteralProtein enteralData ? enteralData.protein 0; +    doctorsData[key] 
-    const enteralCarbs = enteralData ? enteralData.carbs : 0; +        name: name.trim(), 
-    const enteralLipids = enteralData ? enteralData.lipids 0; +        surnamesurname.trim(), 
-    const enteralEnergy = enteralData ? enteralData.energy : 0;+        title: title.trim(), 
 +        fullNamefullName 
 +    };
          
-    const residualProtein = Math.max(0, requirements.protein - enteralProtein); +    populateDoctorsConfigTable(); 
-    const residualCarbs = Math.max(0, carbsGPerKgDay - enteralCarbs); +    updateDoctorsDropdown(); 
-    const residualLipids = Math.max(0, requirements.lipids - enteralLipids); +    alert('Medico aggiunto con successo!\n' + fullName); 
-    const totalEnergyRequirement = (requirements.protein * 4) + (carbsGPerKgDay * 4) + (requirements.lipids * 9); +
-    const residualEnergy = Math.max(0, totalEnergyRequirement - enteralEnergy);+ 
 +function showAddNurseForm() { 
 +    const name prompt('Inserisci il nome dell\'infermiera:'); 
 +    if (!name || name.trim() === '') return;
          
-    // Calcoli micronutrienti enterali +    const surname prompt('Inserisci il cognome dell\'infermiera:')
-    const enteralCalcium enteralData ? enteralData.calcium 0+    if (!surname || surname.trim() === '') return;
-    const enteralPhosphorus = enteralData ? enteralData.phosphorus : 0; +
-    const enteralMagnesium enteralData ? enteralData.magnesium : 0; +
-    const enteralSodium enteralData ? enteralData.sodium : 0; +
-    const enteralPotassium enteralData ? enteralData.potassium : 0;+
          
-    // Calcoli residui micronutrienti +    const title prompt('Inserisci il titolo (Inf.InfCoord., Inf. Spec.):'); 
-    const residualCalcium Math.max(0requirements.calcium - enteralCalcium); +    if (!title || title.trim() === ''return; 
-    const residualPhosphorus = Math.max(0requirements.phosphorus - enteralPhosphorus); +     
-    const residualMagnesium = Math.max(0, requirements.magnesium - enteralMagnesium); +    const key 'inf_' + surname.toLowerCase().replace(/\s+/g'_') + '_' + Date.now(); 
-    const residualSodium Math.max(0requirements.sodium - enteralSodium); +    const fullName title.trim() + ' ' + name.trim() + ' ' + surname.trim();
-    const residualPotassium Math.max(0, requirements.potassium - enteralPotassium);+
          
-    window.residualNeeds = { +    nursesData[key] = { 
-        liquidsrequirements.liquids - (enteralData ? enteralData.totalFluids/patientData.currentWeight*1000 : 0), +        namename.trim(), 
-        proteinresidualProtein, +        surnamesurname.trim()
-        carbs: residualCarbs, +        titletitle.trim()
-        lipids: residualLipids, +        fullNamefullName
-        calcium: residualCalcium, +
-        phosphorus: residualPhosphorus, +
-        magnesium: residualMagnesium, +
-        sodium: residualSodium, +
-        potassium: residualPotassium, +
-        vitalipid: requirements.vitalipid+
-        soluvitrequirements.soluvit, +
-        peditrace: requirements.peditrace, +
-        carnitine: requirements.carnitine, +
-        energy: residualEnergy+
-        totalEnergyRequirementtotalEnergyRequirement+
     };     };
          
-    // Calcola mg/kg/min per la tabella +    populateNursesConfigTable(); 
-    const carbsMgPerKgMin = (carbsGPerKgDay * 1000/ 1440+    alert('Infermiera aggiunta con successo!\n' + fullName); 
-    const enteralCarbsMgPerKgMin = (enteralCarbs * 1000/ 1440+
-    const residualCarbsMgPerKgMin = (residualCarbs * 1000/ 1440;+ 
 +function showAddPharmacistForm() { 
 +    const name prompt('Inserisci il nome del farmacista:'); 
 +    if (!name || name.trim() === ''return;
          
-    let tableHtml '<table class="nutrition-table">'; +    const surname prompt('Inserisci il cognome del farmacista:'); 
-    tableHtml += '<tr><th>Componente</th><th>Fabbisogno</th><th>Da Enterale</th><th>Da NPT</th><th>Unità</th></tr>'; +    if (!surname || surname.trim() === ''return;
-    tableHtml += '<tr><td><strong>Liquidi</strong></td><td><strong>' + requirements.liquids + '</strong></td><td><strong>'(enteralData ? (enteralData.totalFluids/patientData.currentWeight*1000).toFixed(1) : '0') + '</strong></td><td class="highlight"><strong>' + Math.max(0, requirements.liquids - (enteralData ? enteralData.totalFluids/patientData.currentWeight*1000 0)).toFixed(1) + '</strong></td><td><strong>ml/kg/die</strong></td></tr>'; +
-    tableHtml += '<tr><td>Proteine</td><td>' + requirements.protein + '</td><td>' + enteralProtein.toFixed(1+ '</td><td class="highlight">' + residualProtein.toFixed(1) + '</td><td>g/kg/die</td></tr>'+
-    tableHtml += '<tr><td>Glucidi (g/kg/die)</td><td>' + carbsGPerKgDay.toFixed(1+ '</td><td>' + enteralCarbs.toFixed(1) + '</td><td class="highlight">' + residualCarbs.toFixed(1) + '</td><td>g/kg/die</td></tr>'; +
-    tableHtml +'<tr><td>Glucidi (mg/kg/min)</td><td>' + carbsMgPerKgMin.toFixed(1) + '</td><td>' + enteralCarbsMgPerKgMin.toFixed(1) + '</td><td class="highlight">+ residualCarbsMgPerKgMin.toFixed(1) + '</td><td>mg/kg/min</td></tr>'; +
-    tableHtml += '<tr><td>Lipidi</td><td>' + requirements.lipids + '</td><td>' + enteralLipids.toFixed(1+ '</td><td class="highlight">' + residualLipids.toFixed(1) + '</td><td>g/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Calcio elementare</td><td>' + requirements.calcium + '</td><td>' + enteralCalcium.toFixed(1) + '</td><td class="highlight">' + residualCalcium.toFixed(1) + '</td><td>mg/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Fosforo</td><td>' + requirements.phosphorus + '</td><td>' + enteralPhosphorus.toFixed(1) + '</td><td class="highlight">' + residualPhosphorus.toFixed(1) + '</td><td>mg/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Magnesio</td><td>' + requirements.magnesium + '</td><td>' + enteralMagnesium.toFixed(2) + '</td><td class="highlight">' + residualMagnesium.toFixed(2) + '</td><td>mEq/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Sodio</td><td>' + requirements.sodium + '</td><td>' + enteralSodium.toFixed(2) + '</td><td class="highlight">' + residualSodium.toFixed(2) + '</td><td>mEq/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Potassio</td><td>' + requirements.potassium + '</td><td>' + enteralPotassium.toFixed(2) + '</td><td class="highlight">' + residualPotassium.toFixed(2) + '</td><td>mEq/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Vitalipid</td><td>' + requirements.vitalipid + '</td><td>0</td><td class="highlight">' + requirements.vitalipid + '</td><td>ml/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Soluvit</td><td>' + requirements.soluvit + '</td><td>0</td><td class="highlight">' + requirements.soluvit + '</td><td>ml/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Peditrace</td><td>' + requirements.peditrace + '</td><td>0</td><td class="highlight">' + requirements.peditrace + '</td><td>ml/kg/die</td></tr>'; +
-    tableHtml += '<tr><td>Carnitina</td><td>' + requirements.carnitine + '</td><td>0</td><td class="highlight">' + requirements.carnitine + '</td><td>mg/kg/die</td></tr>'; +
-    tableHtml += '<tr class="day-column"><td><strong>ENERGIA TOTALE</strong></td><td><strong>' + totalEnergyRequirement.toFixed(0) + '</strong></td><td><strong>' + enteralEnergy.toFixed(0) + '</strong></td><td class="energy-highlight">' + residualEnergy.toFixed(0) + '</td><td><strong>kcal/kg/die</strong></td></tr>'; +
-    tableHtml += '</table>';+
          
-    document.getElementById('nutritionTable').innerHTML = tableHtml+    const title = prompt('Inserisci il titolo (Dr. Farm., Dr.ssa Farm., Farm.):'); 
-    document.getElementById('nutritionResults').classList.remove('hidden'); +    if (!title || title.trim() === ''return; 
-    document.getElementById('calculateNutritionBtn').className = 'button calculate-nutrition-completed'; +     
-    document.getElementById('calculateNutritionBtn').innerHTML = 'FABBISOGNI CALCOLATI ✓';+    const key = 'farm_' + surname.toLowerCase().replace(/\s+/g, '_') + '_' + Date.now(); 
 +    const fullName = title.trim() + ' ' + name.trim() + ' ' + surname.trim()
 +     
 +    pharmacistsData[key] = { 
 +        name: name.trim()
 +        surname: surname.trim(), 
 +        title: title.trim(), 
 +        fullName: fullName 
 +    }; 
 +     
 +    populatePharmacistsConfigTable(); 
 +    alert('Farmacista aggiunto con successo!\n+ fullName);
 } }
  
-// FUNZIONE CALCOLO ELETTROLITI AGGIUNTIVI +function showAddTechnicianForm() { 
-function calculateElectrolyteAdditions(calciumNeeded, phosphorusNeeded, magnesiumNeeded, sodiumNeeded, potassiumNeeded, currentWeightKg) { +    const name prompt('Inserisci il nome del tecnico:'); 
-    const additions +    if (!name || name.trim() === '') return;
-        ca_gluconato0, +
-        esafosfina: 0, +
-        mg_sulfate: 0, +
-        nacl: 0, +
-        sodium_acetate: 0, +
-        kcl: 0, +
-        totalVolume: 0, +
-        providedCalcium: 0, +
-        providedPhosphorus: 0, +
-        providedMagnesium: 0, +
-        providedSodium: 0, +
-        providedPotassium: 0, +
-        sodiumSource: 'nacl' +
-    };+
          
-    const sodiumTypeSelect document.getElementById('sodiumType'); +    const surname prompt('Inserisci il cognome del tecnico:'); 
-    const selectedSodiumType = sodiumTypeSelect ? sodiumTypeSelect.value : 'nacl'+    if (!surname || surname.trim() === '') return;
-    additions.sodiumSource = selectedSodiumType;+
          
-    const totalCalciumNeeded calciumNeeded * currentWeightKg+    const title prompt('Inserisci il titolo (Tec., Tec. Spec., Coord. Tec.):')
-    const totalPhosphorusNeeded phosphorusNeeded * currentWeightKg; +    if (!title || title.trim() === '') return;
-    const totalMagnesiumNeeded magnesiumNeeded * currentWeightKg; +
-    const totalSodiumNeeded = sodiumNeeded * currentWeightKg; +
-    const totalPotassiumNeeded potassiumNeeded * currentWeightKg;+
          
-    // Calcio Gluconato 10% (840 mg Ca/100ml+    const key = 'tec_' + surname.toLowerCase().replace(/\s+/g, '_') + '_' + Date.now(); 
-    if (totalCalciumNeeded > 0) { +    const fullName = title.trim() + ' ' + name.trim() + ' ' + surname.trim(); 
-        additions.ca_gluconato = totalCalciumNeeded / (parenteralConfig.ca_gluconato.calcium / 100); +     
-        additions.providedCalcium = totalCalciumNeeded; +    technicianData[key] = 
-    }+        name: name.trim(), 
 +        surname: surname.trim(), 
 +        title: title.trim(), 
 +        fullName: fullName 
 +    };
          
-    // Esafosfina (1600 mg P/100ml + 130 mEq Na/100ml+    populateTechniciansConfigTable(); 
-    if (totalPhosphorusNeeded > 0) { +    alert('Tecnico aggiunto con successo!\n' + fullName); 
-        additions.esafosfina = totalPhosphorusNeeded / (parenteralConfig.esafosfina.phosphorus / 100); +
-        additions.providedPhosphorus = totalPhosphorusNeeded; + 
-        additions.providedSodium += (additions.esafosfina * parenteralConfig.esafosfina.sodium / 100);+ 
 +function removeEnteralFormula(key) { 
 +    if (confirm('Sei sicuro di voler rimuovere questa formula?')) { 
 +        alert('Rimozione formula - Implementazione completa nel codice sorgente');
     }     }
 +}
 +
 +function removeParenteralComponent(key) {
 +    if (confirm('Sei sicuro di voler rimuovere questo componente?')) {
 +        alert('Rimozione componente - Implementazione completa nel codice sorgente');
 +    }
 +}
 +
 +function removeFortifier(key) {
 +    if (confirm('Sei sicuro di voler rimuovere questo fortificante?')) {
 +        alert('Rimozione fortificante - Implementazione completa nel codice sorgente');
 +    }
 +}
 +
 +function removeDoctor(key) {
 +    if (confirm('Sei sicuro di voler rimuovere questo medico?\n\n' + doctorsData[key].fullName)) {
 +        delete doctorsData[key];
 +        populateDoctorsConfigTable();
 +        updateDoctorsDropdown();
 +        alert('Medico rimosso con successo!');
 +    }
 +}
 +
 +function removeNurse(key) {
 +    if (confirm('Sei sicuro di voler rimuovere questa infermiera?\n\n' + nursesData[key].fullName)) {
 +        delete nursesData[key];
 +        populateNursesConfigTable();
 +        alert('Infermiera rimossa con successo!');
 +    }
 +}
 +
 +function removePharmacist(key) {
 +    if (confirm('Sei sicuro di voler rimuovere questo farmacista?\n\n' + pharmacistsData[key].fullName)) {
 +        delete pharmacistsData[key];
 +        populatePharmacistsConfigTable();
 +        alert('Farmacista rimosso con successo!');
 +    }
 +}
 +
 +function removeTechnician(key) {
 +    if (confirm('Sei sicuro di voler rimuovere questo tecnico?\n\n' + technicianData[key].fullName)) {
 +        delete technicianData[key];
 +        populateTechniciansConfigTable();
 +        alert('Tecnico rimosso con successo!');
 +    }
 +}
 +
 +// FUNZIONI VALIDAZIONE E ARCHIVIAZIONE PREPARAZIONE
 +function updatePreparationStaffDropdowns() {
 +    console.log('Popolamento dropdown personale preparazione');
          
-    // Magnesio Solfato (800 mEq Mg/100ml+    // Farmacisti 
-    if (totalMagnesiumNeeded > 0) { +    const pharmacistSelect = document.getElementById('validatingPharmacist'); 
-        additions.mg_sulfate totalMagnesiumNeeded / (parenteralConfig.mg_sulfate.magnesium / 100); +    if (pharmacistSelect) { 
-        additions.providedMagnesium totalMagnesiumNeeded;+        pharmacistSelect.innerHTML '<option value="">Seleziona farmacista responsabile</option>'; 
 +        Object.keys(pharmacistsData).forEach(key => { 
 +            const option = document.createElement('option'); 
 +            option.value key; 
 +            option.textContent = pharmacistsData[key].fullName; 
 +            pharmacistSelect.appendChild(option); 
 +        }); 
 +        console.log('Dropdown farmacisti popolata:', Object.keys(pharmacistsData).length, 'farmacisti');
     }     }
          
-    // Sodio rimanente +    // Tecnici (per entrambe le dropdown) 
-    const remainingSodium Math.max(0totalSodiumNeeded - additions.providedSodium);+    ['preparingTechnician1', 'preparingTechnician2'].forEach(selectId => { 
 +        const select document.getElementById(selectId); 
 +        if (select) { 
 +            select.innerHTML = '<option value="">Seleziona tecnico</option>'; 
 +            Object.keys(technicianData).forEach(key => { 
 +                const option = document.createElement('option'); 
 +                option.value = key; 
 +                option.textContent = technicianData[key].fullName; 
 +                select.appendChild(option); 
 +            }); 
 +        } 
 +    }); 
 +    console.log('Dropdown tecnici popolate:'Object.keys(technicianData).length, 'tecnici'); 
 +
 + 
 +// ===================================================== 
 +// SISTEMA VALIDAZIONE E PREPARAZIONE IN DUE FASI 
 +// ===================================================== 
 + 
 +// FASE 1: Validazione Farmacista 
 +function validatePrescription() { 
 +    const pharmacist = document.getElementById('validatingPharmacist').value;
          
-    if (remainingSodium > 0) { +    if (!pharmacist) { 
-        if (selectedSodiumType === 'sodium_acetate'+        alert('⚠️ Errore: Selezionare il farmacista validatore'); 
-            const concentrationSodiumAcetate = parenteralConfig.sodium_acetate.sodium / 100; +        return;
-            additions.sodium_acetate = remainingSodium / concentrationSodiumAcetate; +
-        } else { +
-            const concentrationNaCl = parenteralConfig.nacl.sodium / 100; +
-            additions.nacl = remainingSodium / concentrationNaCl; +
-        } +
-        additions.providedSodium += remainingSodium;+
     }     }
          
-    // Potassio Cloruro (1000 mEq K/100ml) +    if (!window.residualNeeds || !window.nptCalculation || !patientData.currentWeight) { 
-    if (totalPotassiumNeeded > 0) { +        alert('❌ Errore: Prima completare tutti i calcoli NPT (TAB 1-4)'); 
-        additions.kcl = totalPotassiumNeeded / (parenteralConfig.kcl.potassium / 100); +        return;
-        additions.providedPotassium = totalPotassiumNeeded;+
     }     }
          
-    additions.totalVolume additions.ca_gluconato + additions.esafosfina + additions.mg_sulfate + additions.nacl + additions.sodium_acetate + additions.kcl;+    // Validazione completata 
 +    document.getElementById('validatePrescriptionBtn').className 'button config-update-completed'; 
 +    document.getElementById('validatePrescriptionBtn').innerHTML = '✅ PRESCRIZIONE VALIDATA'; 
 +    document.getElementById('validatePrescriptionBtn').disabled = true;
          
-    return additions;+    // Mostra status validazione 
 +    const pharmacistName = pharmacistsData[pharmacist].fullName; 
 +    const validationHtml = '<div class="info">'
 +        '<strong>✅ VALIDAZIONE COMPLETATA</strong><br>'
 +        '<strong>Farmacista:</strong> ' + pharmacistName + '<br>'
 +        '<strong>Data/Ora:</strong> ' + new Date().toLocaleString('it-IT') + '<br>'
 +        '<strong>Status:</strong> Prescrizione validata per allestimento'
 +        '</div>'; 
 +     
 +    document.getElementById('validationStatus').innerHTML = validationHtml; 
 +    document.getElementById('validationStatus').style.display = 'block'; 
 +     
 +    // Abilita fase 2 - Allestimento 
 +    enablePreparationPhase(); 
 +     
 +    alert('✅ Prescrizione validata dal farmacista!\nOra puoi procedere con l\'allestimento.');
 } }
  
-// FUNZIONE CALCOLO NPT PARENTERALE +// Abilita la fase di allestimento tecnici 
-function calculateParenteral() { +function enablePreparationPhase() { 
-    if (!window.residualNeeds) { +    const tech1Select = document.getElementById('preparingTechnician1'); 
-        alert('Prima calcolare fabbisogni nel TAB 3');+    const tech2Select = document.getElementById('preparingTechnician2'); 
 +     
 +    // Abilita le dropdown tecnici 
 +    tech1Select.disabled = false; 
 +    tech2Select.disabled = false; 
 +     
 +    // Popola le dropdown tecnici 
 +    [tech1Select, tech2Select].forEach(select => { 
 +        select.innerHTML = '<option value="">Seleziona tecnico</option>'; 
 +        Object.keys(technicianData).forEach(key => { 
 +            const option = document.createElement('option'); 
 +            option.value = key; 
 +            option.textContent = technicianData[key].fullName; 
 +            select.appendChild(option); 
 +        }); 
 +    }); 
 +     
 +    // Abilita il pulsante conferma (ma ancora non attivo finché non si selezionano i tecnici) 
 +    document.getElementById('confirmPreparationBtn').disabled = false; 
 +    document.getElementById('confirmPreparationBtn').innerHTML = '🧪 CONFERMA ALLESTIMENTO'; 
 +     
 +    // Event listeners per controllare quando entrambi i tecnici sono selezionati 
 +    [tech1Select, tech2Select].forEach(select => { 
 +        select.addEventListener('change', checkTechniciansSelection); 
 +    }); 
 +
 + 
 +// Controlla se entrambi i tecnici sono selezionati 
 +function checkTechniciansSelection() { 
 +    const tech1 = document.getElementById('preparingTechnician1').value; 
 +    const tech2 = document.getElementById('preparingTechnician2').value; 
 +    const confirmBtn = document.getElementById('confirmPreparationBtn'); 
 +     
 +    if (tech1 && tech2 && tech1 !== tech2) { 
 +        confirmBtn.className = 'button'; 
 +        confirmBtn.innerHTML = '🧪 CONFERMA ALLESTIMENTO'; 
 +    } else if (tech1 === tech2 && tech1 !== '') { 
 +        confirmBtn.className = 'button config-update-pending'; 
 +        confirmBtn.innerHTML = '⚠️ TECNICI DEVONO ESSERE DIVERSI'; 
 +    } else { 
 +        confirmBtn.className = 'button'; 
 +        confirmBtn.innerHTML = '🧪 CONFERMA ALLESTIMENTO (seleziona tecnici)'; 
 +    } 
 +
 + 
 +// FASE 2: Conferma Allestimento 
 +function confirmPreparation() { 
 +    const tech1 = document.getElementById('preparingTechnician1').value; 
 +    const tech2 = document.getElementById('preparingTechnician2').value; 
 +     
 +    if (!tech1 || !tech2) { 
 +        alert('⚠️ Errore: Selezionare entrambi tecnici preparatori');
         return;         return;
     }     }
          
-    const currentWeight patientData.currentWeight+    if (tech1 === tech2) { 
-    const currentWeightKg = currentWeight / 1000+        alert('⚠️ Errore: I due tecnici devono essere persone diverse per il controllo incrociato')
-    const residualNeeds = window.residualNeeds;+        return
 +    }
          
-    const totalVolume Math.round(residualNeeds.liquids * currentWeightKg);+    // Allestimento confermato 
 +    document.getElementById('confirmPreparationBtn').className 'button config-update-completed'; 
 +    document.getElementById('confirmPreparationBtn').innerHTML = '🧪 ALLESTIMENTO COMPLETATO ✓'; 
 +    document.getElementById('confirmPreparationBtn').disabled = true;
          
-    const electrolyteAdditions calculateElectrolyteAdditions( +    // Mostra status preparazione 
-        residualNeeds.calcium, +    const tech1Name technicianData[tech1].fullName; 
-        residualNeeds.phosphorus, +    const tech2Name = technicianData[tech2].fullName; 
-        residualNeeds.magnesium, +    const preparationHtml = '<div class="info">' + 
-        residualNeeds.sodium+        '<strong>🧪 ALLESTIMENTO COMPLETATO</strong><br>'
-        residualNeeds.potassium, +        '<strong>Tecnico 1:</strong> ' + tech1Name + '<br>'
-        currentWeightKg+        '<strong>Tecnico 2:</strong> ' + tech2Name + '<br>'
 +        '<strong>Data/Ora:</strong> ' + new Date().toLocaleString('it-IT') + '<br>' + 
 +        '<strong>Status:</strong> NPT pronta per somministrazione'
 +        '</div>'; 
 +     
 +    document.getElementById('preparationStatus').innerHTML = preparationHtml; 
 +    document.getElementById('preparationStatus').style.display = 'block'; 
 +     
 +    // Abilita download JSON 
 +document.getElementById('downloadBtn').disabled = false; 
 +document.getElementById('downloadBtn').className = 'button'; 
 + 
 +    // Abilita pulsante blocco prescrizione 
 +    document.getElementById('lockPrescriptionBtn').disabled = false; 
 +    document.getElementById('lockPrescriptionBtn').className = 'button'; 
 +    document.getElementById('lockPrescriptionBtn').style.backgroundColor = '#e74c3c'; 
 + 
 +    // Genera e salva l'ID preparazione per il sistema di blocco 
 +    if (!window.currentPrescriptionID) { 
 +        window.currentPrescriptionID = generatePreparationID(); 
 +    } 
 +    window.lastPreparationID = window.currentPrescriptionID; 
 + 
 +    console.log('ID Preparazione assegnato:'window.currentPrescriptionID); 
 + 
 + 
 + 
 +    alert('🧪 Allestimento completato!\Puoi ora archiviare la preparazione e bloccarla definitivamente.'); 
 +    } 
 + 
 +// ===================================================== 
 +// SISTEMA BLOCCO PRESCRIZIONE 
 +// ===================================================== 
 + 
 +// Variabile globale per stato blocco 
 +window.prescriptionLocked = false; 
 + 
 +// Funzione per bloccare la prescrizione 
 +function lockPrescription() { 
 +    const confirmed = confirm( 
 +        '🔒 ATTENZIONE: BLOCCO PRESCRIZIONE\n\n'
 +        'Questa operazione bloccherà DEFINITIVAMENTE la prescrizione NPT corrente.\n\n' + 
 +        '• Non sarà più possibile modificare i dati\n'
 +        '• La preparazione sarà considerata FINALIZZATA\n'
 +        '• Per modifiche servirà una NUOVA prescrizione\n\n' + 
 +        'Sei sicuro di voler procedere?'
     );     );
          
-    const proteinVolume = Math.round((residualNeeds.protein * currentWeightKg * 100) / 6); +    if (!confirmed
-    const lipidVolume = Math.round((residualNeeds.lipids * currentWeightKg * 100) / 20);+        return
 +    }
          
-    const vitaminsVolume = (residualNeeds.vitalipid * currentWeightKg) + (residualNeeds.soluvit * currentWeightKg) + (residualNeeds.peditrace * currentWeightKg); +    // Blocca la prescrizione 
-    const carnitineVolume residualNeeds.carnitine > 0 ? (residualNeeds.carnitine * currentWeightKg) / 100 : 0;+    window.prescriptionLocked true;
          
-    const neededGlucose residualNeeds.carbs * currentWeightKg+    // Aggiorna interfaccia 
-    const glucose50Volume = (neededGlucose * 100) / 50;+    document.getElementById('lockPrescriptionBtn').className 'button config-update-completed'; 
 +    document.getElementById('lockPrescriptionBtn').innerHTML = '🔒 PRESCRIZIONE BLOCCATA ✓'
 +    document.getElementById('lockPrescriptionBtn').disabled true; 
 + 
 +    // Assicurati che l'ID preparazione sia disponibile per il banner 
 +    if (!window.lastPreparationID && window.currentPrescriptionID
 +        window.lastPreparationID = window.currentPrescriptionID; 
 +    } 
 +    // Mostra banner di stato 
 +    showPrescriptionLockedBanner();
          
-    const usedVolume = proteinVolume + lipidVolume + vitaminsVolume + carnitineVolume + glucose50Volume + electrolyteAdditions.totalVolume; +    // Disabilita tutti i controlli di input 
-    const waterVolume = totalVolume - usedVolume;+    disableAllInputs();
          
-    let glucoseMessage = '';+    alert('🔒 PRESCRIZIONE BLOCCATA!\n\n'
 +          'La prescrizione NPT è ora finalizzata e non può essere modificata.\n'
 +          'Per eventuali modifiche sarà necessaria una nuova prescrizione.'); 
 +
 + 
 +// Mostra banner di prescrizione bloccata 
 +function showPrescriptionLockedBanner() { 
 +    const currentDateTime new Date().toLocaleString('it-IT'); 
 +    const preparationID = window.lastPreparationID || window.currentPrescriptionID || 'N/A'; 
 +    const bannerHtml = '<div class="alert-critical" style="text-align: center; margin: 20px 0;">'
 +        '<strong>🔒 PRESCRIZIONE NPT BLOCCATA E FINALIZZATA</strong><br>'
 +        '<strong>Data/Ora blocco:</strong> ' + currentDateTime + '<br>'
 +        '<strong>ID Preparazione:</strong> ' + preparationID + '<br>'
 +        '<strong>Status:</strong> NPT pronta per somministrazione - NESSUNA MODIFICA CONSENTITA<br>'
 +        '<button class="button secondary" onclick="startNewPrescription()" style="margin-top: 10px;">📋 NUOVA PRESCRIZIONE NPT</button>'
 +        '</div>';
          
-    if (waterVolume < 0) { +    document.getElementById('prescriptionStatusBanner').innerHTML = bannerHtml
-        glucoseMessage = '<div class="warning"><strong>ERRORE CALCOLO:</strong><br>'+    document.getElementById('prescriptionStatusBanner').style.display = 'block'; 
-                        '• Volume totale richiesto: ' + totalVolume + ' ml<br>'+
-                        '• Volume utilizzato: ' + usedVolume.toFixed(1) + ml<br>+ 
-                        '• Acqua rimanente: ' + waterVolume.toFixed(1+ ' ml (NEGATIVO!)<br><br>'+// Disabilita tutti gli input quando prescrizione è bloccata 
-                        '<strong>SOLUZIONE:</strong> Aumentare il volume totale NPT.</div>'+function disableAllInputs() { 
-         +    // Disabilita TAB 2-4, mantieni TAB 1 accessibile per consultazione 
-        document.getElementById('calculatedTotalVolume').value totalVolume + ml (ERRORE)'; +    const tabButtons = document.querySelectorAll('.tab'); 
-        document.getElementById('suggestedGlucose').value = 'Errore - Volume insufficiente'+    tabButtons.forEach((tab, index) => { 
-        document.getElementById('calculatedProteinVol').value proteinVolume + ' ml'; +        if (index > 0 && index < 4{ // Solo TAB 2-4, NON TAB 1 (index 0) 
-        document.getElementById('calculatedLipidVol').value lipidVolume + ml'; +        tab.style.opacity = '0.5'; 
-         +        tab.style.pointerEvents = 'none'; 
-        document.getElementById('parenteralTable').innerHTML = glucoseMessage+        tab.style.cursor = 'not-allowed';
-        document.getElementById('parenteralResults').classList.remove('hidden'); +
-        return;+
     }     }
 +});
          
-    if (neededGlucose <= 0) { +  // Disabilita input solo nei TAB 2-4, mantieni TAB 1 consultabile 
-        glucoseMessage = '<div class="info"><strong>GLUCOSIO DA ENTERALE:</strong><br>' + +    const inputElements document.querySelectorAll('#enteral input, #enteral select, #enteral button, ' + 
-                        '• Tutto il glucosio necessario proviene dall\'alimentazione enterale<br>' + +                                               '#nutrition-calc input, #nutrition-calc select, #nutrition-calc button, ' + 
-                        '• Non necessario glucosio in NPT</div>'; +                                               '#parenteral input, #parenteral select, #parenteral button'); 
-         + 
-        document.getElementById('suggestedGlucose').value = 'Non necessario (enterale sufficiente)'; +    inputElements.forEach(element => { 
-    } else +        element.disabled = true; 
-        glucoseMessage = '<div class="info"><strong>CALCOLO GLUCOSIO:</strong><br>+ +        element.style.opacity = '0.5'; 
-                        '• Glucosio necessario: ' + neededGlucose.toFixed(1) + 'g<br>' + +}); 
-                        '• Glucosio 50%: + glucose50Volume.toFixed(1) + 'ml<br>+ + 
-                        '• Acqua bidistillata: + waterVolume.toFixed(1) 'ml<br>+ +// TAB 1: disabilita solo i pulsanti di modifica, mantieni visibili i dati 
-                        '• <strong>Concentrazione finale: + ((neededGlucose * 100/ totalVolume).toFixed(1) + '%</strong></div>'; +const tab1Buttons = document.querySelectorAll('#patient-data button')
-         +tab1Buttons.forEach(button => { 
-        document.getElementById('suggestedGlucose').value = 'Glucosio 50% Acqua';+    button.disabled = true; 
 +    button.style.opacity = '0.5'
 +})
 +     
 +    // Mostra overlay sui TAB bloccati 
 +    addLockedOverlay(); 
 +} 
 + 
 +// Aggiunge overlay visivo sui TAB bloccati 
 +function addLockedOverlay() 
 +    const lockedTabs ['enteral', 'nutrition-calc', 'parenteral']; // RIMUOVI 'patient-data
 +        lockedTabs.forEach(tabId ={ 
 +        const tabElement = document.getElementById(tabId); 
 +        if (tabElement && !tabElement.querySelector('.locked-overlay')) { 
 +            const overlay = document.createElement('div'); 
 +            overlay.className = 'locked-overlay'
 +            overlay.style.cssText = ` 
 +                position: absolute; 
 +                top: 0; 
 +                left: 0; 
 +                width: 100%; 
 +                height: 100%; 
 +                background-color: rgba(231, 76, 60, 0.1)
 +                z-index: 1000; 
 +                display: flex; 
 +                align-items: center; 
 +                justify-content: center; 
 +                font-size: 24px; 
 +                font-weight: bold; 
 +                color: #e74c3c; 
 +                pointer-events: none; 
 +            `; 
 +            overlay.innerHTML = '🔒 PRESCRIZIONE BLOCCATA'; 
 +             
 +            tabElement.style.position = 'relative'
 +            tabElement.appendChild(overlay)
 +        } 
 +    })
 +
 + 
 +// Funzione per iniziare nuova prescrizione 
 +function startNewPrescription() 
 +    const confirmed = confirm( 
 +        '📋 NUOVA PRESCRIZIONE NPT\n\n' + 
 +        'Questa operazione:\n+ 
 +        '• Resetterà tutti i dati correnti\n' + 
 +        '• Permetterà di iniziare una nuova prescrizione\n
 +        '• La prescrizione precedente rimarrà archiviata\n\n' + 
 +        'Vuoi procedere?' 
 +    ); 
 +     
 +    if (!confirmed) { 
 +        return;
     }     }
          
-    document.getElementById('calculatedTotalVolume').value totalVolume + ' ml'+    // Reset completo dell'applicazione 
-    document.getElementById('calculatedProteinVol').value proteinVolume + ' ml'+    resetToNewPrescription()
-    document.getElementById('calculatedLipidVol').value lipidVolume + ' ml';+
 + 
 +// Reset per nuova prescrizione 
 +function resetToNewPrescription() { 
 +    // Reset variabili globali 
 +    window.prescriptionLocked false
 +    window.residualNeeds = null; 
 +    window.nptCalculation null
 +    window.monthlyPreparations = []; 
 +    window.currentPrescriptionID null; 
 +    patientData = {}; 
 +    enteralData = null; 
 +    currentRequirements = null;
          
-    let resultHtml = glucoseMessage;+    // Riabilita tutti gli input 
 +    enableAllInputs();
          
-    resultHtml += '<div class="info">'; +    // Reset tutti i form 
-    resultHtml += '<strong>NPT v2.0 - COMPOSIZIONE COMPLETA</strong><br>'; +    resetAllForms();
-    resultHtml += '<strong>Peso:</strong> ' + currentWeight + 'g<br>'; +
-    resultHtml += '<strong>Enterale:</strong> ' + (enteralData ? enteralData.totalFluids : 0+ ' ml<br>'; +
-    resultHtml += '</div>';+
          
-    resultHtml += '<table class="results-table">'+    // Nascondi banner 
-    resultHtml += '<tr><th>Componente</th><th>Volume (ml)</th></tr>';+    document.getElementById('prescriptionStatusBanner').style.display = 'none';
          
-    if (neededGlucose > 0) { +    // Vai al TAB 1 
-        resultHtml += '<tr><td><strong>Glucosio 50%</strong></td><td><strong>' + glucose50Volume.toFixed(1) + '</strong></td></tr>'; +    showTab('patient-data');
-    }+
          
-    resultHtml += '<tr><td><strong>Trophamine 6%</strong></td><td><strong>' + proteinVolume.toFixed(1'</strong></td></tr>'; +    // Imposta nuova data 
-    resultHtml += '<tr><td><strong>Intralipid 20%</strong></td><td><strong>+ Math.max(0, lipidVolume).toFixed(1) + '</strong></td></tr>';+    const today = new Date().toISOString().split('T')[0]
 +    document.getElementById('prescriptionDate').value = today;
          
-    if (electrolyteAdditions.ca_gluconato > 0) { +    alert('📋 Nuova prescrizione iniziata!\nPuoi ora inserire i dati del nuovo paziente.'); 
-        resultHtml += '<tr><td><strong>Calcio Gluconato 10% (1g/10mL0.44 mEq/mL)</strong></td><td><strong>+ electrolyteAdditions.ca_gluconato.toFixed(1) '</strong></td></tr>';+
 + 
 +// Funzioni di supporto per reset completo 
 +function enableAllInputs() { 
 +    // Riabilita tutti i TAB 
 +    const tabButtons document.querySelectorAll('.tab'); 
 +    tabButtons.forEach(tab => { 
 +        tab.style.opacity = '1'; 
 +        tab.style.pointerEvents = 'auto'; 
 +        tab.style.cursor = 'pointer'; 
 +    }); 
 +     
 +    // Riabilita tutti gli input 
 +    const inputElements = document.querySelectorAll('#patient-data input#patient-data select, #patient-data button, ' + 
 +                                                   '#enteral input, #enteral select, #enteral button, ' + 
 +                                                   '#nutrition-calc input, #nutrition-calc select, #nutrition-calc button, ' + 
 +                                                   '#parenteral input, #parenteral select, #parenteral button'); 
 +     
 +    inputElements.forEach(element => { 
 +        element.disabled = false; 
 +        element.style.opacity = '1'; 
 +    })
 +     
 +    // Rimuovi overlay bloccati 
 +    removeLockedOverlays(); 
 +
 + 
 +function removeLockedOverlays() { 
 +    const overlays = document.querySelectorAll('.locked-overlay'); 
 +    overlays.forEach(overlay => { 
 +        overlay.remove(); 
 +    }); 
 +
 + 
 +function resetAllForms() { 
 +    // Reset TAB - Dati Paziente 
 +    document.getElementById('medicalRecord').value = new Date().getFullYear().toString(); 
 +    document.getElementById('birthWeight').value = '1000'; 
 +    document.getElementById('currentWeight').value = '1000'; 
 +    document.getElementById('daysOfLife').value = '9'; 
 +    document.getElementById('gestationalWeeks').value = ''; 
 +    document.getElementById('gestationalDays').value = ''; 
 +    document.getElementById('postConceptionalAge').value = ''; 
 +    document.getElementById('bun').value = ''; 
 +    document.getElementById('glucose').value = ''; 
 +    document.getElementById('sodium').value = ''; 
 +    document.getElementById('ph').value = ''; 
 +    document.getElementById('baseExcess').value = ''; 
 +    document.getElementById('diuresis').value = ''; 
 +    document.getElementById('prescribingDoctor').value = ''; 
 +     
 +    // Reset pulsanti TAB 1 
 +    const phaseBtn = document.getElementById('calculatePhaseBtn'); 
 +    if (phaseBtn) { 
 +        phaseBtn.className = 'button calculate-phase-pending'; 
 +        phaseBtn.innerHTML = 'CALCOLA FASE NUTRIZIONALE'; 
 +        phaseBtn.disabled = false;
     }     }
-    if (electrolyteAdditions.esafosfina > 0) { +     
-        resultHtml += '<tr><td><strong>Esafosfina (5g/50mL)</strong></td><td><strong>' + electrolyteAdditions.esafosfina.toFixed(1) + '</strong></td></tr>';+    // Nascondi risultati fase 
 +    const phaseResults = document.getElementById('phaseResults'); 
 +    if (phaseResults) { 
 +        phaseResults.classList.add('hidden');
     }     }
-    if (electrolyteAdditions.mg_sulfate > 0+     
-        resultHtml += '<tr><td><strong>Magnesio Solfato (2g/10mL, 1.6 mEq/mL)</strong></td><td><strong>+ electrolyteAdditions.mg_sulfate.toFixed(1'</strong></td></tr>';+    // Reset TAB 2 - Nutrizione Enterale 
 +    document.getElementById('formulaType').value = 'none'; 
 +    document.getElementById('dailyVolume').value = '0'; 
 +    document.getElementById('additionalFluids').value = '0'; 
 +    document.getElementById('fluidType').value = 'saline'; 
 +    document.getElementById('fluidRoute').value = 'iv'; 
 +     
 +    // Reset pulsanti TAB 2 
 +    const enteralBtn = document.getElementById('calculateEnteralBtn'); 
 +    if (enteralBtn) { 
 +        enteralBtn.className = 'button calculate-nutrition-pending'; 
 +        enteralBtn.innerHTML = 'Calcola Apporti Enterali';
     }     }
-    if (electrolyteAdditions.nacl > 0) { +     
-        resultHtml += '<tr><td><strong>Sodio Cloruro (3mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.nacl.toFixed(1) + '</strong></td></tr>'; +    // Nascondi risultati enterali 
-    +    const enteralResults document.getElementById('enteralResults')
-    if (electrolyteAdditions.sodium_acetate > 0) { +    if (enteralResults) { 
-        resultHtml +'<tr><td><strong>Sodio Acetato (2 mEq/mL) - Alcalinizzante</strong></td><td><strong>' + electrolyteAdditions.sodium_acetate.toFixed(1) + '</strong></td></tr>'; +        enteralResults.classList.add('hidden');
-    } +
-    if (electrolyteAdditions.kcl > 0) { +
-        resultHtml += '<tr><td><strong>Potassio Cloruro (2 mEq/mL)</strong></td><td><strong>' + electrolyteAdditions.kcl.toFixed(1) + '</strong></td></tr>';+
     }     }
          
-    if (residualNeeds.vitalipid > 0{ +    // Reset TAB 3 - Fabbisogni 
-        const vitalipidVolume residualNeeds.vitalipid * currentWeightKg+    document.getElementById('targetDay').value = '9'; 
-        resultHtml += '<tr><td><strong>Vitalipid N Infant</strong></td><td><strong>+ vitalipidVolume.toFixed(1'</strong></td></tr>';+    document.getElementById('weightCategory').value = ''; 
 +    resetNutritionFields(); 
 +     
 +    // Reset pulsanti TAB 3 
 +    const loadBtn document.getElementById('loadDefaultsBtn')
 +    const nutritionBtn document.getElementById('calculateNutritionBtn'); 
 +    if (loadBtn
 +        loadBtn.className = 'button load-defaults-pending'; 
 +        loadBtn.innerHTML = 'Carica Valori Standard';
     }     }
-    if (residualNeeds.soluvit > 0) { +    if (nutritionBtn) { 
-        const soluvitVolume = residualNeeds.soluvit * currentWeightKg; +        nutritionBtn.className = 'button calculate-nutrition-pending'; 
-        resultHtml += '<tr><td><strong>Soluvit N</strong></td><td><strong>' + soluvitVolume.toFixed(1) + '</strong></td></tr>'; +        nutritionBtn.innerHTML = 'CALCOLA FABBISOGNI';
-    } +
-    if (residualNeeds.peditrace > 0) { +
-        const peditraceVolume = residualNeeds.peditrace * currentWeightKg; +
-        resultHtml += '<tr><td><strong>Peditrace</strong></td><td><strong>' + peditraceVolume.toFixed(1) + '</strong></td></tr>';+
     }     }
          
-    if (residualNeeds.carnitine > 0) { +    // Nascondi risultati nutrizione 
-        resultHtml += '<tr><td><strong>Carnitene</strong></td><td><strong>' + carnitineVolume.toFixed(1) + '</strong></td></tr>';+    const nutritionResults = document.getElementById('nutritionResults'); 
 +    if (nutritionResults) { 
 +        nutritionResults.classList.add('hidden');
     }     }
          
-    if (waterVolume > 0) { +    // Reset TAB 4 - Parenterale 
-        resultHtml += '<tr><td><strong>Acqua Bidistillata</strong></td><td><strong>' + waterVolume.toFixed(1+ '</strong></td></tr>'; +    resetParenteralFields();
-    }+
          
-    resultHtml += '<tr class="energy-highlight"><td><strong>TOTALE NPT</strong></td><td><strong>' + totalVolume.toFixed(1+ ' ml</strong></td></tr>'; +    // Reset TAB 5 - Report 
-    resultHtml += '</table>';+    resetReportFields();
          
-    document.getElementById('parenteralTable').innerHTML resultHtml;+    updateFortifierOptions()
 +
 + 
 +function resetNutritionFields() { 
 +    const nutritionFields 
 +        'reqLiquids', 'reqProtein', 'reqCarbs', 'reqLipids', 
 +        'reqCalcium', 'reqPhosphorus', 'reqMagnesium', 'reqSodium', 'reqPotassium', 
 +        'reqVitalipid', 'reqSoluvit', 'reqPeditrace', 'reqCarnitine' 
 +    ];
          
-    // PREPARAZIONE CON DEFLUSSORE +    nutritionFields.forEach(fieldId => { 
-    const deflectorVolume parseInt(document.getElementById('deflectorVolume').value) || 30+        const field = document.getElementById(fieldId)
-    const totalVolumeWithDeflector = totalVolume + deflectorVolume;+        if (field) { 
 +            field.value = '0'; 
 +        } 
 +    });
          
-    let preparationHtml = '<div class="info">'; +    // Reset unità carboidrati 
-    preparationHtml += '<strong>📋 RICETTA PREPARAZIONE (Deflussore: + deflectorVolume + ml)</strong><br>'; +    document.getElementById('carbUnit').value = 'g'; 
-    preparationHtml += '• <strong>Volume prescrizione:</strong> ' + totalVolume + ' ml<br>'; +    document.getElementById('carbLabel').textContent = 'Glucidi (g/kg/die):';
-    preparationHtml += '• <strong>Volume totale preparazione:</strong> + totalVolumeWithDeflector + ' ml'; +
-    preparationHtml += '</div>';+
          
-    preparationHtml += '<table class="results-table">'+    // Reset tipo sodio 
-    preparationHtml += '<tr><th>Componente</th><th>Prescrizione (ml)</th><th>Preparazione (ml)</th></tr>';+    document.getElementById('sodiumType').value = 'nacl';
          
-    const ratio totalVolumeWithDeflector / totalVolume;+    // Nascondi raccomandazione sodio 
 +    const sodiumRec document.getElementById('sodiumRecommendation'); 
 +    if (sodiumRec) { 
 +        sodiumRec.classList.add('hidden'); 
 +    } 
 +
 + 
 +function resetParenteralFields() { 
 +    document.getElementById('calculatedTotalVolume').value = "Premere 'Calcola NPT'"; 
 +    document.getElementById('suggestedGlucose').value = "Premere 'Calcola NPT'"; 
 +    document.getElementById('calculatedProteinVol').value = "--"; 
 +    document.getElementById('calculatedLipidVol').value = "--";
          
-    if (neededGlucose > 0) { +    const parenteralBtn = document.getElementById('calculateParenteralBtn'); 
-        preparationHtml += '<tr><td><strong>Glucosio 50%</strong></td><td>+ glucose50Volume.toFixed(1) + '</td><td><strong>' + (glucose50Volume * ratio).toFixed(1) + '</strong></td></tr>';+    if (parenteralBtn) { 
 +        parenteralBtn.className = 'button'
 +        parenteralBtn.innerHTML = 'CALCOLA NPT AUTOMATICA';
     }     }
          
-    preparationHtml += '<tr><td><strong>Trophamine 6%</strong></td><td>+ proteinVolume.toFixed(1'</td><td><strong>(proteinVolume * ratio).toFixed(1'</strong></td></tr>'; +    const parenteralResults document.getElementById('parenteralResults'); 
-    preparationHtml += '<tr><td><strong>Intralipid 20%</strong></td><td>+ Math.max(0, lipidVolume).toFixed(1) + '</td><td><strong>(Math.max(0, lipidVolume) * ratio).toFixed(1'</strong></td></tr>';+    if (parenteralResults
 +        parenteralResults.classList.add('hidden'); 
 +    } 
 +
 + 
 +function resetReportFields() 
 +    // Reset dropdown personale 
 +    document.getElementById('validatingPharmacist').value = ''; 
 +    document.getElementById('preparingTechnician1').value = ''
 +    document.getElementById('preparingTechnician2').value = ''
 +     
 +    // Reset pulsanti validazione/preparazione 
 +    const validateBtn = document.getElementById('validatePrescriptionBtn'); 
 +    const confirmBtn = document.getElementById('confirmPreparationBtn')
 +    const downloadBtn = document.getElementById('downloadBtn')
 +    const lockBtn = document.getElementById('lockPrescriptionBtn');
          
-    if (electrolyteAdditions.ca_gluconato > 0) { +    if (validateBtn) { 
-        preparationHtml += '<tr><td><strong>Calcio Gluconato 10% (1g/10mL, 0.44 mEq/mL)</strong></td><td>+ electrolyteAdditions.ca_gluconato.toFixed(1) + '</td><td><strong>+ (electrolyteAdditions.ca_gluconato * ratio).toFixed(1) + '</strong></td></tr>';+        validateBtn.className = 'button'
 +        validateBtn.innerHTML = '✅ VALIDA PRESCRIZIONE'
 +        validateBtn.disabled = false;
     }     }
-    if (electrolyteAdditions.esafosfina > 0) { +     
-        preparationHtml += '<tr><td><strong>Esafosfina (5g/50mL)</strong></td><td>+ electrolyteAdditions.esafosfina.toFixed(1) + '</td><td><strong>+ (electrolyteAdditions.esafosfina * ratio).toFixed(1) + '</strong></td></tr>';+    if (confirmBtn) { 
 +        confirmBtn.className = 'button'
 +        confirmBtn.innerHTML = '🧪 CONFERMA ALLESTIMENTO'
 +        confirmBtn.disabled = true;
     }     }
-    if (electrolyteAdditions.mg_sulfate > 0) { +     
-        preparationHtml += '<tr><td><strong>Magnesio Solfato (2g/10mL, 1.6 mEq/mL)</strong></td><td>+ electrolyteAdditions.mg_sulfate.toFixed(1'</td><td><strong>' + (electrolyteAdditions.mg_sulfate * ratio).toFixed(1) + '</strong></td></tr>';+    if (downloadBtn) { 
 +        downloadBtn.className = 'button secondary'; 
 +        downloadBtn.innerHTML = '💾 ARCHIVIA PREPARAZIONE (JSON)'
 +        downloadBtn.disabled = true;
     }     }
-    if (electrolyteAdditions.nacl > 0) { +     
-        preparationHtml += '<tr><td><strong>Sodio Cloruro (3mEq/mL)</strong></td><td>+ electrolyteAdditions.nacl.toFixed(1) + '</td><td><strong>+ (electrolyteAdditions.nacl * ratio).toFixed(1) + '</strong></td></tr>';+    if (lockBtn) { 
 +        lockBtn.className = 'button'
 +        lockBtn.innerHTML = '🔒 BLOCCA PRESCRIZIONE'
 +        lockBtn.disabled = true; 
 +        lockBtn.style.backgroundColor = '#e74c3c';
     }     }
-    if (electrolyteAdditions.sodium_acetate > 0{ +     
-        preparationHtml += '<tr><td><strong>Sodio Acetato (2 mEq/mL- Alcalinizzante</strong></td><td>' + electrolyteAdditions.sodium_acetate.toFixed(1'</td><td><strong>(electrolyteAdditions.sodium_acetate * ratio).toFixed(1'</strong></td></tr>';+    // Nascondi status 
 +    const validationStatus = document.getElementById('validationStatus'); 
 +    const preparationStatus = document.getElementById('preparationStatus'); 
 +    if (validationStatus) validationStatus.style.display = 'none'; 
 +    if (preparationStatuspreparationStatus.style.display = 'none'; 
 +     
 +    // Reset area report 
 +    document.getElementById('reportOutput').innerHTML = ''
 +
 + 
 + 
 +// SISTEMA DI ARCHIVIAZIONE JSON 
 +function generatePreparationID() 
 +    const medicalRecord = patientData.medicalRecord; 
 +    let prescriptionDate = patientData.prescriptionDate; // ✅ Cambiato da const a let 
 +     
 +    if (!medicalRecord || medicalRecord.trim() === '') { 
 +        return null;
     }     }
-    if (electrolyteAdditions.kcl > 0) { +     
-        preparationHtml +'<tr><td><strong>Potassio Cloruro (2 mEq/mL)</strong></td><td>' + electrolyteAdditions.kcl.toFixed(1) + '</td><td><strong>' + (electrolyteAdditions.kcl * ratio).toFixed(1) + '</strong></td></tr>';+    if (!prescriptionDate || prescriptionDate.trim() === '') { 
 +        // Usa data odierna se non specificata 
 +        const today new Date().toISOString().split('T')[0]; 
 +        prescriptionDate = today; // ✅ Ora funziona correttamente
     }     }
          
-    if (residualNeeds.vitalipid > 0{ +    // Converte la data da YYYY-MM-DD a DDMMYYYY 
-        const vitalipidVolume residualNeeds.vitalipid * currentWeightKg+    const dateObj = new Date(prescriptionDate); 
-        preparationHtml +'<tr><td><strong>Vitalipid N Infant</strong></td><td>' + vitalipidVolume.toFixed(1) + '</td><td><strong>(vitalipidVolume * ratio).toFixed(1) + '</strong></td></tr>';+    const day dateObj.getDate().toString().padStart(2, '0')
 +    const month (dateObj.getMonth() + 1).toString().padStart(2, '0'); 
 +    const year = dateObj.getFullYear().toString()
 +    const formattedDate = day month + year; 
 +     
 +    // Crea chiave univoca per cartella + data 
 +    const counterKey = medicalRecord + '_' + formattedDate; 
 +     
 +    // Inizializza il contatore se non esiste 
 +    if (!window.preparationCounter) { 
 +        window.preparationCounter = {};
     }     }
-    if (residualNeeds.soluvit > 0) { +     
-        const soluvitVolume = residualNeeds.soluvit * currentWeightKg; +    if (!window.preparationCounter[counterKey]) { 
-        preparationHtml += '<tr><td><strong>Soluvit N</strong></td><td>' + soluvitVolume.toFixed(1) + '</td><td><strong>' + (soluvitVolume * ratio).toFixed(1) + '</strong></td></tr>'; +        window.preparationCounter[counterKey] 0;
-    } +
-    if (residualNeeds.peditrace > 0) { +
-        const peditraceVolume = residualNeeds.peditrace * currentWeightKg; +
-        preparationHtml +'<tr><td><strong>Peditrace</strong></td><td>' + peditraceVolume.toFixed(1) + '</td><td><strong>' + (peditraceVolume * ratio).toFixed(1) + '</strong></td></tr>';+
     }     }
          
-    if (residualNeeds.carnitine > 0) { +    // Incrementa il contatore 
-        preparationHtml += '<tr><td><strong>Carnitene (100 mg/ml)</strong></td><td>' + carnitineVolume.toFixed(1) + '</td><td><strong>' + (carnitineVolume * ratio).toFixed(1) + '</strong></td></tr>';+    window.preparationCounter[counterKey]++; 
 +     
 +    // Genera l'ID con formato: CARTELLA_DDMMYYYY_NN 
 +    const counter = window.preparationCounter[counterKey].toString().padStart(2, '0'); 
 +    const preparationID medicalRecord + '_' + formattedDate + '_' + counter; 
 +     
 +    return preparationID; 
 +
 +function createPreparationJSON() 
 +    if (!window.residualNeeds || !window.nptCalculation || !patientData.currentWeight) { 
 +        alert('❌ Errore: Prima completare tutti i calcoli NPT (TAB 1-4)'); 
 +        return null;
     }     }
          
-    if (waterVolume > 0) { +    // Genera ID preparazione 
-        preparationHtml += '<tr><td><strong>Acqua Bidistillata</strong></td><td>+ waterVolume.toFixed(1) + '</td><td><strong>' + (waterVolume * ratio).toFixed(1) + '</strong></td></tr>';+    const preparationID = generatePreparationID(); 
 +    if (!preparationID) { 
 +        alert('❌ Errore: Impossibile generare ID preparazione. Verificare cartella clinica e data.')
 +        return null;
     }     }
          
-    preparationHtml += '<tr class="energy-highlight"><td><strong>TOTALE</strong></td><td><strong>+ totalVolume + ml</strong></td><td><strong>+ totalVolumeWithDeflector + ' ml</strong></td></tr>'; +    // Recupera dati personale 
-    preparationHtml += '</table>';+    const pharmacistKey = document.getElementById('validatingPharmacist').value; 
 +    const tech1Key = document.getElementById('preparingTechnician1').value
 +    const tech2Key document.getElementById('preparingTechnician2').value;
          
-    document.getElementById('preparationTable').innerHTML = preparationHtml+    const pharmacistName = pharmacistKey ? pharmacistsData[pharmacistKey].fullName : 'NON SPECIFICATO'; 
-    document.getElementById('parenteralResults').classList.remove('hidden');+    const tech1Name = tech1Key ? technicianData[tech1Key].fullName : 'NON SPECIFICATO'
 +    const tech2Name = tech2Key ? technicianData[tech2Key].fullName : 'NON SPECIFICATO';
          
-    // Salva i dati per i report +    // Crea oggetto JSON completo 
-    window.nptCalculationData = { +    const preparationData = { 
-        currentWeight, currentWeightKg, totalVolume, electrolyteAdditions+        // IDENTIFICAZIONE 
-        proteinVolume, lipidVolume, vitaminsVolumecarnitineVolume+        preparationID: preparationID, 
-        glucose50VolumewaterVolumeneededGlucoseresidualNeeds+        cartellaClinica: patientData.medicalRecord, 
 +        dataPrescrizione: patientData.prescriptionDate, 
 +        dataCreazione: new Date().toISOString(), 
 +         
 +       // DATI PAZIENTE 
 +        paziente: { 
 +            pesoAttuale: patientData.currentWeight, 
 +            pesoNascita: patientData.birthWeight || 0, 
 +            giorniVita: patientData.daysOfLife || 0, 
 +            etaGestazionale:
 +            settimane: patientData.gestationalWeeks || null, 
 +            giorni: patientData.gestationalDays || null, 
 +            formato: patientData.gestationalWeeks && patientData.gestationalWeeks > 0 ?  
 +            patientData.gestationalWeeks + '+' + (patientData.gestationalDays || 0) : null 
 +            } 
 +        }, 
 +         
 +        // DATI CLINICI 
 +        parametriClinici:
 +            bun: patientData.bun || null, 
 +            glicemia: patientData.glucose || null, 
 +            natremia: patientData.sodium || null, 
 +            ph: patientData.ph || null, 
 +            baseExcess: patientData.baseExcess || null, 
 +            diuresi: patientData.diuresis || null 
 +        }, 
 +         
 +        // COMPOSIZIONE NPT 
 +        npt: { 
 +            volumeTotale: window.nptCalculation.totalVolume, 
 +            energia: window.residualNeeds.energy.toFixed(1), 
 +            proteine: window.residualNeeds.protein.toFixed(2), 
 +            lipidi: window.residualNeeds.lipids.toFixed(2), 
 +            glucidi: window.residualNeeds.carbs.toFixed(2), 
 +            gir: window.nptCalculation.gir.toFixed(1), 
 +            osmolarita: window.nptCalculation.osmolarityData ? window.nptCalculation.osmolarityData.total : 0, 
 +            velocitaInfusione: (window.nptCalculation.totalVolume / 24).toFixed(2) 
 +        }, 
 +         
 +        // COMPONENTI DETTAGLIATI 
 +        componenti: { 
 +            glucosio50: window.nptCalculation.glucose50Volume.toFixed(1), 
 +            trophamine: window.nptCalculation.proteinVolume.toFixed(1), 
 +            intralipid: window.nptCalculation.lipidVolume.toFixed(1), 
 +            acquaBidistillata: window.nptCalculation.waterVolume.toFixed(1), 
 +            elettroliti: window.nptCalculation.electrolyteAdditions 
 +        }
 +         
 +        // PERSONALE 
 +        personale: { 
 +            medicoPrescrittore: patientData.prescribingDoctorName || 'NON SPECIFICATO', 
 +            farmacistValidatore: pharmacistName, 
 +            tecnico1: tech1Name, 
 +            tecnico2: tech2Name 
 +        }, 
 +         
 +        // METADATA 
 +        sistema: { 
 +            versione: "NPT Calculator v3.0 UNIFIED", 
 +            dataCalcolo: new Date().toISOString() 
 +        }
     };     };
          
-    const parenteralBtn = document.getElementById('calculateParenteralBtn'); +    return preparationData;
-    if (parenteralBtn) { +
-        parenteralBtn.className = 'button config-update-completed'; +
-        parenteralBtn.innerHTML = 'NPT CALCOLATA ✓'; +
-    }+
 } }
  
-// FUNZIONI REPORT +function downloadPreparationJSON() { 
-function generateAndShowWorkReport() { +    console.log('Inizio generazione JSON preparazione...'); 
-    if (!window.nptCalculationData{ +     
-        alert('Prima calcolare la NPT!'); +    const preparationData = createPreparationJSON(); 
-        return;+    if (!preparationData) { 
 +        return; // Errore già mostrato in createPreparationJSON
     }     }
          
-    const reportHtml generateWorkReportHTML(); +    try { 
-    document.getElementById('nptWorkReport').innerHTML reportHtml+        // Crea il file JSON 
-    document.getElementById('nptWorkReport').classList.remove('hidden'); +        const jsonString JSON.stringify(preparationData, null, 2); 
-    document.getElementById('nptFinalReport').classList.add('hidden'); +        const blob = new Blob([jsonString], { type: 'application/json})
-    document.getElementById('printReportBtn').classList.remove('hidden')+         
-    document.getElementById('savePdfBtn').classList.remove('hidden'); +        // Nome file: NPT_[ID].json 
-    window.currentActiveReport 'work'+        const filename `NPT_${preparationData.preparationID}.json`
-     +         
-    const generateBtn = document.getElementById('generateWorkReportBtn'); +        // Download automatico 
-    generateBtn.innerHTML = 'Foglio di Lavoro Generato ✓'; +        const url = URL.createObjectURL(blob); 
-    generateBtn.className = 'button config-update-completed';+        const a = document.createElement('a')
 +        a.href = url; 
 +        a.download = filename; 
 +        document.body.appendChild(a); 
 +        a.click()
 +        document.body.removeChild(a); 
 +        URL.revokeObjectURL(url); 
 +         
 +        // Feedback successo 
 +        document.getElementById('downloadBtn').className = 'button config-update-completed'; 
 +        document.getElementById('downloadBtn').innerHTML = '💾 ARCHIVIAZIONE COMPLETATA ✓'
 +         
 +        alert(`✅ Preparazione archiviata con successo!\n\n` + 
 +              `📋 ID: ${preparationData.preparationID}\n` + 
 +              `📁 File: ${filename}\n` + 
 +              `📊 Dati: ${Object.keys(preparationData).length} sezioni salvate`); 
 +        // Salva ID per il sistema di blocco 
 +        window.lastPreparationID preparationData.preparationID
 +         
 +        console.log('JSON generato con successo:', preparationData); 
 +         
 +    } catch (error) { 
 +        console.error('Errore nella generazione JSON:', error)
 +        alert('❌ Errore nella generazione del file JSON:\n+ error.message); 
 +    }
 } }
  
-function generateAndShowFinalReport() { + 
-    if (!window.nptCalculationData) { +// ===================================================== 
-        alert('Prima calcolare la NPT!');+// SISTEMA ARCHIVIAZIONE MENSILE EXCEL 
 +// ===================================================== 
 + 
 +// Variabile globale per i dati mensili 
 +window.monthlyPreparations = []; 
 + 
 +// Funzione per inizializzare il mese corrente 
 +function initializeMonthlySection() { 
 +    const now = new Date(); 
 +    const currentMonth = now.getFullYear() + '-' + (now.getMonth() + 1).toString().padStart(2, '0'); 
 +    document.getElementById('selectedMonth').value = currentMonth; 
 +
 + 
 +// Funzione anteprima dati mensili 
 +function previewMonthlyData() { 
 +    const fileInput = document.getElementById('jsonFilesInput'); 
 +    const files = fileInput.files; 
 +     
 +    if (!files || files.length === 0) { 
 +        alert('⚠️ Seleziona prima i file JSON da consolidare');
         return;         return;
     }     }
          
-    const reportHtml = generateFinalReportHTML(); +    // Reset dati precedenti 
-    document.getElementById('nptFinalReport').innerHTML = reportHtml; +    window.monthlyPreparations [];
-    document.getElementById('nptFinalReport').classList.remove('hidden'); +
-    document.getElementById('nptWorkReport').classList.add('hidden'); +
-    document.getElementById('printReportBtn').classList.remove('hidden'); +
-    document.getElementById('savePdfBtn').classList.remove('hidden'); +
-    window.currentActiveReport 'final';+
          
-    const generateBtn document.getElementById('generateFinalReportBtn'); +    let processedFiles = 0; 
-    generateBtn.innerHTML = 'Report Parenterale Generato ✓'; +    const totalFiles files.length; 
-    generateBtn.className = 'button config-update-completed';+     
 +    // Processa tutti i file JSON 
 +    Array.from(files).forEach((file, index) => { 
 +        const reader = new FileReader(); 
 +         
 +        reader.onload function(e) { 
 +            try { 
 +                const jsonData = JSON.parse(e.target.result); 
 +                 
 +                // Valida che sia un file NPT valido 
 +                if (validateNPTJson(jsonData)) { 
 +                    window.monthlyPreparations.push(jsonData); 
 +                } else { 
 +                    console.warn('File non valido ignorato:', file.name)
 +                } 
 +                 
 +                processedFiles++; 
 +                 
 +                // Quando tutti i file sono processati, mostra l'anteprima 
 +                if (processedFiles === totalFiles) { 
 +                    showMonthlyPreview(); 
 +                } 
 +                 
 +            } catch (error) { 
 +                console.error('Errore parsing JSON:', file.name, error); 
 +                processedFiles++; 
 +                 
 +                if (processedFiles === totalFiles) { 
 +                    showMonthlyPreview(); 
 +                } 
 +            } 
 +        }; 
 +         
 +        reader.readAsText(file); 
 +    });
 } }
  
-function generateWorkReportHTML() { +// Funzione di validazione JSON NPT 
-    const data = window.nptCalculationData+function validateNPTJson(data) { 
-    const deflectorVolume parseInt(document.getElementById('deflectorVolume').value) || 30+    return data &&  
-    const totalVolumeWithDeflector data.totalVolume + deflectorVolume+           data.preparationID &&  
-    const ratio totalVolumeWithDeflector / data.totalVolume;+           data.cartellaClinica &&  
 +           data.npt &&  
 +           data.paziente && 
 +           data.sistema && 
 +           data.sistema.versione; 
 +
 + 
 +// Funzione per mostrare l'anteprima 
 +function showMonthlyPreview() { 
 +    const statsDiv = document.getElementById('monthlyStats'); 
 +    const selectedMonth document.getElementById('selectedMonth').value
 +    const monthName new Date(selectedMonth + '-01').toLocaleDateString('it-IT', {  
 +        year: 'numeric',  
 +        month: 'long'  
 +    });
          
-    const today new Date(); +    if (window.monthlyPreparations.length === 0{ 
-    const dateStr today.toLocaleDateString('it-IT'); +        statsDiv.innerHTML = '<div class="error">❌ Nessun file NPT valido trovato</div>'; 
-     +        statsDiv.style.display = 'block'; 
-    const doctorName = patientData.prescribingDoctor ?  +        return; 
-        doctorsData[patientData.prescribingDoctor]?.fullName || 'N/A' : 'N/A';+    }
          
-    const infusionRate = (data.totalVolume 24).toFixed(2); +    // Calcola statistiche 
-    const finalConcentration = data.neededGlucose > 0 ? (data.neededGlucose * 100) data.totalVolume : 0; +    const stats calculateMonthlyStats(window.monthlyPreparations);
-    const estimatedOsmolarity = (finalConcentration * 55).toFixed(0);+
          
-    let html = '<div class="npt-report">'; +    let html = '<div class="info">'; 
-     +    html += '<h4 style="margin-top: 0;">📊 ANTEPRIMA - ' + monthName + '</h4>'; 
-    // Header +    html += '<p><strong>File NPT trovati:</strong> ' + window.monthlyPreparations.length + '</p>'; 
-    html += '<div class="report-header">'; +    html += '<p><strong>Pazienti unici:</strong> ' + stats.uniquePatients + '</p>'; 
-    html += '<div class="report-header-left">'; +    html += '<p><strong>Peso medio:</strong' + stats.averageWeight.toFixed(0) + 'g</p>'; 
-    html += '<div style="font-weight: bold; font-size: 13px;">CALCOLO NUTRIZIONALE PARENTERALE Data: ' + dateStr + '</div>'; +    html += '<p><strong>GIR medio:</strong> ' + stats.averageGIR.toFixed(1) + ' mg/kg/min</p>'; 
-    html += '<div style="font-size11px; color: #666;">FOGLIO DI LAVORO</div>'; +    html += '<p><strong>Volume medio NPT:</strong> ' + stats.averageVolume.toFixed(0) + ' ml</p>';
-    html += '</div>'; +
-    html += '<div class="report-header-right">LOGO OSPEDALE</div>';+
     html += '</div>';     html += '</div>';
          
-    // Info Paziente +    html += '<div class="warningstyle="font-size: 12pxmargin-top: 10px;">'; 
-    html += '<div class="report-section">'; +    html += '<strong>📋 File da processare:</strong><br>'; 
-    html += '<div class="report-section-title">INFO Paziente</div>'; +    window.monthlyPreparations.forEach(prep => { 
-    html += '<table class="report-table">'; +        html += '• ' + prep.preparationID + ' (Cartella: ' + prep.cartellaClinica + ')<br>'; 
-    html += '<tr><td class="label-col">Medico Prescrittore</td><td class="value-col">' + doctorName + '</td></tr>'; +    });
-    html += '<tr><td class="label-col">Data Prescrizione</td><td class="value-col">' + dateStr + '</td></tr>'; +
-    html +'<tr><td class="label-col">Paziente</td><td class="value-col">' + (patientData.medicalRecord || 'N/A') + '</td></tr>'; +
-    html += '<tr><td class="label-col">Giorni di Vita</td><td class="value-col">' + patientData.daysOfLife + '</td></tr>'; +
-    html += '<tr><td class="label-col">Peso (g)</td><td class="value-col">' + data.currentWeight + '</td></tr>'; +
-    html += '</table>';+
     html += '</div>';     html += '</div>';
          
-    // Composizione +    statsDiv.innerHTML = html; 
-    html +'<div class="report-section">'; +    statsDiv.style.display = 'block';
-    html += '<div class="report-section-title">Composizione Parenterale (numero sacche: 1)</div>'+
-    html += '<table class="composition-table">'; +
-    html += '<tr><th class="component-name-col"></th><th>Teorici</th><th>Con Deflussore</th><th></th></tr>';+
          
-    if (data.waterVolume > 0) { +    // Abilita il pulsante Excel 
-        html += '<tr><td class="component-name-col">Acqua bidistillata</td><td>+ data.waterVolume.toFixed(2) + '</td><td>+ (data.waterVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +    document.getElementById('generateExcelBtn').disabled = false; 
-    +    document.getElementById('generateExcelBtn').className = 'button'; 
-    if (data.glucose50Volume > 0) { +    document.getElementById('generateExcelBtn').innerHTML = '📊 GENERA EXCEL MENSILE (' + window.monthlyPreparations.length + ' NPT)'; 
-        html += '<tr><td class="component-name-col">glucosata 50% (parenterale)</td><td>' + data.glucose50Volume.toFixed(2) + '</td><td>' + (data.glucose50Volume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    + 
-    if (data.electrolyteAdditions.ca_gluconato > 0) { +// Funzione per calcolare statistiche mensili 
-        html +'<tr><td class="component-name-col">Calcio gluconato (1g/10mL,0,44mEq/mL)</td><td>' + data.electrolyteAdditions.ca_gluconato.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.ca_gluconato * ratio).toFixed(2) + '</td><td>ml</td></tr>'+function calculateMonthlyStats(preparations) { 
-    +    const uniquePatients new Set(preparations.map(p =p.cartellaClinica)).size
-    if (data.electrolyteAdditions.nacl > 0) { +    const totalWeight preparations.reduce((sum, p=sum + (p.paziente.pesoAttuale || 0), 0); 
-        html +'<tr><td class="component-name-col">Sodio cloruro (3mEq/mL)</td><td>' + data.electrolyteAdditions.nacl.toFixed(2+ '</td><td>' + (data.electrolyteAdditions.nacl * ratio).toFixed(2+ '</td><td>ml</td></tr>'+    const totalGIR preparations.reduce((sum, p=sum + (parseFloat(p.npt.gir|| 0), 0); 
-    +    const totalVolume preparations.reduce((sum, p=sum + (p.npt.volumeTotale || 0), 0); 
-    if (data.electrolyteAdditions.sodium_acetate > 0) { +     
-        html +'<tr><td class="component-name-col">Sodio acetato (2mEq/mL)</td><td>' + data.electrolyteAdditions.sodium_acetate.toFixed(2+ '</td><td>' + (data.electrolyteAdditions.sodium_acetate * ratio).toFixed(2+ '</td><td>ml</td></tr>'+    return 
-    +        uniquePatients: uniquePatients, 
-    if (data.electrolyteAdditions.kcl > 0) { +        averageWeight: totalWeight preparations.length, 
-        html +'<tr><td class="component-name-col">Potassio cloruro (2mEq/mL)</td><td>' + data.electrolyteAdditions.kcl.toFixed(2+ '</td><td>' + (data.electrolyteAdditions.kcl * ratio).toFixed(2+ '</td><td>ml</td></tr>'+        averageGIR: totalGIR preparations.length, 
-    } +        averageVolume: totalVolume preparations.length 
-    if (data.electrolyteAdditions.mg_sulfate > 0) +    }
-        html += '<tr><td class="component-name-col">Magnesio solfato (2g/10mL,1.6mEq/mL)</td><td>' + data.electrolyteAdditions.mg_sulfate.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.mg_sulfate * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } + 
-    if (data.carnitineVolume > 0) { +// Funzione principale per generare Excel mensile 
-        html += '<tr><td class="component-name-col">Carnitene f</td><td>+ data.carnitineVolume.toFixed(2) + '</td><td>' + (data.carnitineVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+function generateMonthlyExcel() { 
 +    if (!window.monthlyPreparations || window.monthlyPreparations.length === 0) { 
 +        alert('⚠️ Prima esegui l\'anteprima per caricare i dati')
 +        return;
     }     }
          
-    html += '<tr><td class="component-name-col">Trophamine 6%</td><td>' + data.proteinVolume.toFixed(2+ '</td><td>'(data.proteinVolume * ratio).toFixed(2+ '</td><td>ml</td></tr>'+    try { 
-     +        // Crea un nuovo workbook 
-    if (data.electrolyteAdditions.esafosfina > 0{ +        const wb = XLSX.utils.book_new()
-        html +'<tr><td class="component-name-col">Esafosfina f 5g</td><td>' + data.electrolyteAdditions.esafosfina.toFixed(2+ '</td><td>'(data.electrolyteAdditions.esafosfina * ratio).toFixed(2+ '</td><td>ml</td></tr>'+         
-    } +        // FOGLIO 1: Riepilogo Mensile 
-    if (data.residualNeeds.peditrace > 0{ +        const summaryData = createSummarySheet(window.monthlyPreparations)
-        const peditraceVolume data.residualNeeds.peditrace * data.currentWeightKg+        const ws_summary = XLSX.utils.aoa_to_sheet(summaryData); 
-        html += '<tr><td class="component-name-col">Peditrace</td><td>' + peditraceVolume.toFixed(2) + '</td><td>+ (peditraceVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +        XLSX.utils.book_append_sheet(wb, ws_summary, "Riepilogo Mensile"); 
-    } +         
-    if (data.residualNeeds.soluvit > 0) { +        // FOGLIO 2: Dettaglio Preparazioni 
-        const soluvitVolume = data.residualNeeds.soluvit * data.currentWeightKg+        const detailData = createDetailSheet(window.monthlyPreparations); 
-        html += '<tr><td class="component-name-col">Soluvit</td><td>+ soluvitVolume.toFixed(2) + '</td><td>+ (soluvitVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +        const ws_detail XLSX.utils.aoa_to_sheet(detailData); 
-    } +        XLSX.utils.book_append_sheet(wb, ws_detail, "Dettaglio Preparazioni")
-    if (data.residualNeeds.vitalipid > 0) { +         
-        const vitalipidVolume = data.residualNeeds.vitalipid * data.currentWeightKg+        // FOGLIO 3: Statistiche Cliniche 
-        html += '<tr><td class="component-name-col">Vitalipid N</td><td>' + vitalipidVolume.toFixed(2) + '</td><td>' + (vitalipidVolume * ratio).toFixed(2+ '</td><td>ml</td></tr>';+        const statsData = createStatsSheet(window.monthlyPreparations); 
 +        const ws_stats = XLSX.utils.aoa_to_sheet(statsData)
 +        XLSX.utils.book_append_sheet(wb, ws_stats, "Statistiche Cliniche"); 
 +         
 +        // FOGLIO 4: Componenti NPT 
 +        const componentsData = createComponentsSheet(window.monthlyPreparations); 
 +        const ws_components XLSX.utils.aoa_to_sheet(componentsData)
 +        XLSX.utils.book_append_sheet(wb, ws_components, "Componenti NPT"); 
 +         
 +        // Genera nome file 
 +        const selectedMonth = document.getElementById('selectedMonth').value; 
 +        const monthYear = selectedMonth.replace('-', '_')
 +        const fileName = `NPT_Consolidato_${monthYear}.xlsx`; 
 +         
 +        // Salva il file 
 +        XLSX.writeFile(wb, fileName)
 +         
 +        // Feedback successo 
 +        document.getElementById('generateExcelBtn').className 'button config-update-completed'
 +        document.getElementById('generateExcelBtn').innerHTML = '📊 EXCEL GENERATO ✓'; 
 +         
 +        alert(`✅ Excel generato con successo!\n\n` + 
 +              `📁 File: ${fileName}\n` + 
 +              `📊 Preparazioni: ${window.monthlyPreparations.length}\n` + 
 +              `📋 Fogli: 4 (Riepilogo, Dettaglio, Statistiche, Componenti)`); 
 +         
 +    } catch (error) { 
 +        console.error('Errore generazione Excel:', error)
 +        alert('❌ Errore nella generazione Excel:\n' + error.message);
     }     }
 +}
 +
 +// Crea foglio riepilogo mensile
 +function createSummarySheet(preparations) {
 +    const selectedMonth = document.getElementById('selectedMonth').value;
 +    const monthName = new Date(selectedMonth + '-01').toLocaleDateString('it-IT',
 +        year: 'numeric', 
 +        month: 'long' 
 +    });
          
-    html +'<tr><td class="component-name-col">Intralipid 20%</td><td>' + Math.max(0, data.lipidVolume).toFixed(2) + '</td><td>' + (Math.max(0, data.lipidVolume) * ratio).toFixed(2+ '</td><td>ml</td></tr>';+    const stats calculateMonthlyStats(preparations);
          
-    // Totali +    const data 
-    html += '<tr class="composition-total"><td class="component-name-col"><strong>Totale</strong></td><td><strong>+ data.totalVolume.toFixed(2'</strong></td><td><strong>+ totalVolumeWithDeflector.toFixed(2+ '</strong></td><td><strong>ml</strong></td></tr>'; +        [`REPORT MENSILE NPT - ${monthName.toUpperCase()}`, '', '', ''], 
-    html += '<tr><td class="component-name-col"><strong>Deflussore</strong></td><td><strong>+ deflectorVolume + '</strong></td><td><strong>-</strong></td><td><strong>ml</strong></td></tr>'; +        [`Generato il: ${new Date().toLocaleDateString('it-IT')}`, '', '', ''], 
-    html += '<tr><td class="component-name-col"><strong>Velocità infusione</strong></td><td><strong>' + infusionRate + '</strong></td><td><strong>-</strong></td><td><strong>ml/h</strong></td></tr>'; +        [`Sistema: NPT Calculator v3.0 UNIFIED`, '', '', ''], 
-    html += '<tr><td class="component-name-col"><strong>Osmolarità Totale</strong></td><td><strong>+ estimatedOsmolarity + '</strong></td><td><strong>-</strong></td><td><strong>mOsm/ml</strong></td></tr>'+        ['', '', '', ''], 
-    html += '</table>'; +        ['STATISTICHE GENERALI', '', '', ''], 
-    html += '</div>';+        ['Totale preparazioni NPT:', preparations.length, '', ''], 
 +        ['Pazienti unici trattati:', stats.uniquePatients, '', ''], 
 +        ['Peso medio pazienti:', `${stats.averageWeight.toFixed(0)}g`, '', ''], 
 +        ['GIR medio:', `${stats.averageGIR.toFixed(1)} mg/kg/min`, '', ''], 
 +        ['Volume medio NPT:', `${stats.averageVolume.toFixed(0)ml`, '', ''], 
 +        ['', '', '', ''], 
 +        ['DISTRIBUZIONE PER PESO', '', '', ''], 
 +        ['ELBW (≤1000g):', preparations.filter(p =p.paziente.pesoAttuale <= 1000).length, '', ''], 
 +        ['VLBW (1001-1500g):', preparations.filter(p =p.paziente.pesoAttuale 1000 && p.paziente.pesoAttuale <= 1500).length, '', ''], 
 +        ['LBW (1501-2500g):', preparations.filter(p =p.paziente.pesoAttuale 1500 && p.paziente.pesoAttuale <= 2500).length, '', ''], 
 +        ['NBW (>2500g):', preparations.filter(p => p.paziente.pesoAttuale 2500).length, '', ''], 
 +        ['', '', '', ''], 
 +        ['DISTRIBUZIONE PER ETÀ', '', '', ''], 
 +        ['0-7 giorni:', preparations.filter(p =p.paziente.giorniVita <= 7).length, '', ''], 
 +        ['8-14 giorni:', preparations.filter(p =p.paziente.giorniVita 7 && p.paziente.giorniVita <= 14).length, '', ''], 
 +        ['15-30 giorni:', preparations.filter(p =p.paziente.giorniVita 14 && p.paziente.giorniVita <= 30).length, '', ''], 
 +        ['>30 giorni:', preparations.filter(p =p.paziente.giorniVita 30).length, ''''] 
 +    ];
          
-    html += '<div class="report-footer">'; +    return data;
-    html += 'NPT Calculator v2.0 - Foglio di Lavoro generato il ' + new Date().toLocaleString('it-IT'); +
-    html += '</div>'; +
-     +
-    html += '</div>'; +
-     +
-    return html;+
 } }
  
-function generateFinalReportHTML() { +// Crea foglio dettaglio preparazioni 
-    const data window.nptCalculationData; +function createDetailSheet(preparations) { 
-    const deflectorVolume = parseInt(document.getElementById('deflectorVolume').value|| 30; +    const header [ 
-    const totalVolumeWithDeflector = data.totalVolume + deflectorVolume; +        'ID Preparazione', 'Cartella Clinica', 'Data Prescrizione', 'Medico Prescrittore', 
-    const ratio = totalVolumeWithDeflector / data.totalVolume;+        'Peso (g)', 'Giorni Vita', 'Volume NPT (ml)''GIR (mg/kg/min)',  
 +        'Proteine (g/kg/die)', 'Lipidi (g/kg/die)', 'Energia (kcal/kg/die)', 
 +        'Osmolarità (mOsm/L)', 'Farmacista', 'Tecnico 1', 'Tecnico 2' 
 +    ];
          
-    const today new Date(); +    const data [header];
-    const dateStr = today.toLocaleDateString('it-IT');+
          
-    const medicalRecord patientData.medicalRecord || 'N/A'; +    preparations.forEach(prep => { 
-    const birthDate = patientData.prescriptionDate ?  +        const row 
-        new Date(new Date(patientData.prescriptionDate).getTime() - (patientData.daysOfLife * 24 * 60 * 60 * 1000)).toLocaleDateString('it-IT') :  +            prep.preparationID || '', 
-        'N/A'; +            prep.cartellaClinica || '', 
-    const doctorName = patientData.prescribingDoctor ?  +            prep.dataPrescrizione || '', 
-        doctorsData[patientData.prescribingDoctor]?.fullName || 'N/A'N/A';+            prep.personale?.medicoPrescrittore || '', 
 +            prep.paziente?.pesoAttuale || 0, 
 +            prep.paziente?.giorniVita || 0, 
 +            prep.npt?.volumeTotale || 0, 
 +            prep.npt?.gir || 0, 
 +            prep.npt?.proteine || 0, 
 +            prep.npt?.lipidi || 0, 
 +            prep.npt?.energia || 0, 
 +            prep.npt?.osmolarita || 0, 
 +            prep.personale?.farmacistValidatore || ''
 +            prep.personale?.tecnico1 || ''
 +            prep.personale?.tecnico2 || '' 
 +        ]; 
 +        data.push(row); 
 +    });
          
-    const infusionRate = (data.totalVolume 24).toFixed(2); +    return data
-    const finalConcentration data.neededGlucose > 0 ? (data.neededGlucose * 100) / data.totalVolume : 0; +
-    const estimatedOsmolarity = (finalConcentration * 55 + data.electrolyteAdditions.totalVolume * 10).toFixed(0);+ 
 +// Crea foglio statistiche cliniche 
 +function createStatsSheet(preparations{ 
 +    const header 
 +        'PARAMETRO', 'MEDIA', 'MIN', 'MAX', 'DEVIAZIONE STD', 'N° CAMPIONI' 
 +    ];
          
-    let html = '<div class="npt-report">';+    const data 
 +        ['STATISTICHE CLINICHE DETTAGLIATE', '', '', '', '', ''], 
 +        ['', '', '', '', '', ''], 
 +        header 
 +    ];
          
-    // INTESTAZIONE +    // Calcola statistiche per ogni parametro clinico 
-    html += '<div class="report-header">'; +    const parameters 
-    html += '<div class="report-header-left">'; +        { name: 'Peso (g)', values: preparations.map(p => p.paziente.pesoAttuale).filter(v => v > 0) }, 
-    html += '<div style="font-weightbold; font-size13px;">Dipartimento Area della Donna e Materno Infantile</div>'; +        { name: 'Giorni di vita', values: preparations.map(p => p.paziente.giorniVita).filter(v => v > 0) }, 
-    html += '<div style="font-size11px; color#666;">S.CNeonatologia e Terapia Intensiva Neonatale</div>'; +        { name: 'Volume NPT (ml)', values: preparations.map(p => p.npt.volumeTotale).filter(v => v > 0) }, 
-    html += '</div>'+        { name'GIR (mg/kg/min)', valuespreparations.map(p =parseFloat(p.npt.gir)).filter(v =!isNaN(v) && v > 0) }, 
-    html +'<div class="report-header-right">LOGO OSPEDALE</div>'; +        { name: 'Proteine (g/kg/die)', values: preparations.map(p => parseFloat(p.npt.proteine)).filter(v => !isNaN(v) && v > 0) }, 
-    html += '</div>';+        { name'Lipidi (g/kg/die)', valuespreparations.map(p =parseFloat(p.npt.lipidi)).filter(v =!isNaN(v) && v > 0) }, 
 +        { name: 'Energia (kcal/kg/die)', values: preparations.map(p => parseFloat(p.npt.energia)).filter(v => !isNaN(v) && v 0) }, 
 +        { name: 'Osmolarità (mOsm/L)', values: preparations.map(p => p.npt.osmolarita).filter(v => v > 0) } 
 +    ];
          
-    html +'<div class="report-title">CALCOLO NUTRIZIONALE PARENTERALE Data: ' dateStr + '</div>'+    parameters.forEach(param => { 
-    html +'<div class="report-subtitle">REPORT PARENTERALE</div>';+        if (param.values.length > 0) { 
 +            const avg = param.values.reduce((a, b) => b, 0) param.values.length
 +            const min Math.min(...param.values); 
 +            const max = Math.max(...param.values); 
 +            const variance = param.values.reduce((acc, val) => acc + Math.pow(val - avg, 2), 0) param.values.length; 
 +            const stdDev = Math.sqrt(variance); 
 +             
 +            data.push([ 
 +                param.name, 
 +                avg.toFixed(2), 
 +                min.toFixed(2), 
 +                max.toFixed(2), 
 +                stdDev.toFixed(2), 
 +                param.values.length 
 +            ]); 
 +        } 
 +    });
          
-    // INFO PAZIENTE +    // Aggiungi sezione parametri ematochimici se disponibili 
-    html += '<div class="report-section">'+    data.push([''''''''''''])
-    html += '<div class="report-section-title">INFO Paziente</div>'+    data.push(['PARAMETRI EMATOCHIMICI (quando disponibili)'''''''''''])
-    html += '<table class="report-table">'+    data.push(['''''''''''']);
-    html += '<tr><td class="label-col">Medico Prescrittore</td><td class="value-col">+ doctorName + '</td></tr>'+
-    html += '<tr><td class="label-col">Data Prescrizione</td><td class="value-col">' + dateStr + '</td></tr>'; +
-    html += '<tr><td class="label-col">Data Somministrazione</td><td class="value-col">+ dateStr + '</td></tr>'+
-    html += '<tr><td class="label-col">Paziente</td><td class="value-col">+ medicalRecord + '</td></tr>'+
-    html += '<tr><td class="label-col">Data di Nascita</td><td class="value-col">+ birthDate + '</td></tr>'; +
-    html += '<tr><td class="label-col">Giorni di Vita</td><td class="value-col">+ patientData.daysOfLife + '</td></tr>'+
-    html += '<tr><td class="label-col">Peso (g)</td><td class="value-col">+ data.currentWeight + '</td></tr>'+
-    html += '</table>'+
-    html += '</div>';+
          
-    // LISTA APPORTI ENTERALI +    const bloodParams [ 
-    html +'<div class="report-section">'; +        { name: 'BUN (mg/dL)', values: preparations.map(p =parseFloat(p.parametriClinici?.bun)).filter(v => !isNaN(v)) }, 
-    html += '<div class="report-section-title">Lista Degli Apporti per la Giornata Corrente</div>'+        { name: 'Glicemia (mg/dL)', values: preparations.map(p => parseFloat(p.parametriClinici?.glicemia)).filter(v => !isNaN(v)) }, 
-    if (enteralData && enteralData.volume 0) { +        { name: 'Natremia (mEq/L)', valuespreparations.map(p => parseFloat(p.parametriClinici?.natremia)).filter(v => !isNaN(v)) }, 
-        const formulaName = document.getElementById('formulaType').value; +        { name: 'pH', valuespreparations.map(p => parseFloat(p.parametriClinici?.ph)).filter(v => !isNaN(v)) 
-        const formulaDisplayName = formulaData[formulaName]?.name || 'Formula enterale'; +    ];
-        html +'<table class="report-table">'; +
-        html += '<tr><td class="label-col">Apporto</td><td style="text-align: center; width: 60px;"><strong>Quant.</strong></td><td style="text-align: left;"><strong>Somministrazione</strong></td></tr>'; +
-        html += '<tr><td class="label-col">+ formulaDisplayName + '</td><td style="text-aligncenter;">' + enteralData.volume + '</td><td style="text-align: left;">oro-naso-gastrica intermittente</td></tr>'; +
-        html +'</table>'; +
-    else { +
-        html += '<table class="report-table">'+
-        html += '<tr><td class="label-col">Apporto</td><td style="text-aligncenter; width: 60px;"><strong>Quant.</strong></td><td style="text-align: left;"><strong>Somministrazione</strong></td></tr>'; +
-        html +'<tr><td class="label-col">Nessun apporto enterale</td><td style="text-align: center;">-</td><td style="text-align: left;">-</td></tr>'; +
-        html += '</table>'; +
-    +
-    html += '</div>';+
          
-    // COMPOSIZIONE PARENTERALE +    bloodParams.forEach(param => { 
-    html +'<div class="report-section">'+        if (param.values.length > 0) { 
-    html +'<div class="report-section-title">Composizione Parenterale (numero sacche: 1)</div>'+            const avg param.values.reduce((a, b) => a + b, 0) / param.values.length
-    html +'<table class="composition-table">'+            const min Math.min(...param.values); 
-    html +'<tr><th class="component-name-col"></th><th>Teorici</th><th>Con Deflussore</th><th></th></tr>';+            const max Math.max(...param.values); 
 +            const variance param.values.reduce((acc, val) => acc + Math.pow(val - avg, 2), 0) / param.values.length
 +            const stdDev Math.sqrt(variance); 
 +             
 +            data.push([ 
 +                param.name
 +                avg.toFixed(2), 
 +                min.toFixed(2), 
 +                max.toFixed(2), 
 +                stdDev.toFixed(2), 
 +                param.values.length 
 +            ]); 
 +        } 
 +    });
          
-    // Componenti con ordine identico al foglio di lavoro +    return data; 
-    if (data.waterVolume > 0) { +
-        html += '<tr><td class="component-name-col">Acqua bidistillata</td><td>' + data.waterVolume.toFixed(2) + '</td><td>' + (data.waterVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'+ 
-    +// Crea foglio componenti NPT 
-    if (data.glucose50Volume > 0) { +function createComponentsSheet(preparations{ 
-        html += '<tr><td class="component-name-col">glucosata 50% (parenterale)</td><td>' + data.glucose50Volume.toFixed(2) + '</td><td>'(data.glucose50Volume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +    const header = [ 
-    +        'ID Preparazione', 'Cartella''Glucosio 50% (ml)''Trophamine (ml)' 
-    if (data.electrolyteAdditions.ca_gluconato > 0) { +        'Intralipid (ml)''Acqua Bid. (ml)', 'Ca Gluconato (ml)''Esafosfina (ml)', 
-        html += '<tr><td class="component-name-col">Calcio gluconato (1g/10mL,0,44mEq/mL)</td><td>+ data.electrolyteAdditions.ca_gluconato.toFixed(2) + '</td><td>(data.electrolyteAdditions.ca_gluconato * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +        'Mg Solfato (ml)''NaCl (ml)''Na Acetato (ml)''KCl (ml)', 
-    } +        'Vitalipid (ml)''Soluvit (ml)''Peditrace (ml)''Carnitene (ml)' 
-    if (data.electrolyteAdditions.nacl > 0+    ];
-        html += '<tr><td class="component-name-col">Sodio cloruro (3mEq/mL)</td><td>+ data.electrolyteAdditions.nacl.toFixed(2'</td><td>' + (data.electrolyteAdditions.nacl * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } +
-    if (data.electrolyteAdditions.kcl > 0) { +
-        html += '<tr><td class="component-name-col">Potassio cloruro (2mEq/mL)</td><td>+ data.electrolyteAdditions.kcl.toFixed(2) + '</td><td>' + (data.electrolyteAdditions.kcl * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } +
-    if (data.electrolyteAdditions.mg_sulfate > 0+
-        html += '<tr><td class="component-name-col">Magnesio solfato (2g/10mL,1.6mEq/mL)</td><td>+ data.electrolyteAdditions.mg_sulfate.toFixed(2'</td><td>(data.electrolyteAdditions.mg_sulfate * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } +
-    if (data.carnitineVolume > 0) { +
-        html += '<tr><td class="component-name-col">Carnitene f</td><td>' + data.carnitineVolume.toFixed(2'</td><td>(data.carnitineVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } +
-    if (data.proteinVolume > 0+
-        html += '<tr><td class="component-name-col">Trophamine 6%</td><td>+ data.proteinVolume.toFixed(2'</td><td>(data.proteinVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } +
-    if (data.electrolyteAdditions.esafosfina > 0) { +
-        html += '<tr><td class="component-name-col">Esafosfina f 5g</td><td>' + data.electrolyteAdditions.esafosfina.toFixed(2'</td><td>(data.electrolyteAdditions.esafosfina * ratio).toFixed(2) + '</td><td>ml</td></tr>'+
-    } +
-    if (data.residualNeeds.peditrace > 0) { +
-        const peditraceVolume = data.residualNeeds.peditrace * data.currentWeightKg; +
-        html += '<tr><td class="component-name-col">Peditrace</td><td>' + peditraceVolume.toFixed(2) + '</td><td>' + (peditraceVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } +
-    if (data.residualNeeds.soluvit > 0+
-        const soluvitVolume = data.residualNeeds.soluvit * data.currentWeightKg; +
-        html += '<tr><td class="component-name-col">Soluvit</td><td>+ soluvitVolume.toFixed(2) + '</td><td>' + (soluvitVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    } +
-    if (data.residualNeeds.vitalipid > 0+
-        const vitalipidVolume = data.residualNeeds.vitalipid * data.currentWeightKg; +
-        html += '<tr><td class="component-name-col">Vitalipid N</td><td>' + vitalipidVolume.toFixed(2) + '</td><td>' + (vitalipidVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>'; +
-    +
-    // Gestione valore negativo per Intralipid +
-    const displayLipidVolume = data.lipidVolume < 0 ? 0 : data.lipidVolume; +
-    html += '<tr><td class="component-name-col">Intralipid 20%</td><td>' + displayLipidVolume.toFixed(2) + '</td><td>' + (displayLipidVolume * ratio).toFixed(2) + '</td><td>ml</td></tr>';+
          
-    // Totali +    const data = [ 
-    html += '<tr class="composition-total"><td class="component-name-col"><strong>Totale</strong></td><td><strong>+ data.totalVolume.toFixed(2) + '</strong></td><td><strong>+ totalVolumeWithDeflector.toFixed(2) + '</strong></td><td><strong>ml</strong></td></tr>'+        ['DETTAGLIO COMPONENTI NPT''''''''''''''''''', '', '', '', '', '', ''], 
-    html += '<tr><td class="component-name-col"><strong>Deflussore</strong></td><td><strong>+ deflectorVolume + '</strong></td><td><strong>-</strong></td><td><strong>ml</strong></td></tr>'+        ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''], 
-    html += '<tr><td class="component-name-col"><strong>Velocità infusione</strong></td><td><strong>+ infusionRate + '</strong></td><td><strong>-</strong></td><td><strong>ml/h</strong></td></tr>'+        header 
-    html += '<tr><td class="component-name-col"><strong>Osmolarità Totale</strong></td><td><strong>+ estimatedOsmolarity + '</strong></td><td><strong>-</strong></td><td><strong>mOsm/ml</strong></td></tr>'+    ];
-    html += '</table>'; +
-    html += '</div>';+
          
-    // TOTALE ELEMENTI PRO KILO +    preparations.forEach(prep => 
-    html +'<div class="report-section">'+        const comp = prep.componenti || {}
-    html += '<div class="report-section-title">Totale Elementi Pro Kilo</div>'; +        const row 
-    html += '<table class="elements-table">';+            prep.preparationID || '', 
 +            prep.cartellaClinica || '', 
 +            comp.glucosio50 || '0.0', 
 +            comp.trophamine || '0.0', 
 +            comp.intralipid || '0.0', 
 +            comp.acquaBidistillata || '0.0', 
 +            comp.elettroliti?.ca_gluconato?.toFixed(1) || '0.0', 
 +            comp.elettroliti?.esafosfina?.toFixed(1) || '0.0', 
 +            comp.elettroliti?.mg_sulfate?.toFixed(1) || '0.0', 
 +            comp.elettroliti?.nacl?.toFixed(1) || '0.0', 
 +            comp.elettroliti?.sodium_acetate?.toFixed(1) || '0.0', 
 +            comp.elettroliti?.kcl?.toFixed(1) || '0.0', 
 +            '0.0', // Vitalipid calcolato dai residual needs 
 +            '0.0', // Soluvit calcolato dai residual needs   
 +            '0.0', // Peditrace - calcolato dai residual needs 
 +            '0.0'  // Carnitene - calcolato dai residual needs 
 +        ]; 
 +        data.push(row)
 +    });
          
-    // Calcoli degli elementi totali (enterale + parenterale) +    // Aggiungi statistiche componenti 
-    const totalLiquids = (enteralData ? enteralData.totalFluids : 0) + data.totalVolume+    data.push(['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''])
-    const totalLiquidsPerKg = (totalLiquids / data.currentWeightKg).toFixed(2);+    data.push(['STATISTICHE COMPONENTI', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''])
 +    data.push(['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']);
          
-    const totalProtein = (enteralData ? enteralData.protein * data.currentWeightKg 1000 : 0) + (data.residualNeeds.protein * data.currentWeightKg 1000); +    // Calcola medie componenti 
-    const totalLipids = (enteralData ? enteralData.lipids * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.lipids * data.currentWeightKg / 1000)+    const avgGlucose preparations.reduce((sum, p=> sum + (parseFloat(p.componenti?.glucosio50) || 0), 0) / preparations.length
-    const totalCarbs = (enteralData ? enteralData.carbs * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.carbs * data.currentWeightKg / 1000)+    const avgProtein preparations.reduce((sum, p=> sum + (parseFloat(p.componenti?.trophamine|| 0), 0) / preparations.length
-    const totalCalcium = (enteralData ? enteralData.calcium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.calcium * data.currentWeightKg / 1000)+    const avgLipid preparations.reduce((sum, p=> sum + (parseFloat(p.componenti?.intralipid|| 0), 0) / preparations.length
-    const totalPhosphorus = (enteralData ? enteralData.phosphorus * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.phosphorus * data.currentWeightKg / 1000)+    const avgWater preparations.reduce((sum, p=> sum + (parseFloat(p.componenti?.acquaBidistillata|| 0), 0) / preparations.length;
-    const totalSodium = (enteralData ? enteralData.sodium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.sodium * data.currentWeightKg / 1000)+
-    const totalPotassium = (enteralData ? enteralData.potassium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.potassium * data.currentWeightKg / 1000)+
-    const totalMagnesium = (enteralData ? enteralData.magnesium * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.magnesium * data.currentWeightKg 1000); +
-    const totalCarnitine = data.residualNeeds.carnitine * data.currentWeightKg / 1000;+
          
-    const totalEnergy = (enteralData ? enteralData.energy * data.currentWeightKg / 1000 : 0) + (data.residualNeeds.energy * data.currentWeightKg / 1000); +    data.push(['MEDIE COMPONENTI PRINCIPALI', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']); 
-    const totalNonProteinEnergy = totalEnergy - (totalProtein * 4); +    data.push(['Glucosio 50% medio:', avgGlucose.toFixed(1), 'ml', '', '', '', '', '', '', '', '', '', '', '', '', '']); 
-    const glucoseMgKgMin = ((totalCarbs * 1000/ 1440).toFixed(3);+    data.push(['Trophamine medio:', avgProtein.toFixed(1), 'ml', '', '', '', '', '', '', '', '', '', '', '', '', '']); 
 +    data.push(['Intralipid medio:', avgLipid.toFixed(1), 'ml', '', '', '', '', '', '', '', '', '', '', '', '', ''])
 +    data.push(['Acqua Bid. media:', avgWater.toFixed(1), 'ml', '', '', '', '', '', '', '', '', '', '', '', '', '']);
          
-    html +'<tr><td class="element-name">liquidi</td><td class="element-value">' + totalLiquidsPerKg + '</td><td class="element-unit">ml</td></tr>'; +    return data; 
-    html +'<tr><td class="element-name">Proteine</td><td class="element-value">' + (totalProtein * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">g</td></tr>'; +
-    html +'<tr><td class="element-name">Lipidi</td><td class="element-value">' + (totalLipids * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">g</td></tr>'; + 
-    html +'<tr><td class="element-name">Glucidi</td><td class="element-value">' + (totalCarbs * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">g</td></tr>'; +// ====================================================
-    html +'<tr><td class="element-name">Calcio</td><td class="element-value">' + (totalCalcium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mg</td></tr>'; +// SISTEMA KNOWLEDGE BASE 
-    html +'<tr><td class="element-name">Fosforo</td><td class="element-value">' + (totalPhosphorus * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mg</td></tr>'; +// ===================================================== 
-    html +'<tr><td class="element-name">Sodio</td><td class="element-value">' + (totalSodium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mEq</td></tr>'; + 
-    html +'<tr><td class="element-name">Potassio</td><td class="element-value">' + (totalPotassium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mEq</td></tr>'; +// Funzione per mostrare sezioni Knowledge Base 
-    html +'<tr><td class="element-name">Magnesio</td><td class="element-value">' + (totalMagnesium * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mEq</td></tr>'; +function showKnowledgeSection(sectionId
-    html +'<tr><td class="element-name">Carnitina</td><td class="element-value">' + (totalCarnitine * 1000 / data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">mg</td></tr>'; +    // Nascondi tutte le sezioni knowledge 
-    html +'<tr><td class="element-name">Oligoelementi</td><td class="element-value">' + (data.residualNeeds.peditrace * data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">ml</td></tr>'; +    document.querySelectorAll('.knowledge-section').forEach(section => { 
-    html +'<tr><td class="element-name">Vit. idrosolubili</td><td class="element-value">' + (data.residualNeeds.soluvit * data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">ml</td></tr>'; +        section.classList.remove('active')
-    html +'<tr><td class="element-name">Vit. liposolubili</td><td class="element-value">' + (data.residualNeeds.vitalipid * data.currentWeightKg).toFixed(2) + '</td><td class="element-unit">ml</td></tr>'; +        section.classList.add('hidden')
-    html +'<tr style="border-top: 2px solid #333;"><td class="element-name"><strong>KCal Totali</strong></td><td class="element-value"><strong>'(totalEnergy * 1000 / data.currentWeightKg).toFixed(2) + '</strong></td><td class="element-unit"><strong>-</strong></td></tr>'; +    });
-    html += '<tr><td class="element-name"><strong>KCal non proteiche</strong></td><td class="element-value"><strong>+ (totalNonProteinEnergy * 1000 / data.currentWeightKg).toFixed(2) + '</strong></td><td class="element-unit"><strong>-</strong></td></tr>'; +
-    html += '<tr><td class="element-name"><strong>Glucosio (mg/Kg al minuto)</strong></td><td class="element-value"><strong>+ glucoseMgKgMin + '</strong></td><td class="element-unit"><strong>-</strong></td></tr>'; +
-    html += '</table>'; +
-    html += '</div>';+
          
-    html += '<div class="report-footer">'; +    // Rimuovi classe active da tutti i tab knowledge 
-    html += 'NPT Calculator v2.0 - Report Parenterale generato il ' + new Date().toLocaleString('it-IT'); +    const knowledgeTabs document.querySelectorAll('#knowledge-base .tabs .tab')
-    html += '</div>';+    knowledgeTabs.forEach(tab => { 
 +        tab.classList.remove('active'); 
 +    });
          
-    html += '</div>';+    // Mostra la sezione selezionata 
 +    const targetSection document.getElementById(sectionId); 
 +    if (targetSection) { 
 +        targetSection.classList.remove('hidden'); 
 +        targetSection.classList.add('active'); 
 +    }
          
-    return html;+    // Attiva il tab cliccato 
 +    const clickedTab = event.target.closest('.tab'); 
 +    if (clickedTab) { 
 +        clickedTab.classList.add('active'); 
 +    } 
 +     
 +    console.log('Knowledge Base: mostrando sezione', sectionId);
 } }
  
-function printCurrentReport() { +// Database delle regole di calcolo (expandibile
-    const reportContent window.currentActiveReport === 'work' +const knowledgeBase 
-        document.getElementById('nptWorkReport').innerHTML +    calculationRules: { 
-        document.getElementById('nptFinalReport').innerHTML;+        gir: { 
 +            name: "GIR (Glucose Infusion Rate)", 
 +            formula"(Glucidi g/kg/die × 1000) ÷ 1440", 
 +            unit: "mg/kg/min", 
 +            normalRange: "4-12", 
 +            alerts: [ 
 +                { condition: "> 12", action: "Ridurre concentrazione glucosio", severity: "warning" }, 
 +                { condition: "> 15", action: "Sospendere temporaneamente NPT", severity: "critical"
 +            ], 
 +            rationale: "Il GIR elevato può causare iperglicemia e richiede monitoraggio glicemico frequente" 
 +        }, 
 +        osmolarity: { 
 +            name: "Osmolarità NPT", 
 +            formula: "Σ(Volume componente × Osmolarità componente) ÷ Volume totale", 
 +            unit: "mOsm/L", 
 +            thresholds: [ 
 +                { range: "< 600", access: "Periferico possibile", color: "green" }, 
 +                { range: "600-900", access: "CVC raccomandato", color: "orange" }, 
 +                { range: "> 900", access: "Solo CVC (ipertonica)", color: "red"
 +            ], 
 +            rationale: "L'osmolarità determina la via di accesso vascolare per evitare flebiti" 
 +        }, 
 +        proteinAdjustment:
 +            name: "Aggiustamento Proteine (BUN-driven)", 
 +            rules: [ 
 +                { bun: "< 9 mg/dL", action: "Aumenta proteine +1 g/kg/die", rationale: "BUN basso indica catabolismo insufficiente" }, 
 +                { bun: "9-14 mg/dL", action: "Mantieni proteine attuali", rationale: "Range ottimale per neonati" }, 
 +                { bun: "> 14 mg/dL", action: "Riduci proteine -1 g/kg/die", rationale: "BUN elevato indica sovraccarico azotato"
 +            ], 
 +            monitoring: "Controllo BUN ogni 48-72h durante NPT" 
 +        } 
 +    },
          
-    const reportTitle = window.currentActiveReport === 'work' +    clinicalGuidelines: { 
-        'Foglio di Lavoro NPT' 'Report Parenterale NPT';+        ageProtocols
 +            elbw: { name: "ELBW ≤1000g", protocols: [] }, 
 +            vlbw: { name: "VLBW 1001-1500g", protocols: [] }, 
 +            lbw: { name: "LBW 1501-2500g", protocols: [] }, 
 +            term: { name: "Term >2500g", protocols: [] } 
 +        } 
 +    },
          
-    const printWindow = window.open('''_blank');+    alerts: { 
 +        critical: [], 
 +        warning: [], 
 +        info: [] 
 +    } 
 +}; 
 + 
 +// Funzione per ottenere spiegazione di una regola 
 +function getCalculationExplanation(parametervalue
 +    const rules = knowledgeBase.calculationRules; 
 +    let explanation = "";
          
-    printWindow.document.write(` +    switch(parameter) { 
-        <!DOCTYPE html> +        case 'gir': 
-        <html+            if (value 12) { 
-        <head> +                explanation = "⚠️ GIR elevato: Rischio iperglicemia. Considera riduzione glucosio o aumento velocità."; 
-            <title>${reportTitle}</title> +            } else if (value 4) { 
-            <style> +                explanation = "⚠️ GIR bassoPossibile ipoglicemia. Verifica apporti glucidici."; 
-                body { margin0; padding: 15px; font-family: Arial, sans-serif; } +            else { 
-                ${document.querySelector('style').textContent+                explanation = "✅ GIR ottimale: Range di sicurezza per neonati."; 
-            </style> +            
-        </head+            break; 
-        <body+             
-            ${reportContent+        case 'osmolarity': 
-        </body> +            if (value 900) { 
-        </html> +                explanation = "🔴 Osmolarità ipertonica: OBBLIGATORIO accesso venoso centrale."; 
-    `);+            } else if (value 600) { 
 +                explanation = "🟠 Osmolarità elevata: Raccomandato accesso venoso centrale."; 
 +            } else { 
 +                explanation = "🟢 Osmolarità normale: Compatibile con accesso periferico."; 
 +            
 +            break; 
 +             
 +        default: 
 +            explanation = "Parametro monitorato dal sistema."; 
 +    }
          
-    printWindow.document.close(); +    return explanation;
-    printWindow.print();+
 } }
  
-function updateSystemConfig() { +// Funzione per mostrare tooltip informativi 
-    const updateBtn = document.getElementById('updateSystemBtn'); +function showKnowledgeTooltip(element, content) { 
-    updateBtn.className = 'button config-update-completed'; +    // Crea tooltip dinamico 
-    updateBtn.innerHTML = 'Parametri Sistema Aggiornati ✓';+    const tooltip = document.createElement('div'); 
 +    tooltip.className = 'knowledge-tooltip'; 
 +    tooltip.innerHTML = content; 
 +    tooltip.style.cssText = ` 
 +        position: absolute; 
 +        background-color: #2c3e50; 
 +        color: white; 
 +        padding: 10px; 
 +        border-radius: 5px; 
 +        font-size: 12px; 
 +        max-width: 300px; 
 +        z-index: 1000; 
 +        box-shadow: 0 2px 10px rgba(0,0,0,0.3); 
 +    `;
          
 +    document.body.appendChild(tooltip);
 +    
 +    // Posiziona tooltip
 +    const rect = element.getBoundingClientRect();
 +    tooltip.style.left = rect.left + 'px';
 +    tooltip.style.top = (rect.bottom + 5) + 'px';
 +    
 +    // Rimuovi dopo 3 secondi
     setTimeout(() => {     setTimeout(() => {
-        updateBtn.className = 'button'; +        if (tooltip.parentNode) { 
-        updateBtn.innerHTML = 'Aggiorna Parametri Sistema';+            tooltip.remove(); 
 +        }
     }, 3000);     }, 3000);
 } }
  
-// FUNZIONE SALVATAGGIO PDF +// Aggiorna la funzione showTab esistente per gestire il knowledge base 
-async function saveReportAsPDF() { +function showTabOriginal(tabId) { 
-    if (!window.currentActiveReport || !window.nptCalculationData) { +    // Funzione originale già esistente - non modificare 
-        alert('Prima genera un report!'); +    // Questa è solo per referenza 
-        return;+
 + 
 +// INIZIALIZZAZIONE 
 +document.addEventListener('DOMContentLoaded', function() { 
 +    console.log('NPT Calculator v3.0 UNIFIED inizializzato'); 
 +     
 +    // Imposta la data odierna come default 
 +    const today = new Date().toISOString().split('T')[0]; 
 +    document.getElementById('prescriptionDate').value = today; 
 +     
 +    // Configura il campo cartella clinica 
 +    setupMedicalRecordField(); 
 +     
 +    document.getElementById('birthWeight').addEventListener('change', function() { 
 +        document.getElementById('currentWeight').value = this.value; 
 +    }); 
 +     
 +    // Event listeners per resettare Fabbisogni e NPT quando si modificano i valori manualmente 
 +    const requirementFields = [ 
 +        'reqLiquids', 'reqProtein', 'reqCarbs', 'reqLipids',  
 +        'reqCalcium', 'reqPhosphorus', 'reqMagnesium',  
 +        'reqSodium', 'reqPotassium', 'reqVitalipid', 'reqSoluvit', 'reqPeditrace', 'reqCarnitine' 
 +    ]; 
 +     
 +    requirementFields.forEach(fieldId => { 
 +        const field = document.getElementById(fieldId); 
 +        if (field) { 
 +            field.addEventListener('input', function() { 
 +                resetNutritionButton(); 
 +            }); 
 +            field.addEventListener('change', function() { 
 +                resetNutritionButton(); 
 +            }); 
 +        
 +    }); 
 +     
 +    // Event listener per il tipo di sodio 
 +    const sodiumTypeSelect = document.getElementById('sodiumType'); 
 +    if (sodiumTypeSelect) { 
 +        sodiumTypeSelect.addEventListener('change', function() { 
 +            updateSodiumChoice(); 
 +            updateSodiumRecommendation(); 
 +        });
     }     }
          
-    try { +    // Event listener per il volume del deflussore 
-        // Mostra messaggio di caricamento +    const deflectorVolumeInput = document.getElementById('deflectorVolume'); 
-        const savePdfBtn = document.getElementById('savePdfBtn'); +    if (deflectorVolumeInput{ 
-        const originalText = savePdfBtn.innerHTML; +        deflectorVolumeInput.addEventListener('input', function() { 
-        savePdfBtn.innerHTML = '⏳ Generando PDF...'; +            resetParenteralButton();
-        savePdfBtn.disabled = true; +
-         +
-        // Seleziona il report attivo +
-        const reportElement window.currentActiveReport === 'work' ?  +
-            document.getElementById('nptWorkReport') :  +
-            document.getElementById('nptFinalReport'); +
-         +
-        const reportTitle = window.currentActiveReport === 'work' ?  +
-            'Foglio_di_Lavoro' : 'Report_Parenterale'; +
-         +
-        // Genera il nome file con data e cartella +
-        const today = new Date(); +
-        const dateStr = today.toISOString().split('T')[0].replace(/-/g, '')+
-        const medicalRecord = patientData.medicalRecord || 'SENZA_CARTELLA'; +
-        const fileName = `NPT_${reportTitle}_${medicalRecord}_${dateStr}.pdf`; +
-         +
-        // Configurazione html2canvas per qualità migliore +
-        const canvas = await html2canvas(reportElement,+
-            scale: 2, // Migliore qualità +
-            useCORS: true, +
-            backgroundColor: '#ffffff', +
-            width: reportElement.offsetWidth, +
-            height: reportElement.offsetHeight, +
-            scrollX: 0, +
-            scrollY: 0+
         });         });
-         +    } 
-        // Crea PDF con dimensioni A4 +     
-        const { jsPDF } window.jspdf+    // Inizializza configurazione clinica avanzata 
-        const pdf = new jsPDF(+    document.getElementById('calciumReq').value clinicalConfig.calciumReq
-            orientation: 'portrait', +    document.getElementById('phosphorusReq').value = clinicalConfig.phosphorusReq; 
-            unit: 'mm', +    document.getElementById('magnesiumReq').value = clinicalConfig.magnesiumReq; 
-            format: 'a4' +    document.getElementById('maxGIR').value = clinicalConfig.maxGIR
-        }); +    document.getElementById('maxLipids').value clinicalConfig.maxLipids
-         +    document.getElementById('maxProtein').value clinicalConfig.maxProtein
-        // Calcola dimensioni per adattare alla pagina A4 +    document.getElementById('hospitalName').value = clinicalConfig.hospitalName
-        const imgWidth 210// A4 width in mm +    document.getElementById('departmentName').value clinicalConfig.departmentName
-        const pageHeight 297// A4 height in mm +    document.getElementById('directorName').value clinicalConfig.directorName
-        const imgHeight = (canvas.height * imgWidth/ canvas.width+        
-         +    updateFortifierOptions(); 
-        let heightLeft imgHeight+   // Inizializza tutte le dropdown e tabelle 
-        let position 0+    updateDoctorsDropdown(); 
-         +    console.log('Dropdown medici inizializzata con', Object.keys(doctorsData).length, 'medici'); 
-        // Aggiungi l'immagine al PDF +    // Test per verificare che la dropdown sia stata popolata 
-        pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, position, imgWidth, imgHeight); +    setTimeout(() => 
-        heightLeft -= pageHeight; +        const prescribingDoctorSelect document.getElementById('prescribingDoctor'); 
-         +        if (prescribingDoctorSelect) { 
-        // Se il contenuto è più lungo di una pagina, aggiungi pagine +            console.log('Opzioni dropdown medici:', prescribingDoctorSelect.options.length);
-        while (heightLeft >= 0) { +
-            position heightLeft - imgHeight; +
-            pdf.addPage(); +
-            pdf.addImage(canvas.toDataURL('image/png')'PNG', 0, position, imgWidth, imgHeight)+
-            heightLeft -= pageHeight;+
         }         }
-         +    }, 500);
-        // Aggiungi metadati al PDF +
-        pdf.setProperties({ +
-            title: `NPT Calculator - ${reportTitle}`, +
-            subject: 'Calcolo Nutrizionale Parenterale', +
-            author: 'NPT Calculator v2.0', +
-            keywords: 'NPT, Nutrizione Parenterale, Neonatologia', +
-            creator: 'NPT Calculator v2.0' +
-        }); +
-         +
-        // Salva il PDF +
-        pdf.save(fileName); +
-         +
-        // Ripristina il pulsante +
-        savePdfBtn.innerHTML = '✅ PDF Salvato!'; +
-        savePdfBtn.style.backgroundColor = '#27ae60'; +
-         +
-        setTimeout(() => { +
-            savePdfBtn.innerHTML = originalText; +
-            savePdfBtn.style.backgroundColor = '#e74c3c'; +
-            savePdfBtn.disabled = false; +
-        }, 3000); +
-         +
-        // Mostra messaggio di conferma +
-        const confirmationMsg = document.createElement('div'); +
-        confirmationMsg.innerHTML = ` +
-            <div style="position: fixed; top: 20px; right: 20px; background: #27ae60; color: white;  +
-                        padding: 15px 20px; border-radius: 5px; z-index: 10000; box-shadow: 0 4px 12px rgba(0,0,0,0.3);"> +
-                <strong>✅ PDF Salvato!</strong><br> +
-                File: ${fileName}<br> +
-                <small>Il file è stato salvato nella cartella Download</small> +
-            </div> +
-        `; +
-        document.body.appendChild(confirmationMsg); +
-         +
-        setTimeout(() => { +
-            document.body.removeChild(confirmationMsg); +
-        }, 5000); +
-         +
-    } catch (error) { +
-        console.error('Errore durante il salvataggio PDF:', error); +
-        alert('Errore durante il salvataggio del PDF. Riprova o usa la funzione Stampa.'); +
-         +
-        // Ripristina il pulsante in caso di errore +
-        const savePdfBtn = document.getElementById('savePdfBtn'); +
-        savePdfBtn.innerHTML = '💾 Salva PDF'; +
-        savePdfBtn.disabled = false; +
-    } +
-}+
  
 +// Inizializza sezione mensile
 +    initializeMonthlySection();
 +    console.log('NPT Calculator v3.0 UNIFIED pronto');
 +});
 </script> </script>
 +
 </body> </body>
 </html> </html>
docuneo/programma_npt.1753992679.txt.gz · Ultima modifica: da neoadmin