jQuery(document).ready(function($) { // ==================================== // MULTI-INSTANCE MANAGEMENT SYSTEM // ==================================== // Instance registry - tracks all chatbot instances on the page const MxChatInstances = { instances: {}, // Initialize an instance for a bot init: function(botId) { if (!this.instances[botId]) { // When persistence is OFF, track when this session started // so the AI only sees messages from this page load var chatPersistenceEnabled = typeof mxchatChat !== 'undefined' && mxchatChat.chat_persistence_toggle === 'on'; this.instances[botId] = { botId: botId, sessionId: this.getChatSession(botId), lastSeenMessageId: '', notificationCheckInterval: null, pollingInterval: null, processedMessageIds: new Set(), activePdfFile: null, activeWordFile: null, chatHistoryLoaded: false, isStreaming: false, // Fresh context timestamp - only used when persistence is OFF sessionStartTimestamp: chatPersistenceEnabled ? 0 : Date.now() }; } return this.instances[botId]; }, // Get instance by botId get: function(botId) { return this.instances[botId] || this.init(botId); }, // Get all active bot IDs getAllBotIds: function() { return Object.keys(this.instances); }, // Session management per bot getChatSession: function(botId) { var cookieName = 'mxchat_session_id_' + botId; var sessionId = getCookie(cookieName); if (!sessionId) { sessionId = generateSessionId(); this.setChatSession(botId, sessionId); } return sessionId; }, setChatSession: function(botId, sessionId) { var cookieName = 'mxchat_session_id_' + botId; document.cookie = cookieName + "=" + sessionId + "; path=/; max-age=86400; SameSite=Lax"; if (this.instances[botId]) { this.instances[botId].sessionId = sessionId; } }, resetChatSession: function(botId) { var newSessionId = generateSessionId(); this.setChatSession(botId, newSessionId); var $chatBox = getElement(botId, 'chat-box'); if ($chatBox.length) { $chatBox.find('.user-message, .bot-message:not(:first), .agent-message').remove(); } if (this.instances[botId]) { this.instances[botId].chatHistoryLoaded = false; this.instances[botId].processedMessageIds = new Set(); } } }; // ==================================== // ELEMENT SELECTOR HELPERS // ==================================== // Check if a specific bot has an AI theme assigned (skip inline colors) function shouldSkipInlineColors(botId) { // If global AI theme is active, skip inline colors for all bots if (mxchatChat.skip_inline_colors) { return true; } // Check if this specific bot has a theme assignment var botAssignments = mxchatChat.bot_theme_assignments || {}; return botAssignments.hasOwnProperty(botId); } // Get element by ID with bot suffix - returns jQuery object function getElement(botId, elementName) { return $('#' + elementName + '-' + botId); } // Get element by ID with bot suffix - returns DOM element function getElementDOM(botId, elementName) { return document.getElementById(elementName + '-' + botId); } // Get bot ID from any element within a chatbot instance function getBotIdFromElement(element) { var $wrapper = $(element).closest('.mxchat-chatbot-wrapper'); if ($wrapper.length) { return $wrapper.data('bot-id') || 'default'; } // Fallback: try to find from floating container var $floating = $(element).closest('.floating-chatbot'); if ($floating.length) { var id = $floating.attr('id') || ''; var match = id.match(/floating-chatbot-(.+)/); if (match) return match[1]; } // Fallback: check if element itself has an ID with bot suffix (e.g., floating-chatbot-button-{bot_id}) var elementId = $(element).attr('id') || ''; if (elementId) { // Match patterns like: floating-chatbot-button-{bot_id}, pre-chat-message-{bot_id} var idMatch = elementId.match(/^(?:floating-chatbot-button|pre-chat-message|chat-notification-badge)-(.+)$/); if (idMatch) return idMatch[1]; } return 'default'; } // Get wrapper element for a bot function getWrapper(botId) { return getElement(botId, 'mxchat-chatbot-wrapper'); } // ==================================== // GLOBAL VARIABLES & CONFIGURATION // ==================================== const toolbarIconColor = mxchatChat.toolbar_icon_color || '#212121'; // Initialize color settings (these are global as they come from PHP) var userMessageBgColor = mxchatChat.user_message_bg_color; var userMessageFontColor = mxchatChat.user_message_font_color; var botMessageBgColor = mxchatChat.bot_message_bg_color; var botMessageFontColor = mxchatChat.bot_message_font_color; var liveAgentMessageBgColor = mxchatChat.live_agent_message_bg_color; var liveAgentMessageFontColor = mxchatChat.live_agent_message_font_color; var linkTarget = mxchatChat.link_target_toggle === 'on' ? '_blank' : '_self'; // ==================================== // SESSION MANAGEMENT (Legacy compatibility) // ==================================== function getCookie(name) { let value = "; " + document.cookie; let parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } function generateSessionId() { return 'mxchat_chat_' + Math.random().toString(36).substr(2, 9); } // Legacy function - now delegates to instance manager function getChatSession(botId) { botId = botId || 'default'; return MxChatInstances.getChatSession(botId); } function setChatSession(sessionId, botId) { botId = botId || 'default'; MxChatInstances.setChatSession(botId, sessionId); } function resetChatSession(botId) { botId = botId || 'default'; MxChatInstances.resetChatSession(botId); } // ==================================== // INITIALIZE ALL CHATBOT INSTANCES // ==================================== function initializeAllInstances() { // Find all chatbot wrappers on the page $('.mxchat-chatbot-wrapper').each(function() { var botId = $(this).data('bot-id') || 'default'; MxChatInstances.init(botId); initializeBotInstance(botId); }); } function initializeBotInstance(botId) { var instance = MxChatInstances.get(botId); // Initialize quick questions state for this bot checkQuickQuestionsState(botId); // Note: Event handlers use event delegation with class selectors, // so they work automatically for all instances without per-bot setup } // ==================================== // CONTEXTUAL AWARENESS FUNCTIONALITY // ==================================== function getPageContext() { // Check if contextual awareness is enabled if (mxchatChat.contextual_awareness_toggle !== 'on') { return null; } // Get page URL const pageUrl = window.location.href; // Get page title const pageTitle = document.title || ''; // Get main content from the page let pageContent = ''; // Try to get content from common content areas const contentSelectors = [ 'main', '[role="main"]', '.content', '.main-content', '.post-content', '.entry-content', '.page-content', 'article', '#content', '#main' ]; let contentElement = null; for (const selector of contentSelectors) { contentElement = document.querySelector(selector); if (contentElement) { break; } } // If no specific content area found, use body but exclude header, footer, nav, sidebar if (!contentElement) { contentElement = document.body; } if (contentElement) { // Clone the element to avoid modifying the original const clone = contentElement.cloneNode(true); // Remove unwanted elements const unwantedSelectors = [ 'header', 'footer', 'nav', '.navigation', '.sidebar', '.widget', '.menu', 'script', 'style', '.comments', '#comments', '.breadcrumb', '.breadcrumbs', '#floating-chatbot', '#floating-chatbot-button', '.mxchat', '[class*="chat"]', '[id*="chat"]' ]; unwantedSelectors.forEach(selector => { const elements = clone.querySelectorAll(selector); elements.forEach(el => el.remove()); }); // Extract MxChat context data attributes before getting text content const contextData = []; clone.querySelectorAll('[data-mxchat-context]').forEach(el => { const contextValue = el.dataset.mxchatContext; if (contextValue && contextValue.trim()) { contextData.push(contextValue); } }); // Get text content and clean it up pageContent = clone.textContent || clone.innerText || ''; // Add context data to page content if any were found if (contextData.length > 0) { pageContent += '\n\nAdditional Context:\n' + contextData.join('\n'); } // Clean up whitespace and limit length pageContent = pageContent .replace(/\s+/g, ' ') .trim() .substring(0, 3000); // Limit to 3000 characters to avoid token limits } // Only return context if we have meaningful content if (!pageContent || pageContent.length < 50) { return null; } return { url: pageUrl, title: pageTitle, content: pageContent }; } // Track originating page when chat starts function trackOriginatingPage() { const sessionId = getChatSession(); const pageUrl = window.location.href; const pageTitle = document.title || 'Untitled Page'; // Only track once per session const trackingKey = 'mxchat_originating_tracked_' + sessionId; if (sessionStorage.getItem(trackingKey)) { return; } $.ajax({ url: mxchatChat.ajax_url, type: 'POST', data: { action: 'mxchat_track_originating_page', session_id: sessionId, page_url: pageUrl, page_title: pageTitle, nonce: mxchatChat.nonce }, success: function(response) { if (response.success) { sessionStorage.setItem(trackingKey, 'true'); } } }); } // ==================================== // CORE CHAT FUNCTIONALITY // ==================================== // Helper functions to disable/enable chat input while waiting for response function disableChatInput(botId) { botId = botId || 'default'; var chatInput = getElementDOM(botId, 'chat-input'); var sendButton = getElementDOM(botId, 'send-button'); if (chatInput) { chatInput.disabled = true; chatInput.style.opacity = '0.6'; } if (sendButton) { sendButton.disabled = true; sendButton.style.opacity = '0.5'; sendButton.style.pointerEvents = 'none'; } } function enableChatInput(botId) { botId = botId || 'default'; var chatInput = getElementDOM(botId, 'chat-input'); var sendButton = getElementDOM(botId, 'send-button'); if (chatInput) { chatInput.disabled = false; chatInput.style.opacity = '1'; chatInput.focus(); } if (sendButton) { sendButton.disabled = false; sendButton.style.opacity = '1'; sendButton.style.pointerEvents = 'auto'; } } // Update your existing sendMessage function function sendMessage(botId) { botId = botId || 'default'; var $chatInput = getElement(botId, 'chat-input'); var message = $chatInput.val(); // ADD PROMPT HOOK HERE if (typeof customMxChatFilter === 'function') { message = customMxChatFilter(message, "prompt"); } if (message) { // Disable input while waiting for response disableChatInput(botId); appendMessage("user", message, '', [], false, botId); $chatInput.val(''); $chatInput.css('height', 'auto'); if (hasQuickQuestions(botId)) { collapseQuickQuestions(botId); } appendThinkingMessage(botId); scrollToBottom(botId); const currentModel = mxchatChat.model || 'gpt-5.1-chat-latest'; // Check if streaming is enabled AND supported for this model if (shouldUseStreaming(currentModel)) { callMxChatStream(message, function(response) { getElement(botId, 'chat-box').find('.bot-message.temporary-message').removeClass('temporary-message'); }, botId); } else { callMxChat(message, function(response) { replaceLastMessage("bot", response, '', [], botId); }, botId); } } } // Update your existing sendMessageToChatbot function function sendMessageToChatbot(message, botId) { botId = botId || 'default'; // ADD PROMPT HOOK HERE if (typeof customMxChatFilter === 'function') { message = customMxChatFilter(message, "prompt"); } // Disable input while waiting for response disableChatInput(botId); var sessionId = getChatSession(botId); if (hasQuickQuestions(botId)) { collapseQuickQuestions(botId); } appendThinkingMessage(botId); scrollToBottom(botId); const currentModel = mxchatChat.model || 'gpt-5.1-chat-latest'; // Check if streaming is enabled AND supported for this model if (shouldUseStreaming(currentModel)) { callMxChatStream(message, function(response) { getElement(botId, 'chat-box').find('.bot-message.temporary-message').removeClass('temporary-message'); }, botId); } else { callMxChat(message, function(response) { getElement(botId, 'chat-box').find('.temporary-message').remove(); replaceLastMessage("bot", response, '', [], botId); }, botId); } } // Updated shouldUseStreaming function with debugging function shouldUseStreaming(model) { // Check if streaming is enabled in settings (using your toggle naming pattern) const streamingEnabled = mxchatChat.enable_streaming_toggle === 'on'; // Check if model supports streaming const streamingSupported = isStreamingSupported(model); // Only use streaming if both enabled and supported return streamingEnabled && streamingSupported; } // Helper function to handle chat mode updates function handleChatModeUpdates(response, responseText) { // Check for explicit chat mode in response (THIS IS THE KEY FIX) if (response.chat_mode) { updateChatModeIndicator(response.chat_mode); return; // Return early since we found explicit mode } // Check for fallback response chat mode else if (response.fallbackResponse && response.fallbackResponse.chat_mode) { updateChatModeIndicator(response.fallbackResponse.chat_mode); return; // Return early since we found explicit mode } // Only do text-based detection if no explicit mode was provided // Check for specific AI chatbot response text if (responseText === 'You are now chatting with the AI chatbot.' || responseText.includes('now chatting with the AI') || responseText.includes('switched to AI mode') || responseText.includes('AI chatbot is now')) { updateChatModeIndicator('ai'); } // Check for agent transfer messages else if (responseText.includes('agent') && (responseText.includes('transfer') || responseText.includes('connected'))) { updateChatModeIndicator('agent'); } } // Function to get bot ID from any element or wrapper // If element is provided, finds the bot ID from its wrapper // If no element, returns 'default' (for backward compatibility) function getMxChatBotId(element) { if (element) { return getBotIdFromElement(element); } // Fallback: find first chatbot wrapper on page const chatbotWrapper = document.querySelector('.mxchat-chatbot-wrapper'); return chatbotWrapper ? chatbotWrapper.getAttribute('data-bot-id') || 'default' : 'default'; } function callMxChat(message, callback, botId) { botId = botId || getMxChatBotId(); // Store the message in case we need to retry after session reset getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message', message); // Get page context if contextual awareness is enabled const pageContext = getPageContext(); // Get instance for session start timestamp (used when persistence is OFF) var instance = MxChatInstances.get(botId); // Prepare AJAX data const ajaxData = { action: 'mxchat_handle_chat_request', message: message, session_id: getChatSession(botId), nonce: mxchatChat.nonce, current_page_url: window.location.href, current_page_title: document.title, bot_id: botId, // Pass session start timestamp so AI context matches what user sees session_start_timestamp: instance.sessionStartTimestamp || 0 }; // Add page context if available if (pageContext) { ajaxData.page_context = JSON.stringify(pageContext); } // CHECK FOR VISION FLAGS AND ADD THEM if (window.mxchatVisionProcessed) { ajaxData.vision_processed = true; ajaxData.original_user_message = window.mxchatOriginalMessage || message; ajaxData.vision_images_count = window.mxchatVisionImagesCount || 0; // Clear the flags after use window.mxchatVisionProcessed = false; window.mxchatOriginalMessage = null; window.mxchatVisionImagesCount = 0; } $.ajax({ url: mxchatChat.ajax_url, type: 'POST', dataType: 'json', data: ajaxData, success: function(response) { // IMMEDIATE CHAT MODE UPDATE - This should be FIRST if (response.chat_mode) { updateChatModeIndicator(response.chat_mode, botId); } // Also check in data property if response is wrapped if (response.data && response.data.chat_mode) { updateChatModeIndicator(response.data.chat_mode, botId); } // SECURITY FIX: Check for errors FIRST before checking for success // This ensures API errors (quota exceeded, invalid key, rate limit) are properly displayed if (response.success === false || (response.data && response.data.error_message)) { let errorMessage = ""; let errorCode = ""; // Check various possible error locations in the response if (response.data && response.data.error_message) { errorMessage = response.data.error_message; errorCode = response.data.error_code || ""; } else if (response.error_message) { errorMessage = response.error_message; errorCode = response.error_code || ""; } else if (response.message) { errorMessage = response.message; } else if (typeof response.data === 'string') { errorMessage = response.data; } else { // Fallback for any other unexpected response format errorMessage = "An error occurred. Please try again or contact support."; } // Handle session reset action (IP changed, session expired, etc.) if (response.data && response.data.action === 'reset_session') { // Clear the old session and generate a new one resetChatSession(botId); // Remove the temporary loading message getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove(); // Re-send the original message with the new session var originalMessage = getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message'); if (originalMessage) { getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message', null); // Re-add the user message and thinking indicator appendMessage("user", originalMessage, '', [], false, botId); appendThinkingMessage(botId); scrollToBottom(botId); // Determine whether to use streaming const currentModel = mxchatChat.model || 'gpt-5.1-chat-latest'; if (shouldUseStreaming(currentModel)) { callMxChatStream(originalMessage, function(response) { getElement(botId, 'chat-box').find('.bot-message.temporary-message').removeClass('temporary-message'); }, botId); } else { callMxChat(originalMessage, function(response) { replaceLastMessage("bot", response, '', [], botId); }, botId); } } return; } // Format user-friendly error message let displayMessage = errorMessage; // Customize message for admin users if (mxchatChat.is_admin) { // For admin users, show more technical details including error code displayMessage = errorMessage + (errorCode ? " (Error code: " + errorCode + ")" : ""); } replaceLastMessage("bot", displayMessage, '', [], botId); return; // Exit early for errors } // NOW check if this is a successful response by looking for text, html, or message fields // This preserves compatibility with your server response format if (response.text !== undefined || response.html !== undefined || response.message !== undefined || (response.success === true && response.data && response.data.status === 'waiting_for_agent')) { // Handle successful response - this is your original success handling code // Handle other responses let responseText = response.text || ''; let responseHtml = response.html || ''; let responseMessage = response.message || ''; // Add PDF filename handling if (response.data && response.data.filename) { showActivePdf(response.data.filename, botId); var instance = MxChatInstances.get(botId); instance.activePdfFile = response.data.filename; } // Add redirect check here if (response.redirect_url) { if (responseText) { replaceLastMessage("bot", responseText, '', [], botId); } setTimeout(() => { window.location.href = response.redirect_url; }, 1500); return; } // Check for live agent response if (response.success && response.data && response.data.status === 'waiting_for_agent') { updateChatModeIndicator('agent', botId); return; } // Handle the message and show notification if chat is hidden if (responseText || responseHtml || responseMessage) { // ADD RESPONSE HOOKS HERE - BEFORE DISPLAYING if (responseText && typeof customMxChatFilter === 'function') { responseText = customMxChatFilter(responseText, "response"); } if (responseMessage && typeof customMxChatFilter === 'function') { responseMessage = customMxChatFilter(responseMessage, "response"); } // Update the messages as before if (responseText && responseHtml) { replaceLastMessage("bot", responseText, responseHtml, [], botId); } else if (responseText) { replaceLastMessage("bot", responseText, '', [], botId); } else if (responseHtml) { replaceLastMessage("bot", "", responseHtml, [], botId); } else if (responseMessage) { replaceLastMessage("bot", responseMessage, '', [], botId); } // Check if chat is hidden and show notification var $floatingChatbot = getElement(botId, 'floating-chatbot'); if ($floatingChatbot.hasClass('hidden')) { var $badge = getElement(botId, 'chat-notification-badge'); if ($badge.length) { $badge.show(); } } } else { replaceLastMessage("bot", "I received an empty response. Please try again or contact support if this persists.", '', [], botId); } if (response.message_id) { var instance = MxChatInstances.get(botId); instance.lastSeenMessageId = response.message_id; } return; } // Fallback for truly unexpected response formats replaceLastMessage("bot", "Unexpected response format. Please try again or contact support.", '', [], botId); }, error: function(xhr, status, error) { let errorMessage = "An unexpected error occurred."; // Try to parse the response if it's JSON try { const responseJson = JSON.parse(xhr.responseText); if (responseJson.data && responseJson.data.error_message) { errorMessage = responseJson.data.error_message; } else if (responseJson.message) { errorMessage = responseJson.message; } } catch (e) { // Not JSON or parsing failed, use HTTP status based messages if (xhr.status === 0) { errorMessage = "Network error: Please check your internet connection."; } else if (xhr.status === 403) { errorMessage = "Access denied: Your session may have expired. Please refresh the page."; } else if (xhr.status === 404) { errorMessage = "API endpoint not found. Please contact support."; } else if (xhr.status === 429) { errorMessage = "Too many requests. Please try again in a moment."; } else if (xhr.status >= 500) { errorMessage = "Server error: The server encountered an issue. Please try again later."; } } replaceLastMessage("bot", errorMessage, '', [], botId); } }); } function callMxChatStream(message, callback, botId) { botId = botId || getMxChatBotId(); // Store the message in case we need to retry after session reset getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message', message); const currentModel = mxchatChat.model || 'gpt-5.1-chat-latest'; if (!isStreamingSupported(currentModel)) { callMxChat(message, callback, botId); return; } // Get page context if contextual awareness is enabled const pageContext = getPageContext(); // Get instance for session start timestamp (used when persistence is OFF) var instance = MxChatInstances.get(botId); const formData = new FormData(); formData.append('action', 'mxchat_stream_chat'); formData.append('message', message); formData.append('session_id', getChatSession(botId)); formData.append('nonce', mxchatChat.nonce); formData.append('current_page_url', window.location.href); formData.append('current_page_title', document.title); formData.append('bot_id', botId); // Pass session start timestamp so AI context matches what user sees formData.append('session_start_timestamp', instance.sessionStartTimestamp || 0); // Add page context if available if (pageContext) { formData.append('page_context', JSON.stringify(pageContext)); } // CHECK FOR VISION FLAGS AND ADD THEM if (window.mxchatVisionProcessed) { formData.append('vision_processed', 'true'); formData.append('original_user_message', window.mxchatOriginalMessage || message); formData.append('vision_images_count', window.mxchatVisionImagesCount || '0'); // Clear the flags after use window.mxchatVisionProcessed = false; window.mxchatOriginalMessage = null; window.mxchatVisionImagesCount = 0; } let accumulatedContent = ''; let testingDataReceived = false; let streamingStarted = false; fetch(mxchatChat.ajax_url, { method: 'POST', body: formData, credentials: 'same-origin' }) .then(response => { // Store the response for potential fallback handling const responseClone = response.clone(); if (!response.ok) { // Try to get error details from response return responseClone.json().then(errorData => { throw { isServerError: true, data: errorData }; }).catch(() => { throw new Error('Network response was not ok'); }); } // Check if response is JSON instead of streaming const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { return responseClone.json().then(data => { // IMMEDIATE CHAT MODE UPDATE for JSON response if (data.chat_mode) { updateChatModeIndicator(data.chat_mode, botId); } // Check for testing panel if (window.mxchatTestPanelInstance && data.testing_data) { window.mxchatTestPanelInstance.handleTestingData(data.testing_data); } // Handle the JSON response directly handleNonStreamResponse(data, callback, botId); return Promise.resolve(); // Prevent further processing }); } // Continue with streaming processing const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; function processStream() { reader.read().then(({ done, value }) => { if (done) { // If streaming completed but no content was received, try to get response as fallback if (!streamingStarted || !accumulatedContent) { // Try to read the response as JSON responseClone.text().then(text => { try { const data = JSON.parse(text); if (data.text || data.message || data.html) { handleNonStreamResponse(data, callback, botId); } else { // No valid data, fall back to regular call getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove(); callMxChat(message, callback, botId); } } catch (e) { // Could not parse, fall back to regular call getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove(); callMxChat(message, callback, botId); } }).catch(() => { getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove(); callMxChat(message, callback, botId); }); return; } // Re-enable chat input when stream ends with content enableChatInput(botId); if (callback) { callback(accumulatedContent); } return; } buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.startsWith('data: ')) { const data = line.substring(6); if (data === '[DONE]') { if (!accumulatedContent) { getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove(); callMxChat(message, callback, botId); return; } // Re-enable chat input after streaming completes enableChatInput(botId); if (callback) { callback(accumulatedContent); } return; } try { const json = JSON.parse(data); // IMMEDIATE CHAT MODE UPDATE FOR STREAMING if (json.chat_mode) { updateChatModeIndicator(json.chat_mode, botId); } // Handle testing data if (json.testing_data && !testingDataReceived) { if (window.mxchatTestPanelInstance) { window.mxchatTestPanelInstance.handleTestingData(json.testing_data); testingDataReceived = true; } } // Handle content streaming else if (json.content) { streamingStarted = true; accumulatedContent += json.content; updateStreamingMessage(accumulatedContent, botId); } // Handle complete response in stream (fallback response) else if (json.text || json.message || json.html) { handleNonStreamResponse(json, callback, botId); return; } // Handle errors else if (json.error) { // Get error message from various possible fields let errorMessage = json.error_message || json.message || json.text || (typeof json.error === 'string' ? json.error : 'An error occurred. Please try again.'); // Re-enable chat input on error enableChatInput(botId); // Display the error directly in the chat replaceLastMessage("bot", errorMessage, '', [], botId); if (callback) { callback(errorMessage); } return; } } catch (e) { // SSE data parsing error - silently continue } } } processStream(); }).catch(streamError => { getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove(); callMxChat(message, callback, botId); }); } processStream(); }) .catch(error => { // Check if we have server error data with chat mode if (error && error.isServerError && error.data) { // Check for chat mode in error data if (error.data.chat_mode) { updateChatModeIndicator(error.data.chat_mode, botId); } handleNonStreamResponse(error.data, callback, botId); } else { // Only fall back to regular call if we don't have any response data getElement(botId, 'chat-box').find('.bot-message.temporary-message').remove(); callMxChat(message, callback, botId); } }); } // Helper function to handle non-streaming responses function handleNonStreamResponse(data, callback, botId) { botId = botId || 'default'; // IMMEDIATE CHAT MODE UPDATE FOR NON-STREAMING RESPONSES if (data.chat_mode) { updateChatModeIndicator(data.chat_mode, botId); } // Also check in data property if response is wrapped if (data.data && data.data.chat_mode) { updateChatModeIndicator(data.data.chat_mode, botId); } // NOTE: Don't remove temporary message here - let replaceLastMessage handle it // This prevents a visual gap between thinking dots disappearing and content appearing // SECURITY FIX: Check for errors FIRST if (data.success === false || (data.data && data.data.error_message)) { let errorMessage = ""; let errorCode = ""; // Check various possible error locations if (data.data && data.data.error_message) { errorMessage = data.data.error_message; errorCode = data.data.error_code || ""; } else if (data.error_message) { errorMessage = data.error_message; errorCode = data.error_code || ""; } else if (data.message) { errorMessage = data.message; } else if (typeof data.data === 'string') { errorMessage = data.data; } else { errorMessage = "An error occurred. Please try again or contact support."; } // Handle session reset action (IP changed, session expired, etc.) if (data.data && data.data.action === 'reset_session') { // Clear the old session and generate a new one resetChatSession(botId); // Re-send the original message with the new session var originalMessage = getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message'); if (originalMessage) { getElement(botId, 'mxchat-chatbot-wrapper').find('.mxchat-input-holder textarea').data('pending-message', null); // Re-add the user message and thinking indicator appendMessage("user", originalMessage, '', [], false, botId); appendThinkingMessage(botId); scrollToBottom(botId); // Determine whether to use streaming const currentModel = mxchatChat.model || 'gpt-5.1-chat-latest'; if (shouldUseStreaming(currentModel)) { callMxChatStream(originalMessage, callback, botId); } else { callMxChat(originalMessage, callback, botId); } } return; } // Format user-friendly error message let displayMessage = errorMessage; if (mxchatChat.is_admin) { displayMessage = errorMessage + (errorCode ? " (Error code: " + errorCode + ")" : ""); } replaceLastMessage("bot", displayMessage, '', [], botId); if (callback) { callback(''); } return; // Exit early for errors } // Handle different response formats if (data.text || data.html || data.message) { // Apply response hooks if (data.text && typeof customMxChatFilter === 'function') { data.text = customMxChatFilter(data.text, "response"); } if (data.message && typeof customMxChatFilter === 'function') { data.message = customMxChatFilter(data.message, "response"); } // Display the response if (data.text && data.html) { replaceLastMessage("bot", data.text, data.html, [], botId); } else if (data.text) { replaceLastMessage("bot", data.text, '', [], botId); } else if (data.html) { replaceLastMessage("bot", "", data.html, [], botId); } else if (data.message) { replaceLastMessage("bot", data.message, '', [], botId); } } // Handle other response properties if (data.data && data.data.filename) { showActivePdf(data.data.filename, botId); var instance = MxChatInstances.get(botId); instance.activePdfFile = data.data.filename; } if (data.redirect_url) { setTimeout(() => { window.location.href = data.redirect_url; }, 1500); } // Ensure chat input is re-enabled (safety net for edge cases) enableChatInput(botId); if (callback) { callback(data.text || data.message || ''); } } // Enhanced updateChatModeIndicator function for immediate DOM updates function updateChatModeIndicator(mode, botId) { console.log('[MxChat] updateChatModeIndicator called with mode:', mode, 'botId:', botId); botId = botId || 'default'; const indicator = getElementDOM(botId, 'chat-mode-indicator'); console.log('[MxChat] chat-mode-indicator element found:', !!indicator); if (indicator) { const oldText = indicator.textContent; console.log('[MxChat] Current indicator text:', oldText, '-> changing to mode:', mode); if (mode === 'agent') { indicator.textContent = 'Live Agent'; console.log('[MxChat] Mode is agent, calling startPolling...'); startPolling(botId); } else { // Everything else is AI mode const customAiText = indicator.getAttribute('data-ai-text') || 'AI Agent'; indicator.textContent = customAiText; stopPolling(botId); } // Force immediate DOM update and reflow if (oldText !== indicator.textContent) { // Force a reflow to ensure the change is visible immediately indicator.style.display = 'none'; indicator.offsetHeight; // Trigger reflow indicator.style.display = ''; // Double-check after a brief moment to ensure the change stuck setTimeout(() => { if (mode === 'agent' && indicator.textContent !== 'Live Agent') { indicator.textContent = 'Live Agent'; } else if (mode !== 'agent' && indicator.textContent === 'Live Agent') { const customAiText = indicator.getAttribute('data-ai-text') || 'AI Agent'; indicator.textContent = customAiText; } }, 50); } } } // Function to update message during streaming function updateStreamingMessage(content, botId) { botId = botId || 'default'; // ADD RESPONSE HOOK FOR REAL-TIME STREAMING if (typeof customMxChatFilter === 'function') { content = customMxChatFilter(content, "response"); } const formattedContent = linkify(content); // Find the temporary message in this bot's chat box var $chatBox = getElement(botId, 'chat-box'); const tempMessage = $chatBox.find('.bot-message.temporary-message').last(); if (tempMessage.length) { // Update existing message tempMessage.html(formattedContent); } else { // Create new temporary message if it doesn't exist appendMessage("bot", content, '', [], true, botId); } } function isStreamingSupported(model) { if (!model) return false; const modelPrefix = model.split('-')[0].toLowerCase(); // Support streaming for OpenAI, Claude, Grok, DeepSeek, and OpenRouter models const isSupported = modelPrefix === 'gpt' || modelPrefix === 'o1' || modelPrefix === 'claude' || modelPrefix === 'grok' || modelPrefix === 'deepseek' || model === 'openrouter'; // Add this line - check full model name for OpenRouter return isSupported; } // Update the event handlers to use the correct function names (using event delegation) // Use class-based selectors for multi-instance support $(document).on('click', '.send-button', function() { var botId = getBotIdFromElement(this); disableChatInput(botId); sendMessage(botId); }); // Override enter key handler (using event delegation) $(document).on('keypress', '.chat-input', function(e) { if (e.which == 13 && !e.shiftKey) { e.preventDefault(); var botId = getBotIdFromElement(this); disableChatInput(botId); sendMessage(botId); } }); function appendMessage(sender, messageText = '', messageHtml = '', images = [], isTemporary = false, botId = 'default') { try { // Determine styles based on sender type let messageClass, bgColor, fontColor; if (sender === "user") { messageClass = "user-message"; bgColor = userMessageBgColor; fontColor = userMessageFontColor; // Only sanitize user input messageText = sanitizeUserInput(messageText); } else if (sender === "agent") { messageClass = "agent-message"; bgColor = liveAgentMessageBgColor; fontColor = liveAgentMessageFontColor; } else { messageClass = "bot-message"; bgColor = botMessageBgColor; fontColor = botMessageFontColor; } const messageDiv = $('
tags return paragraphs .map(para => para.trim()) .filter(para => para.length > 0) // Remove empty paragraphs .map(para => `
${para}
`) .join(''); } function formatCodeBlocks(text) { // Handle fenced code blocks with language specification (```language) text = text.replace(/```(\w+)?\n?([\s\S]*?)```/g, (match, language, code) => { const lang = language || 'text'; const escapedCode = escapeHtml(code.trim()); return `${escapedCode}
$1');
// Handle raw PHP tags (legacy support)
text = text.replace(/(<\?php[\s\S]*?\?>)/g, (match) => {
const escapedCode = escapeHtml(match);
return `${escapedCode}
')) {
return unsafe;
}
return unsafe
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function decodeHTMLEntities(text) {
var textArea = document.createElement('textarea');
textArea.innerHTML = text;
return textArea.value;
}
// ====================================
// UI & SCROLLING CONTROLS
// ====================================
function scrollToBottom(botIdOrInstant, instant) {
// Handle backward compatibility: scrollToBottom() or scrollToBottom(true/false)
var botId = 'default';
if (typeof botIdOrInstant === 'string') {
botId = botIdOrInstant;
instant = instant || false;
} else if (typeof botIdOrInstant === 'boolean') {
instant = botIdOrInstant;
} else {
instant = false;
}
var chatBox = getElement(botId, 'chat-box');
if (instant) {
// Instantly set the scroll position to the bottom
chatBox.scrollTop(chatBox.prop("scrollHeight"));
} else {
// Use requestAnimationFrame for smoother scrolling if needed
let start = null;
const scrollHeight = chatBox.prop("scrollHeight");
const initialScroll = chatBox.scrollTop();
const distance = scrollHeight - initialScroll;
const duration = 500; // Duration in ms
function smoothScroll(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const currentScroll = initialScroll + (distance * (progress / duration));
chatBox.scrollTop(currentScroll);
if (progress < duration) {
requestAnimationFrame(smoothScroll);
} else {
chatBox.scrollTop(scrollHeight); // Ensure it's exactly at the bottom
}
}
requestAnimationFrame(smoothScroll);
}
}
function scrollElementToTop(element, botId) {
botId = botId || 'default';
var chatBox = getElement(botId, 'chat-box');
var elementTop = element.position().top + chatBox.scrollTop();
chatBox.animate({ scrollTop: elementTop }, 500);
}
function showChatWidget(botId) {
botId = botId || 'default';
var $button = getElement(botId, 'floating-chatbot-button');
// First ensure display is set
$button.css('display', 'flex');
// Then handle the fade
$button.fadeTo(500, 1);
// Force visibility
$button.removeClass('hidden');
}
function hideChatWidget(botId) {
botId = botId || 'default';
var $button = getElement(botId, 'floating-chatbot-button');
$button.css('display', 'none');
$button.addClass('hidden');
}
function disableScroll() {
if (isMobile()) {
$('body').css('overflow', 'hidden');
}
}
function enableScroll() {
if (isMobile()) {
$('body').css('overflow', '');
}
}
function isMobile() {
// This can be a simple check, or more sophisticated detection of mobile devices
return window.innerWidth <= 768; // Example threshold for mobile devices
}
function setFullHeight() {
var vh = $(window).innerHeight() * 0.01;
$(':root').css('--vh', vh + 'px');
}
// ====================================
// NOTIFICATION SYSTEM
// ====================================
function createNotificationBadge() {
const chatButton = document.getElementById('floating-chatbot-button');
if (!chatButton) return;
// Remove any existing badge first
const existingBadge = chatButton.querySelector('.chat-notification-badge');
if (existingBadge) {
existingBadge.remove();
}
notificationBadge = document.createElement('div');
notificationBadge.className = 'chat-notification-badge';
notificationBadge.style.cssText = `
display: none;
position: absolute;
top: -5px;
right: -5px;
background-color: red;
color: white;
border-radius: 50%;
padding: 4px 8px;
font-size: 12px;
font-weight: bold;
z-index: 10001;
`;
chatButton.style.position = 'relative';
chatButton.appendChild(notificationBadge);
}
function showNotification(botId) {
botId = botId || 'default';
const badge = getElementDOM(botId, 'chat-notification-badge');
var $floatingChatbot = getElement(botId, 'floating-chatbot');
if (badge && $floatingChatbot.hasClass('hidden')) {
badge.style.display = 'block';
badge.textContent = '1';
}
}
function hideNotification(botId) {
botId = botId || 'default';
const badge = getElementDOM(botId, 'chat-notification-badge');
if (badge) {
badge.style.display = 'none';
}
}
function startNotificationChecking(botId) {
botId = botId || 'default';
const chatPersistenceEnabled = mxchatChat.chat_persistence_toggle === 'on';
if (!chatPersistenceEnabled) return;
createNotificationBadge(botId);
var instance = MxChatInstances.get(botId);
instance.notificationCheckInterval = setInterval(function() {
checkForNewMessages(botId);
}, 30000); // Check every 30 seconds
}
function stopNotificationChecking(botId) {
botId = botId || 'default';
var instance = MxChatInstances.get(botId);
if (instance.notificationCheckInterval) {
clearInterval(instance.notificationCheckInterval);
}
}
function checkForNewMessages() {
const sessionId = getChatSession();
const chatPersistenceEnabled = mxchatChat.chat_persistence_toggle === 'on';
if (!chatPersistenceEnabled) return;
$.ajax({
url: mxchatChat.ajax_url,
type: 'POST',
data: {
action: 'mxchat_check_new_messages',
session_id: sessionId,
last_seen_id: lastSeenMessageId,
nonce: mxchatChat.nonce
},
success: function(response) {
if (response.success && response.data.hasNewMessages) {
showNotification();
}
}
});
}
// ====================================
// LIVE AGENT FUNCTIONALITY
// ====================================
function startPolling(botId) {
console.log('[MxChat] startPolling called for botId:', botId);
botId = botId || 'default';
var instance = MxChatInstances.get(botId);
// Clear any existing interval first
stopPolling(botId);
// Start new polling interval
console.log('[MxChat] Starting polling interval (5s) for botId:', botId);
instance.pollingInterval = setInterval(function() {
checkForAgentMessages(botId);
}, 5000);
}
function stopPolling(botId) {
console.log('[MxChat] stopPolling called for botId:', botId);
botId = botId || 'default';
var instance = MxChatInstances.get(botId);
if (instance.pollingInterval) {
clearInterval(instance.pollingInterval);
instance.pollingInterval = null;
console.log('[MxChat] Polling stopped for botId:', botId);
}
}
function checkForAgentMessages(botId) {
console.log('[MxChat] checkForAgentMessages called for botId:', botId);
botId = botId || 'default';
var instance = MxChatInstances.get(botId);
const sessionId = getChatSession(botId);
$.ajax({
url: mxchatChat.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'mxchat_fetch_new_messages',
session_id: sessionId,
last_seen_id: instance.lastSeenMessageId,
persistence_enabled: 'true',
nonce: mxchatChat.nonce
},
success: function (response) {
if (response.success && response.data?.new_messages) {
let hasNewMessage = false;
response.data.new_messages.forEach(function (message) {
if (message.role === "agent" && !instance.processedMessageIds.has(message.id)) {
hasNewMessage = true;
appendMessage("agent", message.content, '', [], false, botId);
instance.lastSeenMessageId = message.id;
instance.processedMessageIds.add(message.id);
}
});
var $floatingChatbot = getElement(botId, 'floating-chatbot');
if (hasNewMessage && $floatingChatbot.hasClass('hidden')) {
showNotification(botId);
}
scrollToBottom(botId, true);
}
},
error: function (xhr, status, error) {
// Polling error - silently continue
}
});
}
// ====================================
// CHAT HISTORY & PERSISTENCE
// ====================================
function loadChatHistory(botId) {
botId = botId || 'default';
var instance = MxChatInstances.get(botId);
// Prevent duplicate loading
if (instance.chatHistoryLoaded) {
return;
}
var sessionId = getChatSession(botId);
var chatPersistenceEnabled = mxchatChat.chat_persistence_toggle === 'on';
if (chatPersistenceEnabled && sessionId) {
$.ajax({
url: mxchatChat.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'mxchat_fetch_conversation_history',
session_id: sessionId
},
success: function(response) {
// Handle session reset (IP changed while user was away)
if (response.success === false && response.data && response.data.action === 'reset_session') {
// Silently reset session - user will start fresh
resetChatSession(botId);
instance.chatHistoryLoaded = true; // Prevent retry loop
return;
}
// Check if the response indicates success
if (response.success) {
// Handle case where conversation data exists and is an array
if (response.data && Array.isArray(response.data.conversation)) {
var $chatBox = getElement(botId, 'chat-box');
var $fragment = $(document.createDocumentFragment());
let highestMessageId = instance.lastSeenMessageId;
// Update chat mode if provided
if (response.data.chat_mode) {
updateChatModeIndicator(response.data.chat_mode, botId);
}
// Only process if there are actual messages
if (response.data.conversation.length > 0) {
// IMPORTANT: Clear existing messages before loading history
$chatBox.empty();
$.each(response.data.conversation, function(index, message) {
// Skip agent messages if persistence is off
if (!chatPersistenceEnabled && message.role === 'agent') {
return;
}
var messageClass, messageBgColor, messageFontColor;
switch (message.role) {
case 'user':
messageClass = 'user-message';
messageBgColor = userMessageBgColor;
messageFontColor = userMessageFontColor;
break;
case 'agent':
messageClass = 'agent-message';
messageBgColor = liveAgentMessageBgColor;
messageFontColor = liveAgentMessageFontColor;
break;
default:
messageClass = 'bot-message';
messageBgColor = botMessageBgColor;
messageFontColor = botMessageFontColor;
break;
}
var messageElement = $('