Nota: dopo aver pubblicato, potrebbe essere necessario pulire la cache del proprio browser per vedere i cambiamenti.

  • Firefox / Safari: tieni premuto il tasto delle maiuscole Shift e fai clic su Ricarica, oppure premi Ctrl-F5 o Ctrl-R (⌘-R su Mac)
  • Google Chrome: premi Ctrl-Shift-R (⌘-Shift-R su un Mac)
  • Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5.
console.log("✅ Common.js è attivo");
/* ====================== Language in Home page Linkedin =================*/
document.addEventListener("DOMContentLoaded", function () {
  var trigger = document.querySelector(".language-trigger");
  var dropdown = document.querySelector(".language-dropdown");

  if (trigger && dropdown) {
    trigger.addEventListener("click", function () {
      dropdown.classList.toggle("open");
    });
  }
});



/* ======================= PULSANTE PURGE ======================= */
mw.loader.using('mediawiki.util').then(function () {
    setTimeout(function () {
        let menuAzioni = document.getElementById('p-cactions');
        if (menuAzioni && !document.getElementById('ca-purge')) {
            mw.util.addPortletLink(
                'p-cactions',
                mw.config.get('wgScript') + '?title=' + mw.config.get('wgPageName') + '&action=purge',
                '🔄 Purga',
                'ca-purge',
                'Pulisci la cache della pagina'
            );
            console.log("✅ Pulsante 'Purge' aggiunto con successo!");
        }
    }, 2000);
});

/* ======================= PULSANTE SCROLL TO TOP (Sempre visibile) ======================= */
mw.loader.using('mediawiki.util').then(function () {
    mw.hook('wikipage.content').add(function () {
        if (!document.getElementById("go-to-top")) {
            let goToTopBtn = document.createElement("button");
            goToTopBtn.id = "go-to-top";
            goToTopBtn.innerText = "⬆️ TOP";
            goToTopBtn.style.position = "fixed";
            goToTopBtn.style.bottom = "50px";
            goToTopBtn.style.right = "20px";
            goToTopBtn.style.background = "#3498db";
            goToTopBtn.style.color = "#fff";
            goToTopBtn.style.border = "none";
            goToTopBtn.style.padding = "10px";
            goToTopBtn.style.cursor = "pointer";
            goToTopBtn.style.borderRadius = "5px";
            goToTopBtn.style.zIndex = "1000";
            goToTopBtn.style.display = "none";

            document.body.appendChild(goToTopBtn);

            window.addEventListener("scroll", function () {
                goToTopBtn.style.display = window.scrollY > 200 ? "block" : "none";
            });

            goToTopBtn.addEventListener("click", function () {
                window.scrollTo({ top: 0, behavior: "smooth" });
            });

            console.log("✅ Pulsante Scroll-to-Top aggiunto!");
        }
    });
});
/* ======================= PULSANTE SCROLL BACK TO LAST POSITION ======================= */

// 1. Crea il bottone dinamicamente
var scrollBackBtn = document.createElement("button");
scrollBackBtn.id = "scroll-back-btn";
scrollBackBtn.innerHTML = "🔙 TORNA";
scrollBackBtn.style.display = "none";
scrollBackBtn.style.position = "fixed";
scrollBackBtn.style.bottom = "6em";
scrollBackBtn.style.right = "1em";
scrollBackBtn.style.padding = "10px 16px";
scrollBackBtn.style.border = "none";
scrollBackBtn.style.borderRadius = "10px";
scrollBackBtn.style.backgroundColor = "#007bff";
scrollBackBtn.style.color = "white";
scrollBackBtn.style.fontSize = "16px";
scrollBackBtn.style.cursor = "pointer";
scrollBackBtn.style.zIndex = "999";
document.body.appendChild(scrollBackBtn);

// 2. Ricorda l'ultima posizione prima di cliccare su una citazione
var lastScrollPosition = null;

// Quando clicchi su un link <sup> come [1], [2], ecc.
document.addEventListener('click', function(e) {
    if (e.target.closest('sup')) {
        lastScrollPosition = window.scrollY;
    }
});

