// Use the following glyphicons for the toolbar buttons
// Feedback: glyphicon glyphicon-envelope
// Chat: 

let serverLocation = ""
const hostname = window.location.hostname.toLowerCase();
if (hostname.includes('dev') || hostname.includes('stg') || hostname.includes('exp') || hostname.includes('tst')) {
    serverLocation = "https://dev-documentation.wolterskluwerfs.com/feedback/submit-feedback.php";
} else {
    serverLocation = "https://documentation.wolterskluwerfs.com/feedback/submit-feedback.php";
}

// Get the current date and time
const currentDateTime = new Date().toISOString();

// #region Feedback Form PHP
$('body').append(
    '<div id="FeedbackBox" class="feedbackBox">' +
    '<div class="container">' +
    '<div class="row" id="FeedbackBoxTitleBar" style="display:inline-block">Feedback' +
    '<a href="#" id="closeFB">' +
    '<i class="bi bi-box-arrow-right closeFBPane" style="position:absolute; right:10px;"></i>' +
    '</a>' +
    '</div>' +
    '<div class="row" id="FeedbackBoxBody">' +
    '<p id="FeedbackBodyText">We would love to hear from you about your experience with our documentation.</p>' +
    '<p id="FeedbackSupportQuestionText"><i class="bi bi-question-circle"></i> Have a product support question? <a href="#" id="contactUsLink">Contact us directly!</a></p>' +
    // Updated form action to point to the specified URL
    '<form id="feedbackForm" action="' + serverLocation + '" method="POST">' +
    // New hidden field to store the current date and time
    '<input type="hidden" id="feedback_date" name="feedback_date" value="' + currentDateTime + '">' +
    // Hidden field to store the current URL
    '<input type="hidden" id="url" name="url" value="' + window.location.href + '">' +
    // Like
    '<div id="likedDiv">' +
    '<label for="like">What do you like about the web page you are viewing?</label><br/>' +
    '<textarea id="like" name="like" rows="4" cols="50"></textarea>' +
    '</div>' +
    // Improvement
    '<div id="improveDiv">' +
    '<label for="improvement">Is there anything on the web page that could be improved?</label><br/>' +
    '<textarea id="improve" name="improve" rows="4" cols="50"></textarea>' +
    '</div>' +
    // New input for rating
    '<div id="ratingDiv">' +
    '<label for="rating">Please rate your overall experience of this web page?</label><br/>' +
    Array.from({
        length: 10
    }, (_, i) =>
        `<input type="radio" id="rating${i + 1}" name="rating" value="${i + 1}">` +
        `<label for="rating${i + 1}" class="rating-button">${i + 1}</label>`
    ).join('') +
    '</div>' +
    // CONTACT DIV
    '<div id="ContactDiv">' +
    // New checkbox for requesting contact
    '<div id="requestContactDiv">' +
    '<input type="checkbox" id="requestContact" name="request_contact">' +
    '<label id="labelRequestContact" for="requestContact">Would you like us to contact you regarding your feedback?</label>' +
    '</div>' +
    // New input for email
    '<div id="emailDiv">' +
    'If so, please include your email address.' +
    '<br/>' +
    '<input type="email" id="email" name="email" placeholder="you@example.com">' +
    '</div>' +
    '</div>' +
    // Submit button
    '<div id="submitFeedbackDiv">' +
    '<button type="submit" id="submitFeedback" class="btn btn-primary">Submit</button>' +
    '</div>' +
    '</form>' +
    '</div>' +
    '</div>' +
    '</div>'
);

// Code for showing/hiding the feedback box
$("#feedback").click(function () {
    $(".feedbackBox").addClass("show");
});

$("#closeFB").click(function () {
    $(".feedbackBox").removeClass("show");
});

function handleContactUsLink() {
    $("#contactUsLink").click(function(e) {
        e.preventDefault();
        $(".feedbackBox").removeClass("show");
        ShowContactUsBox();
    });
}

handleContactUsLink();

// Close boxes on ESC key press
$(document).on('keydown', function (event) {
    if (event.key === 'Escape') { // Check if the ESC key is pressed
        $(".chatBox").removeClass("show");
        $(".contactUsBox").removeClass("show");
        $(".feedbackBox").removeClass("show");
    }
});

// #endregion

