// Client Portal Login System const MASTER_CREDENTIALS = { username: 'HelloMC', password: 'MissionCritical25' }; let loginFormHandler; let logoutHandler; let calculatorButtonHandler; let whitepaperFormHandler; // Whitepaper download URLs - Update these with your actual hosting URLs const WHITEPAPER_URLS = { 'enterprise-ai-transformation-guide-2025': 'https://yourdomain.com/whitepapers/enterprise-ai-transformation-guide-2025.pdf', 'ai-readiness-assessment-framework': 'https://yourdomain.com/whitepapers/ai-readiness-assessment-framework.pdf', 'intelligent-process-automation-playbook': 'https://yourdomain.com/whitepapers/intelligent-process-automation-playbook.pdf', 'manufacturing-ai-revolution-2025': 'https://yourdomain.com/whitepapers/manufacturing-ai-revolution-2025.pdf', 'future-of-work-ai-human-collaboration': 'https://yourdomain.com/whitepapers/future-of-work-ai-human-collaboration.pdf', 'responsible-ai-ethics-compliance': 'https://yourdomain.com/whitepapers/responsible-ai-ethics-compliance.pdf', 'no-code-ai-revolution': 'https://yourdomain.com/whitepapers/no-code-ai-revolution.pdf' }; function handleLogin(event) { event.preventDefault(); const username = document.getElementById('username').value; const password = document.getElementById('password').value; const errorDiv = document.getElementById('login-error'); // Clear previous errors errorDiv.classList.add('hidden'); // Validate credentials if (username === MASTER_CREDENTIALS.username && password === MASTER_CREDENTIALS.password) { // Success - show dashboard localStorage.setItem('clientPortalLoggedIn', 'true'); localStorage.setItem('clientPortalUsername', username); showDashboard(); } else { // Error - show error message errorDiv.classList.remove('hidden'); // Add shake animation to form const form = document.getElementById('portal-login-form'); form.style.animation = 'shake 0.5s ease-in-out'; setTimeout(() => { form.style.animation = ''; }, 500); } } function handleLogout() { localStorage.removeItem('clientPortalLoggedIn'); localStorage.removeItem('clientPortalUsername'); showLogin(); } function showDashboard() { document.getElementById('login-container').classList.add('hidden'); document.getElementById('dashboard-container').classList.remove('hidden'); document.getElementById('client-resources').classList.remove('hidden'); // Update page title document.title = 'Client Portal Dashboard - Mission Critical'; // Smooth scroll to top window.scrollTo({ top: 0, behavior: 'smooth' }); } function showLogin() { document.getElementById('dashboard-container').classList.add('hidden'); document.getElementById('client-resources').classList.add('hidden'); document.getElementById('login-container').classList.remove('hidden'); // Clear form document.getElementById('username').value = ''; document.getElementById('password').value = ''; document.getElementById('login-error').classList.add('hidden'); // Update page title document.title = 'Client Portal Login - Mission Critical'; // Smooth scroll to top window.scrollTo({ top: 0, behavior: 'smooth' }); } function checkExistingLogin() { const isLoggedIn = localStorage.getItem('clientPortalLoggedIn') === 'true'; if (isLoggedIn) { showDashboard(); } else { showLogin(); } } // ROI Calculator Functions - Enhanced for live domain compatibility function openROICalculator() { console.log('Opening ROI Calculator...'); // Debug log const modal = document.getElementById('roiCalculatorModal'); console.log('Modal element:', modal); // Debug log if (!modal) { console.error('ROI Calculator modal not found!'); alert('Calculator is loading. Please wait a moment and try again.'); return; } modal.classList.remove('hidden'); modal.classList.add('flex'); document.body.style.overflow = 'hidden'; // Reset form to default values resetCalculatorForm(); // Hide results section const resultsSection = document.getElementById('roiResults'); if (resultsSection) { resultsSection.classList.add('hidden'); } console.log('Calculator modal opened successfully'); } function closeROICalculator() { const modal = document.getElementById('roiCalculatorModal'); if (modal) { modal.classList.add('hidden'); modal.classList.remove('flex'); document.body.style.overflow = ''; } } function resetCalculatorForm() { const inputs = { 'laborCosts': '125000', 'operationalCosts': '75000', 'weeklyHours': '40', 'hourlyRate': '25', 'setupCost': '25000', 'maintenanceCost': '2000', 'timeSavings': '0.5', 'costReduction': '0.25', 'revenueIncrease': '0.1' }; Object.keys(inputs).forEach(id => { const element = document.getElementById(id); if (element) { element.value = inputs[id]; } }); } function calculateROI() { console.log('Calculating ROI...'); // Debug log // Get all input values with fallbacks const getInputValue = (id, defaultValue = 0) => { const element = document.getElementById(id); return element ? parseFloat(element.value) || defaultValue : defaultValue; }; const laborCosts = getInputValue('laborCosts'); const operationalCosts = getInputValue('operationalCosts'); const weeklyHours = getInputValue('weeklyHours'); const hourlyRate = getInputValue('hourlyRate'); const setupCost = getInputValue('setupCost'); const maintenanceCost = getInputValue('maintenanceCost'); const timeSavings = getInputValue('timeSavings'); const costReduction = getInputValue('costReduction'); const revenueIncrease = getInputValue('revenueIncrease'); // Calculate current annual costs const totalCurrentCosts = laborCosts + operationalCosts; // Calculate time savings value (weekly hours saved * hourly rate * 52 weeks) const timeSavingsValue = weeklyHours * timeSavings * hourlyRate * 52; // Calculate operational cost savings const costSavingsValue = totalCurrentCosts * costReduction; // Calculate revenue increase value const revenueIncreaseValue = totalCurrentCosts * revenueIncrease; // Calculate total annual benefits const totalAnnualBenefits = timeSavingsValue + costSavingsValue + revenueIncreaseValue; // Calculate total first-year investment (setup + 12 months maintenance) const totalInvestment = setupCost + (maintenanceCost * 12); // Calculate net annual benefit const netBenefit = totalAnnualBenefits - (maintenanceCost * 12); // Calculate ROI (first year) const roiPercentage = totalInvestment > 0 ? ((totalAnnualBenefits - totalInvestment) / totalInvestment) * 100 : 0; // Calculate payback period in months const monthlyBenefit = totalAnnualBenefits / 12; const paybackPeriod = monthlyBenefit > 0 ? Math.ceil(totalInvestment / monthlyBenefit) : 0; // Calculate 3-year ROI const threeYearBenefits = (totalAnnualBenefits * 3) - totalInvestment - (maintenanceCost * 24); const threeYearROI = totalInvestment > 0 ? (threeYearBenefits / totalInvestment) * 100 : 0; // Update the results display updateResultsDisplay({ annualSavings: totalAnnualBenefits, roiPercentage: roiPercentage, paybackPeriod: paybackPeriod, threeYearROI: threeYearROI, totalCurrentCosts: totalCurrentCosts, timeSavingsValue: timeSavingsValue, costSavingsValue: costSavingsValue, revenueIncreaseValue: revenueIncreaseValue, totalInvestment: totalInvestment, netBenefit: netBenefit }); // Show results section with animation const resultsSection = document.getElementById('roiResults'); if (resultsSection) { resultsSection.classList.remove('hidden'); setTimeout(() => { resultsSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }, 100); } } function updateResultsDisplay(results) { // Format currency values const formatCurrency = (value) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(value); }; // Format percentage values const formatPercentage = (value) => { return Math.round(value) + '%'; }; // Update main metrics const elements = { 'annualSavings': formatCurrency(results.annualSavings), 'roiPercentage': formatPercentage(results.roiPercentage), 'paybackPeriod': results.paybackPeriod + ' months', 'threeYearROI': formatPercentage(results.threeYearROI), 'totalCurrentCosts': formatCurrency(results.totalCurrentCosts), 'timeSavingsValue': formatCurrency(results.timeSavingsValue), 'costSavingsValue': formatCurrency(results.costSavingsValue), 'revenueIncreaseValue': formatCurrency(results.revenueIncreaseValue), 'totalInvestment': formatCurrency(results.totalInvestment), 'netBenefit': formatCurrency(results.netBenefit) }; Object.keys(elements).forEach(id => { const element = document.getElementById(id); if (element) { element.textContent = elements[id]; } }); } function downloadResults() { // Get current results data const getElementText = (id) => { const element = document.getElementById(id); return element ? element.textContent : 'N/A'; }; const annualSavings = getElementText('annualSavings'); const roiPercentage = getElementText('roiPercentage'); const paybackPeriod = getElementText('paybackPeriod'); const netBenefit = getElementText('netBenefit'); // Create downloadable content const reportContent = `AI ROI CALCULATOR RESULTS ======================== Generated: ${new Date().toLocaleDateString()} KEY METRICS: - Annual Savings: ${annualSavings} - ROI (12 months): ${roiPercentage} - Payback Period: ${paybackPeriod} - Net Annual Benefit: ${netBenefit} This report was generated by Mission Critical's AI ROI Calculator. Contact us to discuss how we can help you achieve these results. Mission Critical Email: info@missioncritical.ai Website: https://missioncritical.ai Phone: Schedule a consultation to discuss your AI automation needs`; // Create and trigger download const blob = new Blob([reportContent], { type: 'text/plain' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'AI_ROI_Calculator_Results.txt'; document.body.appendChild(a); a.click(); document.body.removeChild(a); window.URL.revokeObjectURL(url); } // Close modal when clicking outside function handleModalClick(event) { const modal = document.getElementById('roiCalculatorModal'); if (event.target === modal) { closeROICalculator(); } } // Close modal with Escape key function handleEscapeKey(event) { if (event.key === 'Escape') { closeROICalculator(); closeWhitepaperModal(); closeSuccessModal(); closePDFTemplates(); } } // Calculator button click handler function handleCalculatorButtonClick(event) { event.preventDefault(); event.stopPropagation(); console.log('Calculator button clicked!'); openROICalculator(); } // Whitepaper Filtering Functions function filterWhitepapers(category) { const whitepaperCards = document.querySelectorAll('.whitepaper-card'); const filterButtons = document.querySelectorAll('[onclick*="filterWhitepapers"]'); // Update active button state filterButtons.forEach(button => { button.classList.remove('bg-blue-50', 'text-blue-600', 'border-blue-200'); button.classList.add('bg-white/80', 'text-gray-700', 'border-white/40'); }); // Set active state for clicked button const activeButton = Array.from(filterButtons).find(button => button.onclick && button.onclick.toString().includes(`'${category}'`) ); if (activeButton) { activeButton.classList.remove('bg-white/80', 'text-gray-700', 'border-white/40'); activeButton.classList.add('bg-blue-50', 'text-blue-600', 'border-blue-200'); } // Filter whitepaper cards with animation whitepaperCards.forEach((card, index) => { const cardCategory = card.getAttribute('data-category'); const shouldShow = category === 'all' || cardCategory === category; if (shouldShow) { card.style.display = 'block'; setTimeout(() => { card.style.opacity = '1'; card.style.transform = 'translateY(0)'; }, index * 50); } else { card.style.opacity = '0'; card.style.transform = 'translateY(20px)'; setTimeout(() => { card.style.display = 'none'; }, 300); } }); } // Whitepaper Download System with Lead Capture function initiateWhitepaperDownload(whitepaperSlug, whitepaperTitle) { console.log('Initiating download for:', whitepaperSlug, whitepaperTitle); // Set the modal title and form data const modalTitle = document.getElementById('modalWhitepaperTitle'); const whitepaperSlugInput = document.getElementById('whitepaperSlug'); if (modalTitle) modalTitle.textContent = whitepaperTitle; if (whitepaperSlugInput) whitepaperSlugInput.value = whitepaperSlug; // Show the modal const modal = document.getElementById('whitepaperDownloadModal'); if (modal) { modal.classList.remove('hidden'); document.body.style.overflow = 'hidden'; // Clear form clearLeadForm(); } } function clearLeadForm() { const form = document.getElementById('whitepaperLeadForm'); if (form) { form.reset(); // Keep the whitepaper slug value const whitepaperSlugInput = document.getElementById('whitepaperSlug'); const currentSlug = whitepaperSlugInput ? whitepaperSlugInput.value : ''; form.reset(); if (whitepaperSlugInput) whitepaperSlugInput.value = currentSlug; } } function closeWhitepaperModal() { const modal = document.getElementById('whitepaperDownloadModal'); if (modal) { modal.classList.add('hidden'); document.body.style.overflow = ''; } } function handleWhitepaperFormSubmit(event) { event.preventDefault(); const form = event.target; const formData = new FormData(form); const whitepaperSlug = formData.get('whitepaper_requested'); console.log('Form submitted for whitepaper:', whitepaperSlug); console.log('Lead data:', Object.fromEntries(formData)); // Close the lead capture modal closeWhitepaperModal(); // Start the download setTimeout(() => { downloadWhitepaper(whitepaperSlug); }, 500); // The form will also submit to your email via the landingsite contact form system return true; // Allow the form to submit normally } function downloadWhitepaper(whitepaperSlug) { const downloadUrl = WHITEPAPER_URLS[whitepaperSlug]; if (downloadUrl) { // Show success modal showDownloadSuccessModal(); // Start download const link = document.createElement('a'); link.href = downloadUrl; link.download = `${whitepaperSlug}.pdf`; document.body.appendChild(link); link.click(); document.body.removeChild(link); console.log('Download initiated for:', whitepaperSlug); } else { alert('Whitepaper not found. Please contact support.'); console.error('Download URL not found for:', whitepaperSlug); } } function showDownloadSuccessModal() { const modal = document.getElementById('downloadSuccessModal'); if (modal) { modal.classList.remove('hidden'); } } function closeSuccessModal() { const modal = document.getElementById('downloadSuccessModal'); if (modal) { modal.classList.add('hidden'); } } // File Management System Functions function toggleFileManagement() { const section = document.getElementById('fileManagementSection'); if (section) { if (section.classList.contains('hidden')) { section.classList.remove('hidden'); window.scrollTo({ top: section.offsetTop - 100, behavior: 'smooth' }); } else { section.classList.add('hidden'); } } } function handleFileUpload(event) { const files = event.target.files; if (files.length === 0) return; console.log('Files selected:', files.length); // Show upload progress const progressSection = document.getElementById('uploadProgress'); const progressBar = document.getElementById('progressBar'); const progressPercent = document.getElementById('progressPercent'); if (progressSection) { progressSection.classList.remove('hidden'); } // Simulate upload progress (replace with actual upload logic) let progress = 0; const interval = setInterval(() => { progress += Math.random() * 15; if (progress >= 100) { progress = 100; clearInterval(interval); setTimeout(() => { if (progressSection) progressSection.classList.add('hidden'); alert('Files uploaded successfully! Note: This is a demo interface. Implement actual file upload to your server.'); }, 500); } if (progressBar) progressBar.style.width = progress + '%'; if (progressPercent) progressPercent.textContent = Math.round(progress) + '%'; }, 200); } function previewFile(filename) { alert(`Preview functionality for ${filename} - Implement PDF preview here`); } function editFileDetails(slug) { alert(`Edit details for ${slug} - Implement file metadata editor here`); } function deleteFile(filename) { if (confirm(`Are you sure you want to delete ${filename}?`)) { alert(`Delete functionality for ${filename} - Implement file deletion here`); } } // PDF Template Functions function showPDFTemplates() { const section = document.getElementById('pdfTemplates'); if (section) { section.classList.remove('hidden'); window.scrollTo({ top: section.offsetTop - 100, behavior: 'smooth' }); } } function closePDFTemplates() { const section = document.getElementById('pdfTemplates'); if (section) { section.classList.add('hidden'); } } function generateAllTemplates() { // This would generate all PDF templates alert(` PDF Template Generation: This would generate all 7 whitepaper templates: 1. The Complete Enterprise AI Transformation Guide 2025 (75 pages) 2. AI Readiness Assessment Framework (42 pages) 3. Intelligent Process Automation Playbook (58 pages) 4. Manufacturing AI Revolution: 2025 State Report (65 pages) 5. The Future of Work: AI & Human Collaboration (52 pages) 6. Responsible AI: Ethics & Compliance Framework (48 pages) 7. No-Code AI Revolution: Democratizing Intelligence (55 pages) Total: 395 pages of professional content To implement: - Convert the HTML templates to PDF using libraries like Puppeteer or jsPDF - Set up automated PDF generation pipeline - Create download links for generated PDFs - Implement version control for template updates `); } // Global function registration window.filterWhitepapers = filterWhitepapers; window.initiateWhitepaperDownload = initiateWhitepaperDownload; window.closeWhitepaperModal = closeWhitepaperModal; window.closeSuccessModal = closeSuccessModal; window.toggleFileManagement = toggleFileManagement; window.handleFileUpload = handleFileUpload; window.previewFile = previewFile; window.editFileDetails = editFileDetails; window.deleteFile = deleteFile; window.showPDFTemplates = showPDFTemplates; window.closePDFTemplates = closePDFTemplates; window.generateAllTemplates = generateAllTemplates; // IMMEDIATE GLOBAL REGISTRATION - This runs as soon as the script loads (function() { console.log('Registering global calculator functions immediately...'); // Register functions on window object immediately window.openROICalculator = openROICalculator; window.closeROICalculator = closeROICalculator; window.calculateROI = calculateROI; window.downloadResults = downloadResults; console.log('Global functions registered:', { openROICalculator: typeof window.openROICalculator, closeROICalculator: typeof window.closeROICalculator, calculateROI: typeof window.calculateROI, downloadResults: typeof window.downloadResults }); })(); function attachCalculatorButton() { const calculatorButton = document.getElementById('launchROICalculator'); if (calculatorButton && !calculatorButton.dataset.listenerAttached) { calculatorButtonHandler = handleCalculatorButtonClick; calculatorButton.addEventListener('click', calculatorButtonHandler, true); // Use capture phase calculatorButton.dataset.listenerAttached = 'true'; console.log('Calculator button event listener attached successfully'); return true; } else if (!calculatorButton) { console.log('Calculator button not found, will retry...'); return false; } return true; } // Enhanced initialization with multiple retry attempts function initializeCalculator() { console.log('Initializing calculator...'); // Try to attach button immediately if (!attachCalculatorButton()) { // If not found, try multiple times with increasing delays const retryAttempts = [100, 300, 500, 1000, 2000]; retryAttempts.forEach((delay, index) => { setTimeout(() => { if (attachCalculatorButton()) { console.log(`Calculator button attached after ${delay}ms delay (attempt ${index + 1})`); } }, delay); }); } // Set up modal event listeners with retry function setupModalListeners() { const modal = document.getElementById('roiCalculatorModal'); if (modal) { modal.addEventListener('click', handleModalClick); document.addEventListener('keydown', handleEscapeKey); console.log('ROI Calculator modal event listeners attached'); return true; } return false; } if (!setupModalListeners()) { setTimeout(setupModalListeners, 500); } } function setupWhitepaperFiltering() { // Initialize whitepaper filtering const whitepaperCards = document.querySelectorAll('.whitepaper-card'); // Set up smooth transitions for cards whitepaperCards.forEach(card => { card.style.transition = 'opacity 0.3s ease, transform 0.3s ease'; card.style.opacity = '1'; card.style.transform = 'translateY(0)'; }); // Set default active state (All Categories) const allCategoriesButton = document.querySelector('[onclick*="filterWhitepapers(\\'all\\')"]'); if (allCategoriesButton) { allCategoriesButton.classList.remove('bg-white/80', 'text-gray-700', 'border-white/40'); allCategoriesButton.classList.add('bg-blue-50', 'text-blue-600', 'border-blue-200'); } console.log('Whitepaper filtering initialized'); } function setupWhitepaperDownloads() { // Attach form submit handler const whitepaperForm = document.getElementById('whitepaperLeadForm'); if (whitepaperForm) { whitepaperFormHandler = handleWhitepaperFormSubmit; whitepaperForm.addEventListener('submit', whitepaperFormHandler); console.log('Whitepaper form handler attached'); } // Set up drag and drop for file management const uploadArea = document.getElementById('uploadArea'); if (uploadArea) { uploadArea.addEventListener('dragover', (e) => { e.preventDefault(); uploadArea.classList.add('border-blue-400'); }); uploadArea.addEventListener('dragleave', (e) => { e.preventDefault(); uploadArea.classList.remove('border-blue-400'); }); uploadArea.addEventListener('drop', (e) => { e.preventDefault(); uploadArea.classList.remove('border-blue-400'); const files = e.dataTransfer.files; const fileInput = document.getElementById('fileInput'); if (fileInput) { fileInput.files = files; handleFileUpload({ target: { files } }); } }); console.log('File upload drag and drop initialized'); } } function init() { console.log('Initializing resources page...'); // Debug log // Ensure calculator functions are globally available again window.openROICalculator = openROICalculator; window.closeROICalculator = closeROICalculator; window.calculateROI = calculateROI; window.downloadResults = downloadResults; window.filterWhitepapers = filterWhitepapers; window.initiateWhitepaperDownload = initiateWhitepaperDownload; window.closeWhitepaperModal = closeWhitepaperModal; window.closeSuccessModal = closeSuccessModal; window.toggleFileManagement = toggleFileManagement; window.showPDFTemplates = showPDFTemplates; window.closePDFTemplates = closePDFTemplates; window.generateAllTemplates = generateAllTemplates; // Set up event handlers loginFormHandler = handleLogin; logoutHandler = handleLogout; // Attach event listeners const loginForm = document.getElementById('portal-login-form'); const logoutBtn = document.getElementById('logout-btn'); if (loginForm) { loginForm.addEventListener('submit', loginFormHandler); } if (logoutBtn) { logoutBtn.addEventListener('click', logoutHandler); } // Check if user is already logged in (only if portal elements exist) if (loginForm || document.getElementById('login-container')) { checkExistingLogin(); } // Initialize calculator with enhanced retry logic initializeCalculator(); // Initialize whitepaper filtering setupWhitepaperFiltering(); // Initialize whitepaper download system setupWhitepaperDownloads(); // Add CSS animations const style = document.createElement('style'); style.textContent = ` @keyframes shake { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-5px); } 75% { transform: translateX(5px); } } @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } .fade-in { animation: fadeIn 0.5s ease-out; } /* Modal animations */ .modal-enter { animation: modalFadeIn 0.3s ease-out; } @keyframes modalFadeIn { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } } /* Ensure button styling */ button { cursor: pointer !important; } button:disabled { opacity: 0.6; cursor: not-allowed !important; } /* Make sure calculator button is clickable */ #launchROICalculator { cursor: pointer !important; pointer-events: auto !important; position: relative !important; z-index: 10 !important; } #launchROICalculator:hover { transform: scale(1.05) !important; } /* Whitepaper card transitions */ .whitepaper-card { transition: opacity 0.3s ease, transform 0.3s ease; } .whitepaper-card:hover { transform: translateY(-8px) !important; } /* File management styling */ #uploadArea.border-blue-400 { border-color: #60A5FA !important; background-color: #EFF6FF !important; } `; document.head.appendChild(style); console.log('Resources page initialization complete'); // Final verification after a delay setTimeout(() => { console.log('Final verification:'); console.log('Global functions available:', { openROICalculator: typeof window.openROICalculator, closeROICalculator: typeof window.closeROICalculator, calculateROI: typeof window.calculateROI, downloadResults: typeof window.downloadResults, filterWhitepapers: typeof window.filterWhitepapers, initiateWhitepaperDownload: typeof window.initiateWhitepaperDownload, generateAllTemplates: typeof window.generateAllTemplates }); const button = document.getElementById('launchROICalculator'); console.log('Calculator button found:', !!button); if (button) { console.log('Button has listener:', !!button.dataset.listenerAttached); } const whitepaperCards = document.querySelectorAll('.whitepaper-card'); console.log('Whitepaper cards found:', whitepaperCards.length); const whitepaperForm = document.getElementById('whitepaperLeadForm'); console.log('Whitepaper form found:', !!whitepaperForm); }, 100); } function teardown() { // Remove event listeners const loginForm = document.getElementById('portal-login-form'); const logoutBtn = document.getElementById('logout-btn'); const modal = document.getElementById('roiCalculatorModal'); const calculatorButton = document.getElementById('launchROICalculator'); const whitepaperForm = document.getElementById('whitepaperLeadForm'); if (loginForm && loginFormHandler) { loginForm.removeEventListener('submit', loginFormHandler); } if (logoutBtn && logoutHandler) { logoutBtn.removeEventListener('click', logoutHandler); } if (modal) { modal.removeEventListener('click', handleModalClick); document.removeEventListener('keydown', handleEscapeKey); } if (calculatorButton && calculatorButtonHandler) { calculatorButton.removeEventListener('click', calculatorButtonHandler, true); delete calculatorButton.dataset.listenerAttached; } if (whitepaperForm && whitepaperFormHandler) { whitepaperForm.removeEventListener('submit', whitepaperFormHandler); } // Clear handlers loginFormHandler = null; logoutHandler = null; calculatorButtonHandler = null; whitepaperFormHandler = null; // Clear global calculator functions delete window.openROICalculator; delete window.closeROICalculator; delete window.calculateROI; delete window.downloadResults; delete window.filterWhitepapers; delete window.initiateWhitepaperDownload; delete window.closeWhitepaperModal; delete window.closeSuccessModal; delete window.toggleFileManagement; delete window.showPDFTemplates; delete window.closePDFTemplates; delete window.generateAllTemplates; // Restore body overflow document.body.style.overflow = ''; } // Export functions for the page system window.portalInit = init; window.portalTeardown = teardown; export { init, teardown };