// 3. Quando sei nella bibliografia, mostra il bottone "Torna"
window.addEventListener('scroll', function() {
    if (lastScrollPosition !== null && window.scrollY > 500) {
        document.getElementById('scroll-back-btn').style.display = 'block';
    } else {
        document.getElementById('scroll-back-btn').style.display = 'none';
    }
});

// 4. Cosa fa il bottone se cliccato
document.getElementById('scroll-back-btn').addEventListener('click', function() {
    if (lastScrollPosition !== null) {
        window.scrollTo({ top: lastScrollPosition, behavior: 'smooth' });
    }
});


/* ======================= AGGIUNGE I PULSANTI NEI TOOLS ======================= */
mw.loader.using('mediawiki.util').then(function () {
    function aggiungiAiTools(id, label, action) {
        let toolsMenu = document.getElementById("p-tb");
        if (!toolsMenu) {
            console.warn("⚠️ Menu 'Tools' non trovato!");
            return;
        }

        // Rimuove il pulsante dalla pagina, se esiste già
        let button = document.getElementById(id);
        if (button) {
            button.remove();
        }

        // Crea il link nei Tools
        if (!document.getElementById(id + "-tools")) {
            let newItem = document.createElement("li");
            let link = document.createElement("a");
            link.href = "#";
            link.id = id + "-tools";
            link.textContent = label;
            link.addEventListener("click", function (e) {
                e.preventDefault();

                $.ajax({
                    url: action,
                    dataType: "script",
                    cache: false,
                    success: function () {
                        console.log(`✅ Script ${action} caricato ed eseguito.`);

                        // Avvia la funzione giusta in base al pulsante cliccato
                        if (id === "traduci-contenuto") {
                            if (typeof traduciTesto === "function") {
                                traduciTesto();
                            } else {
                                console.error("❌ Errore: traduciTesto non è definita.");
                            }
                        } else if (id === "translate-update") {
                            if (typeof traduciTestoUpdate === "function") {
                                traduciTestoUpdate();
                            } else {
                                console.error("❌ Errore: traduciTestoUpdate non è definita.");
                            }
                        } else if (id === "reload-js") {
                            location.reload(); // Ricarica la pagina
                        }
                    },
                    error: function () {
                        console.error(`❌ Errore nel caricamento di ${action}`);
                    }
                });
            });

            newItem.appendChild(link);
            toolsMenu.querySelector("ul").appendChild(newItem);
            console.log(`✅ Pulsante "${label}" aggiunto nei Tools!`);
        }
    }

    // ✅ Aggiunge i pulsanti SEMPRE nei Tools
    setTimeout(function () {
        aggiungiAiTools("traduci-contenuto", "🌍 Traduci contenuto", "/index.php?title=MediaWiki:CommonTranslate.js&action=raw&ctype=text/javascript");
        aggiungiAiTools("translate-update", "🔄 Aggiorna Traduzione", "/index.php?title=MediaWiki:CommonTranslateUpdate.js&action=raw&ctype=text/javascript");
        aggiungiAiTools("reload-js", "♻️ Ricarica JS", "/index.php?title=MediaWiki:Common.js&action=raw&ctype=text/javascript");
    }, 2000);
});

/* ======================= NASCONDE I PULSANTI DALLA PAGINA ======================= */
document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll("#traduci-contenuto-button, #translate-update-button").forEach(btn => btn.style.display = "none");
});

/* ======================= IMPORTA CommonTranslate.js ======================= */
/* importScript('MediaWiki:CommonTranslateUpdate.js');*/
mw.loader.load('/index.php?title=MediaWiki:CommonTranslateUpdate.js&action=raw&ctype=text/javascript');


/* ======================= IMPORTA CommonDashboard.js ======================= */

if (mw.config.get('wgPageName') === 'Dashboard_Masticationpedia') {
  importScript('MediaWiki:CommonDashboard.js');
}