// #region Did You Know slideout box
// $('body').append('<div id="DykBox" class="dykBox">' +
//     '<div class="container">' +
//     '<div class="row" id="DykBoxTitleBar" style="display:inline-block">' +
//     'Did you know?' + '<a href="#" id="closeDYK">' +
//     '<i class="bi bi-box-arrow-right closeDYKPane" style="position:absolute; right:10px;"></i>' +
//     '</a>' +
//     '</div>' +
//     '<div class="row" id="DykBoxBody">' +
//     '<ul class="list-group list-group-flush DYKList"></ul>' +
//     '</div>' +
//     '</div>');
// $("#closeDyk").click(function () {
//     $(".dykBox").removeClass("show");
// });
// $('.closeDYKPane').on('click', function (event) {
//     $('.dykBox').removeClass('show');
// });
// #endregion

let SupportPhone = "";
let SupportEmail = "";

// Define a function to set support contact details based on conditions
function setSupportDetails() {
    // console.log('Setting support details');
    // console.log('Variables.IsAuthoring: ' + Variables.IsAuthoring);
    // console.log('Variables.IsDGS: ' + Variables.IsDGS);
    // console.log('Variables.IsEngine: ' + Variables.IsEngine);
    // console.log('Variables.IseOriginal: ' + Variables.IseOriginal);
    // console.log('Variables.IsI32: ' + Variables.IsI32);
    // console.log('Variables.IsWKES: ' + Variables.IsWKES);
    // console.log('Variables.IsWKHosted: ' + Variables.IsWKHosted);
    // console.log('Variables.IsWKIS: ' + Variables.IsWKIS);
    // console.log('Variables.IsAssumptions: ' + Variables.IsAssumptions);
    // console.log('Variables.IsMortgage: ' + Variables.IsMortgage);
    // console.log('Variables.IsInterfaceManager: ' + Variables.IsInterfaceManager);
    // console.log('Variables.IsProductDownloadSite: ' + Variables.IsProductDownloadSite);
    // console.log('Variables.IsTSoftPlus: ' + Variables.IsTSoftPlus);
    // console.log('Variables.IsVanceo: ' + Variables.IsVanceo);
    // console.log('Variables.IsWorkflow: ' + Variables.IsWorkflow);
    console.log('Variables.SecAdmin: ' + Variables.SecAdmin);
    if (Variables.IsAuthoring || 
        Variables.IsDGS || 
        Variables.IsEngine || 
        Variables.IseOriginal || 
        Variables.IsI32 || 
        Variables.IsWKES || 
        Variables.IsWKHosted || 
        Variables.IsWKIS) {
        SupportPhone = "1-800-274-2711, ext. 1126618";
        SupportEmail = "ExpereIESupport@wolterskluwer.com";
    } else if(Variables.IsAssumptions){
        // console.log("Assumptions");
        SupportPhone = "800-274-2711 EXT 1123663";
        SupportEmail = "ComplianceOneAssumptionsSupport@wolterskluwer.com";
    } else if (Variables.IsMortgage || Variables.IsInterfaceManager){
        // console.log("IsMortgage or IsInterfaceManager");
        SupportPhone = "800-274-2711 EXT 1123665";
        SupportEmail = "ComplianceOneMortgageSupport@wolterskluwer.com";
    } else if (Variables.IsProductDownloadSite){
        SupportPhone = "800-274-2711";
        SupportEmail = "N/A";
    } else if (Variables.IsTSoftPlus){
        SupportPhone = "800-274-2711 EXT 1124028";
        SupportEmail = "TSoftSup@wolterskluwer.com";
    } else if (Variables.SecAdmin){
        SupportPhone = "800-274-2711";
        SupportEmail = "ExpereIESupport@wolterskluwer.com";
    } else if (Variables.IsVanceo){
        // console.log("IsVanceo");
        SupportPhone = "800-274-2711 EXT 1109002";
        SupportEmail = "VanceoMortgageSupport@wolterskluwer.com";
    } else if (Variables.IsWorkflow){
        SupportPhone = "800-274-2711 EXT 1125031";
        SupportEmail = "CASHSupport@wolterskluwer.com";
    }
}

// Call the function to set support details
setSupportDetails();


