jQuery(document).ready(function($) { //console.log('mxchatChat object:', mxchatChat); // Initialize color settings 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 linkTarget = mxchatChat.link_target === 'on' ? '_blank' : '_self'; function getChatSession() { var sessionId = getCookie('mxchat_session_id'); //console.log("Session ID retrieved from cookie: ", sessionId); if (!sessionId) { sessionId = generateSessionId(); //console.log("Generated new session ID: ", sessionId); setChatSession(sessionId); } //console.log("Final session ID: ", sessionId); return sessionId; } function setChatSession(sessionId) { // Set the cookie with a 24-hour expiration (86400 seconds) document.cookie = "mxchat_session_id=" + sessionId + "; path=/; max-age=86400; SameSite=Lax"; } // Get cookie value by name function getCookie(name) { let value = "; " + document.cookie; let parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } // Generate a new session ID function generateSessionId() { return 'mxchat_chat_' + Math.random().toString(36).substr(2, 9); } // Function to send the message to the chatbot (backend) function sendMessageToChatbot(message) { var sessionId = getChatSession(); // Reuse the session ID logic // Hide the popular questions section $('#mxchat-popular-questions').hide(); // Show thinking indicator (no need to append the user's message again) appendThinkingMessage(); scrollToBottom(); //console.log("Sending message to chatbot:", message); // Log the message //console.log("Session ID:", sessionId); // Log the session ID // Call the chatbot using the same call logic as sendMessage callMxChat(message, function(response) { // ** Ensure temporary thinking message is removed before adding new response ** $('.temporary-message').remove(); // Replace thinking indicator with actual response replaceLastMessage("bot", response); }); } function sendMessage() { var message = $('#chat-input').val(); if (message) { appendMessage("user", message); $('#chat-input').val(''); // Hide the popular questions section $('#mxchat-popular-questions').hide(); // Show typing indicator appendThinkingMessage(); scrollToBottom(); callMxChat(message, function(response) { // Replace typing indicator with actual response replaceLastMessage("bot", response); }); } } // Function to append a thinking message with animation function appendThinkingMessage() { // Remove any existing thinking dots first $('.thinking-dots').remove(); // Retrieve the bot message font color and background color var botMessageFontColor = mxchatChat.bot_message_font_color; var botMessageBgColor = mxchatChat.bot_message_bg_color; var thinkingHtml = '
and tags
return `
${escapeHtml(codeContent)}
`;
});
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Function to convert newlines, skipping preformatted text
function convertNewlinesToBreaks(text) {
// Regex to exclude and tags from adding
tags
return text.replace(/(^|[^>])\n/g, '$1
');
}
$(document).ready(function() {
loadChatHistory();
});
// Helper function to check if a string is an image HTML
function isImageHtml(str) {
return str.startsWith('
');
}
// Function to remove thinking dots
function removeThinkingDots() {
$('.thinking-dots').closest('.temporary-message').remove();
}
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 disableScroll() {
if (isMobile()) {
$('body').css('overflow', 'hidden');
}
}
function enableScroll() {
if (isMobile()) {
$('body').css('overflow', '');
}
}
// Function to show the chatbot widget (moved outside the Complianz logic)
function showChatWidget() {
setTimeout(function() {
$('#floating-chatbot-button').css('display', 'flex').fadeTo(500, 1);
}, 250);
}
// Function to hide the chatbot widget
function hideChatWidget() {
$('#floating-chatbot-button').css('display', 'none');
}
// Pre-chat dismissal check function (wrapped in a function for reuse)
function checkPreChatDismissal() {
$.ajax({
url: mxchatChat.ajax_url,
type: 'POST',
data: {
action: 'mxchat_check_pre_chat_message_status',
_ajax_nonce: mxchatChat.nonce
},
success: function(response) {
if (response.success && !response.data.dismissed) {
$('#pre-chat-message').fadeIn(250);
} else {
$('#pre-chat-message').hide();
}
},
error: function() {
console.error('Failed to check pre-chat message dismissal status.');
}
});
}
// Function to dismiss pre-chat message for 24 hours
function handlePreChatDismissal() {
$('#pre-chat-message').fadeOut(200);
$.ajax({
url: mxchatChat.ajax_url,
type: 'POST',
data: {
action: 'mxchat_dismiss_pre_chat_message',
_ajax_nonce: mxchatChat.nonce
},
success: function() {
$('#pre-chat-message').hide();
},
error: function() {
console.error('Failed to dismiss pre-chat message.');
}
});
}
// Handle pre-chat message dismissal on button click
$(document).on('click', '.close-pre-chat-message', function(e) {
e.stopPropagation();
handlePreChatDismissal();
});
// Function for Complianz logic
var applyComplianzLogic = mxchatChat.complianz_toggle;
if (applyComplianzLogic) {
function checkConsentAndShowChat() {
var consentStatus = typeof cmplz_has_consent === "function" && cmplz_has_consent('marketing');
var consentType = typeof complianz !== 'undefined' ? complianz.consenttype : null;
if (consentType === 'optin' && !consentStatus) {
hideChatWidget();
} else if (consentType === 'optout' && !consentStatus) {
hideChatWidget();
} else {
showChatWidget();
checkPreChatDismissal(); // Ensure we check dismissal after consent is handled
}
}
checkConsentAndShowChat();
$(document).on('cmplz_status_change', function(event, category) {
checkConsentAndShowChat();
});
} else {
showChatWidget();
checkPreChatDismissal(); // Always check pre-chat dismissal when consent logic is not applied
}
// Toggle chatbot visibility on floating button click
$(document).on('click', '#floating-chatbot-button', function() {
var chatbot = $('#floating-chatbot');
if (chatbot.hasClass('hidden')) {
chatbot.removeClass('hidden').addClass('visible');
$(this).addClass('hidden');
disableScroll();
// Hide the pre-chat message without dismissing it
$('#pre-chat-message').fadeOut(250);
} else {
chatbot.removeClass('visible').addClass('hidden');
$(this).removeClass('hidden');
enableScroll();
// Show the pre-chat message again if it hasn't been dismissed
checkPreChatDismissal();
}
});
$(document).on('click', '#exit-chat-button', function() {
$('#floating-chatbot').addClass('hidden').removeClass('visible');
$('#floating-chatbot-button').removeClass('hidden');
enableScroll();
});
// Close pre-chat message on click
$(document).on('click', '.close-pre-chat-message', function(e) {
e.stopPropagation(); // Prevent triggering the parent .pre-chat-message click
$('#pre-chat-message').fadeOut(200, function() {
$(this).remove();
});
});
// Open chatbot when pre-chat message is clicked
$(document).on('click', '#pre-chat-message', function() {
var chatbot = $('#floating-chatbot');
if (chatbot.hasClass('hidden')) {
chatbot.removeClass('hidden').addClass('visible');
$('#floating-chatbot-button').addClass('hidden');
$('#pre-chat-message').fadeOut(250); // Hide pre-chat message
disableScroll(); // Disable scroll when chatbot opens
}
});
// If the chatbot is initially hidden, ensure the button is visible
if ($('#floating-chatbot').hasClass('hidden')) {
$('#floating-chatbot-button').removeClass('hidden');
}
function setFullHeight() {
var vh = $(window).innerHeight() * 0.01;
$(':root').css('--vh', vh + 'px');
}
// Set the height when the page loads
$(document).ready(function() {
setFullHeight();
});
// Set the height on resize and orientation change events
$(window).on('resize orientationchange', function() {
setFullHeight();
});
// Now handle the close button to dismiss the pre-chat message for 24 hours
var closeButton = document.querySelector('.close-pre-chat-message');
if (closeButton) {
closeButton.addEventListener('click', function() {
$('#pre-chat-message').fadeOut(200); // Hide the message
// Send an AJAX request to set the transient flag for 24 hours
$.ajax({
url: mxchatChat.ajax_url,
type: 'POST',
data: {
action: 'mxchat_dismiss_pre_chat_message',
_ajax_nonce: mxchatChat.nonce
},
success: function() {
//console.log('Pre-chat message dismissed for 24 hours.');
// Ensure the message is hidden after dismissal
$('#pre-chat-message').hide();
},
error: function() {
//console.error('Failed to dismiss pre-chat message.');
}
});
});
}
// Event listener for Add to Cart button
$(document).on('click', '.add-to-cart-button', function() {
var productId = $(this).data('product-id'); // Get product ID from data attribute
// Simulate user message first for proper ordering
appendMessage("user", "add to cart"); // Display the user's "add to cart" message first
// Use existing function to send the "add to cart" command to the chatbot
sendMessageToChatbot("add to cart"); // Triggers the chatbot response as though user typed it
});
});