// Carica Merriweather da Google Fonts
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://fonts.googleapis.com/css2?family=Merriweather&display=swap';
document.head.appendChild(link);

/* ======================= IMPORTA CitationPopup.js======================= */
/* ============ ESPANSIONE DINAMICA INLINE ================= */ 

// Inietta stile CSS
/*mw.loader.using('mediawiki.util').then(function () {
  const style = document.createElement('style');
  style.textContent = `
    .expandible-block {
      margin: 12px 0;
      font-size: 95%;
    }
    .expand-trigger {
      cursor: pointer;
      color: #3366cc;
      font-weight: bold;
      display: inline-block;
    }
    .expand-content {
      display: none;
      margin-top: 8px;
      padding: 10px;
      background-color: #f8f8f8;
      border: 1px solid #ccc;
      border-radius: 8px;
    }
    .expandible-block.active .expand-content {
      display: block;
    }
  `;
  document.head.appendChild(style);

  // Aggiunge interazione
  document.querySelectorAll('.expandible-block .expand-trigger').forEach(trigger => {
    trigger.addEventListener('click', function () {
      const container = this.closest('.expandible-block');
      container.classList.toggle('active');
    });
  });
});
function toggleExpandable(trigger) {
  const content = trigger.nextElementSibling;
  if (content && content.classList.contains("expandable-content")) {
    content.style.display = (content.style.display === "none" || content.style.display === "") ? "block" : "none";
  }
}
*/
/* ========= TRANSCLUSIONE ==========*/
window.caricaTranscluso = function(boxID, trigger) {
  const containerID = 'contenuto-' + boxID;
  const container = document.getElementById(containerID);

  if (container.style.display === 'block') {
    container.style.display = 'none';
    return;
  }

  container.innerHTML = '⌛ Caricamento...';
  container.style.display = 'block';

  fetch('/mediawiki/index.php?title=Transcluso:' + boxID + '&action=render')
    .then(res => res.text())
    .then(html => {
      container.innerHTML = html;
    })
    .catch(err => {
      container.innerHTML = '<span style="color:red;">⚠ Errore nel caricamento.</span>';
      console.error(err);
    });
};
/* ===================== Differential Diagnostic protocol =========== */ 
// MediaWiki:Common.js
// Carica lo script CommonDDP.js SOLO quando si apre la pagina "Differential Diagnostic Protocol"

if (mw.config.get("wgPageName") === "Differential_Diagnostic_Protocol") {
    importScript("MediaWiki:CommonDDP.js");
}

(function () {
  // 1) Mappa titolo pagina → codice lingua (tutte le chiavi tra virgolette)
  var langMap = {
    'Main_Page':          'en',  // Home in inglese
    'Pagina_principale':  'it',  // Home in italiano
    'Page_d%27accueil':   'fr',  // Home in francese (apostrofo codificato %27)
    'Hauptseite':         'de',  // Home in tedesco
    'P%C3%A1gina_principal': 'es' // Home in spagnolo (accento percent-encoded)
  };

  var page = mw.config.get('wgPageName');
  if ( !langMap.hasOwnProperty(page) ) return; // non siamo in home

  // importa CSS e JS esterni
  mw.loader.load('https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.css');
  mw.loader.load('https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js');

  mw.loader.using('jquery', function () {
    window.addEventListener('load', function() {
      if (!window.cookieconsent) return;
      var lang = langMap[page];

      var texts = {
        it: { message: 'Utilizziamo cookie essenziali, analitici e di marketing per migliorare il sito.', dismiss:'Accetto tutti', deny:'Solo essenziali', link:'Cookie Policy' },
        en: { message: 'We use essential, analytics and marketing cookies to improve the site.', dismiss:'Accept all', deny:'Essential only', link:'Cookie Policy' },
        fr: { message: 'Nous utilisons des cookies essentiels, analytiques et marketing pour améliorer le site.', dismiss:'Tout accepter', deny:'Seulement essentiels', link:'Politique de cookies' },
        de: { message: 'Wir verwenden notwendige, analytische und Marketing-Cookies, um die Website zu verbessern.', dismiss:'Alle akzeptieren', deny:'Nur notwendige', link:'Cookie-Richtlinie' },
        es: { message: 'Utilizamos cookies esenciales, analíticas y de marketing para mejorar el sitio.', dismiss:'Aceptar todo', deny:'Solo esenciales', link:'Política de cookies' }
      };

      var c = texts[lang];

      window.cookieconsent.initialise({
        palette: {
          popup:  { background: '#343a40', text: '#ffffff' },
          button: { background: '#007BFF', text: '#ffffff' }
        },
        theme: 'classic',
        content: {
          message: c.message,
          dismiss: c.dismiss,
          deny:    c.deny,
          link:    c.link,
          href:    mw.util.getUrl('Cookie_Policy')
        },
        revocable: true,
        type: 'opt-in'
      });
    });
  });
})();
/* ============= Scroll =====*/
document.addEventListener("DOMContentLoaded", function () {
  var toggle = document.querySelector('.scroll-toggle');
  var dropdown = document.querySelector('.scroll-dropdown');
  if (toggle && dropdown) {
    toggle.addEventListener('click', function () {
      dropdown.classList.toggle('active');
    });
  }
});