// #region Contact Us slideout box
$('body').append('<div id="ContactUsBox" class="contactUsBox">' +
    '<div class="container">' +
    '<div class="row" id="ContactUsBoxTitleBar" style="display:inline-block">' +
    'Contact Us' + '<a href="#" id="closeContactUs">' +
    '<i class="bi bi-box-arrow-right closeContactUsPane" style="position:absolute; right:10px;"></i>' +
    '</a>' +
    '</div>' +
    '<div class="row" id="ContactUsBoxBody">' + 
    '<p id="ContactUsTitle">Have a Product Support question?<br/><br/>' +
    'If you have any questions regarding this product, contact <br/> ' +
    'the Wolters Kluwer support team by phone or e-mail.<br/>' +
    'Support staff is available Monday through Friday, <br/>' +
    '7 A.M. to 7 P.M. Central.<br/><br/>' +
    // 'Voice mail is available after hours and on weekends.<br/><br/>' +
    // 'You can contact us directly through either of the following:<br/>' +
    '<b>Email:</b> <a href="mailto:' + SupportEmail + '">' + SupportEmail + '</a><br/>' +
    '<b>Phone:</b> <a href="tel:' + SupportPhone.replace(/[^0-9]/g, '') + '">' + SupportPhone + '</a></li>' +
    '</p>' +
    '</div>');

    // Use both id and class selectors for more specificity
    $("#closeContactUs, .closeContactUsPane").click(function (e) {
        e.preventDefault(); // Prevent default anchor behavior
        $("#ContactUsBox").removeClass("show");
    });
    
    // Add a click handler for the entire ContactUsBox
    $("#ContactUsBox").click(function(e) {
        // Close the box if the click is directly on the ContactUsBox (outside the inner content)
        if (e.target === this) {
            $(this).removeClass("show");
        }
    });// #endregion




// #region Chat slideout box
$('body').append('<div id="ChatBox" class="chatBox">' +
    '<div class="container">' +
    '<div class="row" id="ChatBoxTitleBar" style="display:inline-block">' +
    'Live Chat' + '<a href="#" id="closeCLPane">' +
    '<i class="bi bi-box-arrow-right closeChat" style="position:absolute; right:10px;"></i>' +
    '</a>' +
    '</div>' +
    '<div class="row" id="ChatBoxBody">' +
    '<p id="confEnvTitle">Have a Product Support question?<br/><span style="font-size:11px">(Available 8am-5pm CT, Mon-Fri)</span></p>' +

    '<div>' +
    '<input class="chatTextbox" type="text" name="firstname" value="Name (required)" id="firstname" autocomplete="off">' +
    '</div>' +
    '<div id="provideName"><span class="NameReminder">Please provide your name.</span></div>' +

    '<div>' +
    '<input class="chatTextbox" type="text" name="customernum" value="Customer # / Email address (required)" id="customernum" autocomplete="off" onclick="CustNumKeyPress()">' +
    '</div>' +
    '<div id="provideCustNum"><span class="NumReminder">Please provide your customer number.</div>' +

    '<div id="ContinueButton">' +
    '<button type="button" id="ChatBoxContinue" class="btn btn-primary active"  onclick="submitLiveChat()";>Continue <i class="bi bi-chevron-right"></i></button>' +
    '</div>' +
    '</div>' +
    '</div>');

$("#chat").click(function () {
    $(".chatBox").addClass("show");
});
$(".closeChat").click(function () {
    $(".chatBox").removeClass("show");
});

var enableDisable = function () {
    var currentTime = new Date().getHours();
    var currentDay = new Date().getDay();
    if (currentDay >= 1 && currentDay <= 5 && currentTime >= 4 && currentTime < 17) {
        $('#firstname').attr("disabled", false);
        $('#customernum').attr("disabled", false);
        $('#ChatBoxContinue').attr("disabled", false);
    } else {
        $('#firstname').attr("disabled", true);
        $('#customernum').attr("disabled", true);
        $('#ChatBoxContinue').attr("disabled", true);
    }
};
enableDisable();

// Show chat button
var chatAssumptions = window.location.href.indexOf("Assumptions") != -1;
var chatDocViewer = window.location.href.indexOf("DocViewer") != -1;
var chatExpere = window.location.href.indexOf("Expere") != -1;
var chatMortgage = window.location.href.indexOf("Mortgage") != -1;
var chatOPPSA = window.location.href.indexOf("OPPSA") != -1;

