/* =======================================================
AI PRO SUITE - system script
======================================================= */
let appHistory = [];
let visionReqs = parseInt(localStorage.getItem('visionReqs') || '0');
let textReqs = parseInt(localStorage.getItem('textReqs') || '0');
let isProcessing = false;
window.capturedImage = null; // MASTER IMAGE VARIABLE
window.currentMathImage = null; // SAFE MATH IMAGE VARIABLE
let currentMode = "";
let qaImages = [];
let transImages = [];
let qaContextText = "";
window.latestMathSolution = "";
let availableVoices = [];
window.hasResetToday = false;
let qaSourceImages = [];
let qaQuestionImage = null;
const MASTER_OCR_PROMPT = "Extract all text from this image exactly as it appears. Do not translate or summarize.";
// Video Player Variables
let videoTickInterval = null;
let videoTotalEst = 0;
let videoElapsed = 0;
let isVideoPaused = false;
let videoLineIndex = 0;
let activeVideoUtterance = null;
let currentVideoVolume = 1;
let videoSpeed = 1;
let videoRunToken = 0;
let hideControlsTimer = null;
// TTS System
let speechSynth = window.speechSynthesis;
let activeUtterance = null;
window.currentAbortController = null;
window.currentTypingTimer = null;
window.isImageGenerationMode = false;
window.requestCache = {};
let sessionCache = { math: null, search: null, translation: null, image_translation: null, qa: null };
// ๐ DATABASE LOADER ๐
if (typeof localforage !== 'undefined') {
localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });
localforage.getItem('aiHistory').then(function(savedData) {
let mergedHistory = savedData ? savedData : [];
let oldHistory = [];
try { let oldData = localStorage.getItem('aiHistory'); if (oldData) oldHistory = JSON.parse(oldData); } catch(e) {}
if (oldHistory.length > 0) {
let existingIds = new Set(mergedHistory.map(item => item.id));
oldHistory.forEach(item => { if (!existingIds.has(item.id)) mergedHistory.push(item); });
mergedHistory.sort((a, b) => b.id - a.id);
localforage.setItem('aiHistory', mergedHistory);
}
appHistory = mergedHistory;
if (document.getElementById('historyList')) renderHistory();
const urlParams = new URLSearchParams(window.location.search);
const restoreId = urlParams.get('restore');
if (restoreId) {
setTimeout(() => restoreSession(null, restoreId), 150);
window.history.replaceState({}, document.title, window.location.pathname);
}
}).catch(e => console.log("Vault error:", e));
} else {
try { appHistory = JSON.parse(localStorage.getItem('aiHistory') || '[]'); } catch(e) { appHistory = []; }
}
// ๐ TTS & SESSION CONTEXT ๐
window.loadVoices = function() {
if (speechSynth) {
availableVoices = speechSynth.getVoices();
if (speechSynth.onvoiceschanged !== undefined) {
speechSynth.onvoiceschanged = () => { availableVoices = speechSynth.getVoices(); };
}
}
};
window.speakAndHighlight = function(elementId) {
if (!speechSynth) return showToast("TTS not supported.");
let textEl = document.getElementById(elementId);
let text = textEl ? textEl.innerText : "";
if(!text) return;
speechSynth.cancel();
activeUtterance = new SpeechSynthesisUtterance(text);
let isHindi = /[เค
-เคน]/.test(text);
activeUtterance.lang = isHindi ? 'hi-IN' : 'en-US';
let preferredVoice = availableVoices.find(v => v.lang === activeUtterance.lang && (v.name.includes('Google') || v.name.includes('Premium')));
if (preferredVoice) activeUtterance.voice = preferredVoice;
activeUtterance.onstart = () => { const p = document.getElementById('ttsPlayer'); if(p) p.style.display = 'flex'; };
activeUtterance.onend = () => { const p = document.getElementById('ttsPlayer'); if(p) p.style.display = 'none'; };
speechSynth.speak(activeUtterance);
};
window.toggleTts = function() {
const btn = document.getElementById('ttsPlayPauseBtn');
if (speechSynth.paused) {
speechSynth.resume();
if(btn) btn.innerHTML = "โธ๏ธ";
} else {
speechSynth.pause();
if(btn) btn.innerHTML = "โถ๏ธ";
}
};
window.closeTts = function() {
if(speechSynth) speechSynth.cancel();
const p = document.getElementById('ttsPlayer');
if(p) p.style.display = 'none';
};
window.formatHindiSpeechText = function(text) { return text; };
window.getSessionContext = function(type) {
let context = "";
if(appHistory && appHistory.length > 0) {
let session = appHistory.find(i => i.type === type);
if(session && session.interactions) {
let lastFew = session.interactions.slice(-3);
lastFew.forEach(i => {
// CRITICAL FIX: Strip massive Base64 image tags out of the AI's memory
// so it doesn't crash the prompt limit on the next question!
let cleanAnswer = String(i.answer || "")
.replace(/]*src="data:image[^>]*>/gi, '[DIAGRAM REMOVED]')
.replace(/<[^>]*>?/gm, ' ')
.trim();
context += `User: ${i.question}\nAI: ${cleanAnswer}\n`;
});
}
}
return context ? `Previous Context:\n${context}\n` : "";
};
window.toggleImageModeBtn = function() {
window.isImageGenerationMode = !window.isImageGenerationMode;
const btn = document.getElementById("imgModeBtn");
if(!btn) return;
if(window.isImageGenerationMode) {
btn.innerHTML = "๐ผ๏ธ Image Mode ON";
btn.style.background = "var(--primary)";
btn.style.color = "white";
showToast("Image Generation Mode Enabled");
} else {
btn.innerHTML = "๐ผ๏ธ Image Mode";
btn.style.background = "var(--input-bg)";
btn.style.color = "var(--text-main)";
showToast("Image Generation Mode Disabled");
}
};
window.__imageModePages = [];
window.__imageModePageIndex = 0;
window.openImageModeViewer = function(imgSrcOrArray) {
const modal = document.getElementById('imageModeModal');
if(!modal) return;
window.__imageModePages = Array.isArray(imgSrcOrArray) ? imgSrcOrArray.filter(Boolean) : [imgSrcOrArray];
window.__imageModePageIndex = 0;
renderImageModePage();
modal.style.display = 'flex';
setTimeout(() => modal.style.opacity = '1', 10);
};
function renderImageModePage() {
const pages = window.__imageModePages; const idx = window.__imageModePageIndex;
const paper = document.getElementById('imageModePaper');
if (paper && pages[idx]) paper.innerHTML = `
`;
const indicator = document.getElementById('imageModePageIndicator');
if (indicator) indicator.innerText = `Page ${idx + 1} / ${pages.length}`;
const prevBtn = document.getElementById('imgPrevBtn');
const nextBtn = document.getElementById('imgNextBtn');
if (prevBtn) prevBtn.style.display = (pages.length > 1 && idx > 0) ? 'block' : 'none';
if (nextBtn) nextBtn.style.display = (pages.length > 1 && idx < pages.length - 1) ? 'block' : 'none';
}
window.prevImagePage = function (event) {
if (event) event.stopPropagation();
if (window.__imageModePageIndex > 0) { window.__imageModePageIndex--; renderImageModePage(); }
};
window.nextImagePage = function (event) {
if (event) event.stopPropagation();
if (window.__imageModePageIndex < window.__imageModePages.length - 1) { window.__imageModePageIndex++; renderImageModePage(); }
};
window.toggleImageControls = function () {
const controls = document.getElementById('imageModeControls');
const indicator = document.getElementById('imageModePageIndicator');
const hide = !controls || controls.style.opacity !== '0';
if (controls) controls.style.opacity = hide ? '0' : '1';
if (indicator) indicator.style.opacity = hide ? '0' : '1';
};
window.closeImageMode = function() {
const modal = document.getElementById('imageModeModal');
if(modal) {
modal.style.opacity = '0';
setTimeout(() => modal.style.display = 'none', 300);
}
};
window.downloadImageMode = function() {
const img = document.querySelector('#imageModePaper img');
if(img) {
const link = document.createElement('a');
link.download = 'AI_Math_Solution.png';
link.href = img.src;
link.click();
}
};
// ๐ INIT SCRIPT & TIMERS ๐
document.addEventListener("DOMContentLoaded", () => {
window.loadVoices();
// Auto-fix the missing Flash button onclick from HTML
const flashBtn = document.getElementById("toggleFlashBtn");
if (flashBtn) flashBtn.onclick = window.toggleFlash;
setInterval(() => {
const now = new Date();
const laTimeStr = now.toLocaleString("en-US", { timeZone: "America/Los_Angeles" });
const laTime = new Date(laTimeStr);
const currentPtDate = laTime.toLocaleDateString("en-US", { timeZone: "America/Los_Angeles" });
const lastResetDate = localStorage.getItem('lastApiResetDatePT');
const nextMidnight = new Date(laTime); nextMidnight.setHours(24, 0, 0, 0);
let diffMs = nextMidnight - laTime;
let h = Math.floor(diffMs / (1000 * 60 * 60)), m = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60)), s = Math.floor((diffMs % (1000 * 60)) / 1000);
const pad = (num) => num.toString().padStart(2, '0');
if (!lastResetDate) {
localStorage.setItem('lastApiResetDatePT', currentPtDate);
} else if (currentPtDate !== lastResetDate) {
visionReqs = 0; textReqs = 0;
localStorage.setItem('visionReqs', '0'); localStorage.setItem('textReqs', '0');
localStorage.setItem('lastApiResetDatePT', currentPtDate);
}
const t = document.getElementById('apiTimer'); if(t) t.innerText = `${pad(h)}h ${pad(m)}m ${pad(s)}s`;
const elTotal = document.getElementById('apiTotal'); if(elTotal) elTotal.innerText = visionReqs + textReqs;
const elVis = document.getElementById('apiVision'); if(elVis) elVis.innerText = visionReqs;
const elTxt = document.getElementById('apiText'); if(elTxt) elTxt.innerText = textReqs;
}, 1000);
const inputs = [{id:"searchInput", fn:runGroqSearch}, {id:"mathInstructionInput", fn:executeMathFlow}];
inputs.forEach(i => { const el = document.getElementById(i.id); if(el) el.addEventListener("keypress", (e) => { if(e.key === "Enter" && !e.shiftKey) { e.preventDefault(); i.fn(); } }); });
if (document.getElementById('historyList') && typeof localforage === 'undefined') renderHistory();
});
// ๐ UTILITIES & UI CONTROLS ๐
function showToast(msg) {
let t = document.createElement('div'); t.innerText = msg;
t.style.cssText = "position:fixed; bottom:20px; left:50%; transform:translateX(-50%); background:linear-gradient(135deg, #3b82f6, #8b5cf6); color:white; padding:12px 25px; border-radius:30px; box-shadow:0 10px 25px rgba(0,0,0,0.5); z-index:10000; font-weight:600; font-size: 14px; text-align:center; animation:fadeInOut 3s forwards;";
document.body.appendChild(t);
if(!document.getElementById('toastStyles')) {
let s = document.createElement('style'); s.id = 'toastStyles';
s.innerHTML = "@keyframes fadeInOut { 0%{opacity:0; bottom:10px;} 10%{opacity:1; bottom:30px;} 90%{opacity:1; bottom:30px;} 100%{opacity:0; bottom:10px;} }";
document.head.appendChild(s);
}
setTimeout(() => t.remove(), 3000);
}
function copyToClipboard(textId) { navigator.clipboard.writeText(document.getElementById(textId).innerText).then(() => showToast("โ
Copied to clipboard!")); }
function viewPhotoFullscreen(src) { const viewer = document.getElementById('photoViewer'); const img = document.getElementById('previewImage'); if(viewer && img) { img.src = src; viewer.classList.add('active'); } }
function getActiveChatContainer(defaultId) { let c = document.getElementById(defaultId); if (!c) c = document.getElementById("mathsChatHistory"); if (!c) c = document.getElementById("chatHistory"); if (!c) c = document.querySelector(".chat-scroll-area"); return c; }
function track(type) { if(type==='v'){ visionReqs++; localStorage.setItem('visionReqs', visionReqs); } else { textReqs++; localStorage.setItem('textReqs', textReqs); } }
function toggleSidebar() {
const sidebar = document.getElementById("sidebar"); const overlay = document.getElementById("overlay");
if (!sidebar || !overlay) return;
const active = !sidebar.classList.contains("active");
sidebar.classList.toggle("active", active); overlay.classList.toggle("active", active); document.body.classList.toggle("sidebar-open", active);
}
if(document.getElementById("overlay")) document.getElementById("overlay").onclick = toggleSidebar;
function scrollToBottom(aid, force = true) {
const scrollTargets = [];
[aid, "mathScrollArea", "searchChatHistory", "imageScrollArea"].forEach(id => { if (id) { const el = document.getElementById(id); if (el) scrollTargets.push(el); } });
const run = () => scrollTargets.forEach(a => { if (a) { a.scrollTop = a.scrollHeight; if (force && a.scrollTo) a.scrollTo({ top: a.scrollHeight, behavior: "auto" }); } });
requestAnimationFrame(run); setTimeout(run, 40); setTimeout(run, 160);
}
window.toggleFocusMode = function(enable) {
const topbar = document.getElementById('appTopbar'); const inputArea = document.querySelector('.chat-input-area'); const exitBtn = document.getElementById('exitFocusBtn'); const page = document.querySelector('.page');
if (enable) {
if(topbar) topbar.style.display = "none";
if(inputArea) { inputArea.style.opacity = "0"; inputArea.style.pointerEvents = "none"; inputArea.style.transform = "translateY(20px)"; }
exitBtn.style.display = "block"; setTimeout(() => exitBtn.style.opacity = "1", 10);
if (page) page.style.paddingTop = "15px";
if(typeof showToast === 'function') showToast("๐ฏ Focus Mode Activated!");
} else {
if(topbar) topbar.style.display = "flex";
if(inputArea) { inputArea.style.opacity = "1"; inputArea.style.pointerEvents = "auto"; inputArea.style.transform = "translateY(0)"; }
exitBtn.style.opacity = "0"; setTimeout(() => exitBtn.style.display = "none", 500);
if (page) page.style.paddingTop = "105px";
if(typeof showToast === 'function') showToast("UI Restored");
}
};
window.appendUserBubble = function(text, img, containerId) {
const historyDiv = document.getElementById(containerId); if (!historyDiv) return;
const msgDiv = document.createElement("div"); msgDiv.className = "chat-msg chat-user";
let escapedText = String(text || "").replace(/'/g, "\\'").replace(/"/g, '"').replace(/\n/g, '\\n');
let contentHtml = `