// su tutti i link rimuovo il title…
$('a').not('.book-index-link').removeAttr('title');
// …ma lascio il title sul Book Index

function toggleHeroMenu() {
  var menu = document.getElementById("heroMenu");
  if (!menu) return;
  if (menu.style.display === "block") {
    menu.style.display = "none";
  } else {
    menu.style.display = "block";
  }
}

mw.hook('wikipage.content').add(function () {
  var burger = document.querySelector('.hamburger-icon');
  var menu = document.getElementById('heroMenu');

  if (burger && menu) {
    burger.addEventListener('click', function () {
      const isVisible = menu.style.display === 'block';
      menu.style.display = isVisible ? 'none' : 'block';
    });
  }
});

console.log("✅ Bottone menu cliccato");

document.addEventListener('DOMContentLoaded', function () {
  var lang = mw.config.get('wgUserLanguage') || 'en';
  var langMap = {
    'it': 'Registrazione_LinkedIn',
    'en': 'Subscribe_LinkedIn',
    'fr': 'Inscription_LinkedIn',
    'de': 'Registrieren_LinkedIn',
    'es': 'Suscripcion_LinkedIn'
  };

  var targetPage = langMap[lang] || 'Subscribe_LinkedIn';
  var expertBtn = document.querySelector('.cta-button-expert');
  if (expertBtn) {
    expertBtn.setAttribute('href', '/wiki/Masticationpedia:' + targetPage);
  }
});

// Aggiunge il footer personalizzato nella homepage
$(document).ready(function () {
  if (mw.config.get('wgPageName') === 'Main_Page') {
    var footerHtml = `
      <div id="custom-footer" style="margin-top: 40px; font-family: sans-serif; font-size: 14px; color: #555; text-align: center; line-height: 1.6;">
        <div>
          © 2025 <strong>Masticationpedia</strong> — A nonprofit project in masticatory science.<br>
          <em>Founded and curated by Dr. Gianni Frsardi, developed with the support of clinicians, researchers and open science advocates.</em>
        </div>
        <div style="margin-top: 10px;">
          <a href="/wiki/Privacy_policy" style="color:#0077b5; text-decoration:none;">Privacy Policy</a>
          &nbsp;&bull;&nbsp;
          <a href="/wiki/About_Masticationpedia" style="color:#0077b5; text-decoration:none;">About</a>
          &nbsp;&bull;&nbsp;
          <a href="/wiki/Disclaimer" style="color:#0077b5; text-decoration:none;">Disclaimer</a>
        </div>
      </div>
    `;

    // Inserisce nel footer standard oppure in fondo al body
    if ($('#footer').length) {
      $('#footer').append(footerHtml);
    } else if ($('.mw-footer').length) {
      $('.mw-footer').append(footerHtml);
    } else {
      $('body').append(footerHtml);
    }
  }
});