if (chatDocViewer || chatExpere || chatAssumptions || chatMortgage || chatOPPSA) {
    $('#chat').css('display', 'block');

    // // Create Chat notice popup div
    // var elm = '<div id="ChatBoxNotice" class="chatBoxNotice">' +
    // '<div class="confirmEnv">' +
    // 	'<div id="ChatBoxNoticeTitleBar">' +
    // 		'<div style="display:inline-block;" onclick="hideLiveChatNotice()">' +
    // 			'<a href="#" id="closeChatNotice" style=" color: black;"><i class="glyphicon glyphicon-remove-circle"></i><span style="font-size:10px">Don\'t show again</span></a>' +
    // 		'</div>' +
    // 		'<div style="display:inline-block; float: right">' +
    // 			'<i class="glyphicon glyphicon-arrow-up"></i>' +
    // 		'</div>' +
    // 	'</div>' +
    // 	'<div id="ChatBoxNoticeBody">' +
    // 		'<p id="ChatBoxNoticeTitle">Hi!     I noticed you\'ve been on the page a while.</p>' +
    // 		'<p id="ChatBoxNoticeBodyMsg">If you ever have questions and would like to speak with one of ' +
    // 		'our representatives, you can click the Chat button above!</p>' +
    // 	'</div>' +
    // '</div>';
    // $(elm).insertAfter("#ChatBox");

    $("#chat,#chatNoticeBtn").click(function () {
        $('.chatBoxNotice').css('display', 'none');
        $(".chatBox").addClass("show");
    });
    $("#closeChat").click(function () {
        $(".chatBox").removeClass("show");
    });

    // Comment the next line if you do NOT want the Live Chat notice to appear.
    // AutoShowLiveChatNotice();
}

var SelectedOption = "prod";
$('.btn-group input[type=radio]').change(function () {
    SelectedOption = (this.value);
});

$("#firstname, #customernum").on('mouseup', function () {
    $(this).select();
});

$("#customernum").keypress(function () {
    var name = $('#firstname').val();
    var custnum = $('#customernum').val();
    if (event.keyCode == 13 && (name != "Name (required)" || name != "") && (custnum != "Customer #  (required)" || custnum != "")) {
        $("#ChatBoxContinue").click();
    }
});

$("#ChatBoxContinue").click(function () {
    let switchval = 0;
    const name = $('#firstname').val();
    const custnum = $('#customernum').val();

    if (name === "Name (required)" || name === "") {
        switchval += 3;
    }
    if (custnum == "Customer #  (required)" || custnum == "") {
        switchval += 5;
    }


    switch (switchval) {
        case 0: // no problems
        // const baseurl = "https://dev-documentation.wolterskluwerfs.com/Genesys/index.html";
        const baseurl = "/Genesys/index.html";
        const fn = `?chatUsername=${name}`;
            const cn = `&customInfo=${custnum}`;
            const currentUrl = `&url=${window.location.href}`;
            let targetProduct = "";

            if (typeof chatDocViewer !== 'undefined' && chatDocViewer || typeof chatExpere !== 'undefined' && chatExpere || typeof chatOPPSA !== 'undefined' && chatOPPSA) {
                if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i)) {
                    targetProduct = "&t=FS_BMI_SL+Expere+IE+Support+Chat";
                } else {
                    targetProduct = "&t=FS_BMI_SL%25Expere%25IE%25Support%25Chat";
                }
            }

            if (typeof chatMortgage !== 'undefined' && chatMortgage) {
                if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i)) {
                    targetProduct = "&t=FS_BMI_SL+ComplianceOne+Mortgage+Chat";
                } else {
                    targetProduct = "&t=FS_BMI_SL%20ComplianceOne%20Mortgage%20Chat";
                }
            }

            if (typeof chatAssumptions !== 'undefined' && chatAssumptions) {
                if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i)) {
                    targetProduct = "&t=FS_BMI_SL+ComplianceOne+Assumptions+Chat";
                } else {
                    targetProduct = "&t=FS_BMI_SL%20ComplianceOne%20Assumptions%20Chat";
                }
            }

            const newUrl = `${baseurl}${fn}${cn}${targetProduct}${currentUrl}`;
            localStorage.setItem("i3ChatUrl", newUrl);
            window.open(newUrl);

            if (typeof SelectedOption !== 'undefined' && SelectedOption === "ct") {
                alert('Coming soon!');
            }

            $(".chatBox").removeClass("show");
            $('#provideName').css('display', 'none');
            $('#provideCustNum').css('display', 'none');
            $('#ChatBox').css('height', '290px');
            break;

        case 3: //name is missing
            $('.NameReminder').css('display', 'block');
            $('.NumReminder').css('display', 'none');
            break;

        case 5: //customer num is missing
            $('.NumReminder').css('display', 'block');
            $('.NameReminder').css('display', 'none');
            break;

        case 8: // name AND cust num are missing
            $('.NameReminder').css('display', 'block');
            $('.NumReminder').css('display', 'block');
            break;
    }
});

function submitLiveChat() {
    var url = window.location.href;
    var name = $('#firstname').val().trim();
    var custnum = $('#customernum').val().trim();
    var data = {
        "url": url,
        "name": name,
        "custnum": custnum
    }

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/resources/webhelp/php/LiveChatHandler.php',
        // dataType: 'json',
        data: JSON.stringify(data),
        success: function (result) {
            // $('#searchForm').submit();
        },
        error: function (xhr, ajaxOptions, thrownError) {
        }
    });

    return false;
}
// #endregion

// #region Button group
$('.wh_right_tools').prepend('<div class="btn-group">' +
    '<button type="button" class="btn btn-default btn-sm btn-idev" aria-label="Contact Us" title="Contact us" onclick="ShowContactUsBox()"><i class="bi bi-person-lines-fill" style="font-size: 2rem; color: #347bb7;"></i></span></button>' +
    '<button type="button" class="btn btn-default btn-sm btn-idev" aria-label="Chat" title="Chat with a live representative" onclick="ShowChatBox()"><i class="bi bi-chat-dots-fill" style="font-size: 2rem; color: #347bb7;"></i></span></button>' +
    '<button type="button" id="FeedbackButton" class="btn btn-default btn-sm btn-idev" aria-label="Feedback" title="Give your feedback" onclick="ShowFeedbackBox()"><i class="bi bi-pencil-square" style="font-size: 2rem; color: #347bb7;"></i></button>' +
    // '<button type="button" class="btn btn-default btn-sm btn-idev" aria-label="Did You Know" title="Did you know" onclick="ShowDykBox()"><i class="bi bi-mortarboard-fill" style="font-size: 2rem; color: #347bb7;"></i></button>' +
    '</div>');
// #endregion

// #region Add DYK list items
// $('.DYKList').append('<a href="/InfoDev/Using%20InfoDev%20WebHelp/index.html" target="_blank" class="list-group-item list-group-item-action">You can learn more about WebHelp features <i class="bi bi-box-arrow-up-right"></i></a>');


// if (IsChangelog) {
//     $('.DYKList').append('<a href="/InfoDev/Using%20InfoDev%20WebHelp/topics/FilteringChangelogs.html#FilteringChangelogs__section_FilterDynamically" target="_blank" class="list-group-item list-group-item-action">You can filter content dynamically <i class="bi bi-box-arrow-up-right"></i></a>');
//     $('.DYKList').append('<a href="/InfoDev/Using%20InfoDev%20WebHelp/topics/FilteringChangelogs.html#FilteringChangelogs__section_FilterDynamically" target="_blank"class="list-group-item list-group-item-action">You can filter changelogs by sprint# or PBI# <i class="bi bi-box-arrow-up-right"></i></a>');
//     $('.DYKList').append('<a href="/InfoDev/Using%20InfoDev%20WebHelp/topics/FilteringChangelogs.html#FilteringChangelogs__section_FilterByType" target="_blank" class="list-group-item list-group-item-action">You can filter changelogs by release note type <i class="bi bi-box-arrow-up-right"></i></a>');
//     $('.DYKList').append('<a href="/InfoDev/Using%20InfoDev%20WebHelp/topics/FilteringChangelogs.html#FilteringChangelogs__section_FoldingContent" target="_blank" class="list-group-item list-group-item-action">You can fold all changelogs dynamically <i class="bi bi-box-arrow-up-right"></i></a>');
// } else {
//     $('.DYKList').append('<a href="/InfoDev/Using%20InfoDev%20WebHelp/topics/AccessingRelatedDocumentation.html" target="_blank" class="list-group-item list-group-item-action">You always have quick access to the changelog <i class="bi bi-box-arrow-up-right"></i></a>');

// }
// #endregion

// #region Slider box placement
var ToolsPosition = $('.wh_tools').position();
// $('#DykBox').css('top', ToolsPosition.top + $('.wh_tools').height() + 10);
$('#FeedbackBox').css('top', ToolsPosition.top + $('.wh_tools').height() + 10);
$('#ChatBox').css('top', ToolsPosition.top + $('.wh_tools').height());
// #endregion

// #region Functions
function ShowContactUsBox() {
    // $('.dykBox').removeClass('show');
    $(".feedbackBox").removeClass("show");
    $(".chatBox").removeClass("show");
    if ($('.contactUsBox').hasClass('show')) {
        $(".contactUsBox").removeClass("show");
    } else {
        $(".contactUsBox").addClass("show");
    }
}

function ShowChatBox() {
    // $('.dykBox').removeClass('show');
    $(".contactUsBox").removeClass("show");
    $(".feedbackBox").removeClass("show");
    if ($('.chatBox').hasClass('show')) {
        $(".chatBox").removeClass("show");
    } else {
        $(".chatBox").addClass("show");
    }
}

function ShowFeedbackBox() {
    // $('.dykBox').removeClass('show');
    $(".chatBox").removeClass("show");
    $(".contactUsBox").removeClass("show");
    if ($('.feedbackBox').hasClass('show')) {
        $(".feedbackBox").removeClass("show");
    } else {
        $(".feedbackBox").addClass("show");
    }
}

// function ShowDykBox() {
//     $(".chatBox").removeClass("show");
//     $(".feedbackBox").removeClass("show");
//     if ($('.dykBox').hasClass('show')) {
//         $('.dykBox').removeClass('show');
//     } else {
//         $('.dykBox').addClass('show');
//     }
// }



$(document).ready(function() {
    // Disable the email input by default
    $('#emailDiv').addClass('disabled');
    $('#email').prop('disabled', true);

    // Toggle the email input when the request contact checkbox is checked/unchecked
    $('#requestContact').on('change', function() {
        if ($(this).is(':checked')) {
            $('#emailDiv').removeClass('disabled');
            $('#email').prop('disabled', false);
        } else {
            $('#emailDiv').addClass('disabled');
            $('#email').prop('disabled', true);
            $('#email').val(''); // Clear the email field when unchecked
        }
    });

    // Remove any existing submit event handlers
    $('form').off('submit');

    let isSubmitting = false;

    // Handle form submission
    $('#feedbackForm').on('submit', function(event) {
        event.preventDefault();

        if (isSubmitting) {
            return;
        }

        const form = $(this);
        const submitButton = form.find('button[type="submit"]');
        const requestContactChecked = $('#requestContact').is(':checked');
        const emailValue = $('#email').val().trim();
        const likeValue = $('#like').val().trim();
        const improveValue = $('#improve').val().trim();
        const ratingValue = $('input[name="rating"]:checked').val();

        // Validate form inputs
        if (requestContactChecked && !validateEmail(emailValue)) {
            alert('Please enter a valid email address if you want to be contacted.');
            $('#email').focus();
            return;
        } else if (!likeValue && !improveValue) {
            alert('Please fill in at least one field before submitting.');
            return;
        }

        // if ((!likeValue || !improveValue) ) {
        //     alert('Please fill in at least one field before submitting.');
        // return;
        // }

        // If validation passes, submit the form via AJAX
        isSubmitting = true;
        submitButton.prop('disabled', true);
        submitFeedbackForm(form, submitButton);
    });
    
    function submitFeedbackForm(form, submitButton) {
        $('body').css('cursor', 'wait');
    
        $.ajax({
            type: 'POST',
            url: serverLocation,
            data: form.serialize(),
            dataType: 'json',
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            success: function (response) {
                if (response.success) {
                    alert(response.message);
                    $(".feedbackBox").removeClass("show");
                    form[0].reset();
                } else {
                    alert(response.message || 'An error occurred while submitting the form.');
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error("AJAX request failed:", textStatus, errorThrown);
                alert('An unexpected error occurred. Please try again later. (Error: ' + textStatus + ')');
            },
            complete: function () {
                $('body').css('cursor', 'default');
                submitButton.prop('disabled', false);
                isSubmitting = false;
            }
        });
    }
    
    function validateEmail(email) {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailPattern.test(email);
    }
});
// #endregion


//#region New FeedbackNotice div container
$(document).ready(function() {
    // Check if the user has dismissed the FeedbackNotice
    if (!localStorage.getItem('feedbackNoticeDismissed')) {
        $('body').append(
            '<div id="FeedbackNotice" class="feedbackNotice" style="display: none;">' + // Ensure it's hidden initially
            '<div class="FeedbackNoticeHeader">' +
                '<i class="bi bi-envelope-fill" style="font-size: 2rem; color: #ffffff;"></i>' +
                '<span id="HeaderText">We\'d love your Feedback</span>' +
                '<i class="bi bi-arrow-90deg-up" style="float: right; font-size: 1.5em; margin-right: 16px; margin-left: 50px"></i>' +
            '</div>' +
            '<div class="FeedbackNoticeContent">How can we make this page better?<br/>From any topic you can leave us your comments and help us out!</div>' +
            '<div class="FeedbackNoticeFooter" style="padding: 5px; display: flex; justify-content: space-between; margin-top: auto;">' + // Use flexbox for alignment
            '<button id="closeFeedbackNotice" style="margin-right: auto;">Close</button>' + // Left-aligned Close button
            '<a href="#" id="Dismiss" style="margin-left: auto;">Dismiss</a>' + // Right-aligned link
            '</div>' +
            '</div>'
        );

        $('#FeedbackNotice').css({
            display: 'none',
            flexDirection: 'column', // Ensure the layout is column
            width: 330,
            height: 170,
            marginTop: 10,
            position: 'absolute',
            border: '2px solid #85bc20',
            borderRadius: 4,
            backgroundColor: '#ffffff',
            boxShadow: '0px 0px 10px #000000', // Added shadow background
            zIndex: 999,
        });

        $('.FeedbackNoticeHeader').css({
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'flex-start',
            backgroundColor: 'rgba(133, 188, 32, 1.0)',
            color: '#ffffff',
            padding: '10px',
        });
        
        $('#HeaderText').css({
            fontSize: 'medium',
            marginLeft: '10px',
        });
        
        $('.FeedbackNoticeContent').css({
            padding: '8px',
            flexGrow: 1,
            overflow: 'auto',
        });

        $('.FeedbackNoticeFooter').css({
            backgroundColor: '#f1f1f1',
            padding: '5px',
            marginTop: 'auto', // Push footer to the bottom
        });

        $('#closeFeedbackNotice').css({
            backgroundColor: '#85bc20',
            color: '#ffffff',
            border: 'none',
            borderRadius: '4px',
            padding: '5px 10px',
            cursor: 'pointer',
            transition: 'background-color 0.3s',
        });

        $('#Dismiss').css({
            alignContent: 'center',
            marginRight: '10px',
        });

        $('#closeFeedbackNotice').hover({
            function() {
                $(this).css('background-color', '#6fae1f'); // Darker green on hover
            },
            function() {
                $(this).css('background-color', '#85bc20'); // Original color
            }
        });

        // Fade in the FeedbackNotice div after a slight delay
        setTimeout(function() {
            $('#FeedbackNotice').css({
                top: $('#FeedbackButton').offset().top + $('#FeedbackButton').outerHeight(), // Position below the Feedback button with a small gap
                left: $('#FeedbackButton').offset().left + $('#FeedbackButton').outerWidth() - 310 // Align right edge with Feedback button
            });
            $('#FeedbackNotice').fadeIn(500); // Fade in over 500 milliseconds
        }, 2000); // Delay in milliseconds (2000ms = 2 seconds)
    }

    // Close button click event
    $('#closeFeedbackNotice').click(function() {
        $('#FeedbackNotice').fadeOut(); // Hide the FeedbackNotice div with fade out
    });

    // Dismiss button click event
    $('#Dismiss').click(function(event) {
        event.preventDefault(); // Prevent default anchor behavior
        localStorage.setItem('feedbackNoticeDismissed', 'true'); // Store the preference
        $('#FeedbackNotice').fadeOut(); // Hide the FeedbackNotice div
    });
});
// #endregion