// search.js

// const IsIndex  = window.location.href.indexOf("/index.html") != -1;
const IsSearch = window.location.href.indexOf("/search.html") != -1;
let SearchPath = '';
let TelNum = '';
let EmailAdd = '';

// Helper function to safely get the lowercase value of a variable
function safeToLowerCase(variable) {
    return typeof variable === 'string' ? variable.toLowerCase() : String(variable).toLowerCase();
}

// Extract the relevant part of the URL path and convert it to lowercase
const pathParts = window.location.pathname.split('/');
const relevantPart = pathParts.length > 1 ? safeToLowerCase(pathParts[1]) : '';
// console.log(relevantPart);
// #region Product Support variables
if (relevantPart === 'expere' || 
    relevantPart === 'engine' || 
    relevantPart === 'i32' || 
    relevantPart === 'woltersKluwer_e-sign' || 
    relevantPart === 'wkhostedexpere') {
    TelNum = 'Tel: 1-800-274-2711, ext. 1126618';
    EmailAdd = 'E-mail: ExpereIESupport@wolterskluwer.com';
} else if (relevantPart === 'assumptions') {
    // console.log('assumptions');
    TelNum = 'Tel: 800-274-2711 EXT 1109001';
    EmailAdd = 'E-mail: VanceoAssumptionsSupport@wolterskluwer.com';
} else if (relevantPart === 'interfacemanager') {
    TelNum = 'Tel: 800-274-2711 EXT 1123665';
    EmailAdd = 'E-mail: ComplianceOneMortgageSupport@wolterskluwer.com';
} else if (relevantPart === 'mortgage') {
    // console.log('mortgage');
    TelNum = 'Tel: 800-274-2711 EXT 1123665';
    EmailAdd = 'E-mail: ComplianceOneMortgageSupport@wolterskluwer.com';
} else if (relevantPart === 'tsoftplus') {
    TelNum = 'Tel: 800-274-2711 EXT 1124028';
    EmailAdd = 'E-mail: TSoftSup@wolterskluwer.com';
} else if (relevantPart === 'workflow') {
    TelNum = 'Tel: 800-274-2711 EXT 1125031';
    EmailAdd = 'E-mail: CASHSupport@wolterskluwer.com';
} else {
    TelNum = 'Tel: 800-274-2711';
}
// #endregion

// #region SEARCH FEEDBACK FORM
if (IsSearch) {
    $(".wh_search_results").css({
        'display': 'flex',
        'flex-direction': 'row',
        'justify-content': 'space-between',
    });
    $(".wh_search_results_items").css("flex", "1");

    function appendSearchFeedbackForm() {
        // Get the current date and time
        const currentDateTime = new Date().toISOString();
    
        // Create the main div
        const feedbackDiv = $('<div id="SearchFeedbackFormDiv"></div>').css({
            'width': '440px',
            'border': '2px solid #007ac3',
            'border-radius': '8px',
            'margin-left': '20px',
            'height': 'fit-content',
        });
    
        // Create the title bar
        const titleBar = $('<div class="titlebar">Search Feedback</div>').css({
            'background-color': '#007ac3',
            'color': 'white',
            'padding': '10px',
            'font-weight': 'bold',
            'text-align': 'center'
        });
    
        // Create the content div
        const contentDiv = $('<div class="content"></div>').css({
            'padding': '10px'
        });
    
        // Add intro paragraph to content div
        const introParagraph = $('<p><b>Not finding what you need?</b><br/>Take a moment to let us know how we can help!</p>');
        contentDiv.append(introParagraph);
    
        // Add intro Naotice to content div
        const introNotice = $('<p><b>IMPORTANT</b><br/>This form is provided for questions about our documentation.<br/>' +
            'If you have a product support question, please contact us directly:<br/>' +
            TelNum + '<br/>' + EmailAdd + '</p>').css({
            'font-size': 'smaller', 'border': '1px solid #007ac3', 'background-color': 'azure', 'border-radius': '4px', 'padding': '5px', 'line-height': '1.2'
        });
        contentDiv.append(introNotice);
    
        // Add Comments input
        const commentsDiv = $('<div id="commentsDiv">' +
            '<label for="improve">Comments</label><br/>' +
            '<textarea id="searchFeedbackComments" name="improve" rows="4" cols="42" ' +
                    'style="border: 1px solid #007ac3; border-radius: 4px; min-height: 60px; ' +
                    'max-width: 100%; box-sizing: border-box;"></textarea>' +
            '</div>')
        contentDiv.append(commentsDiv);
    
        // Add Email div
        const contactDiv = $('<div id="ContactDiv">' +
            '<div id="requestContactDiv">' +
            '<input type="checkbox" id="searchFeedbackContact" name="request_contact">' +
            '<label id="labelRequestContact" for="requestContact" style="cursor: pointer">Would you like us to contact you?</label>' +
            '</div>' +
            '<div id="emailDiv">' +
            'If so, please include your email address.' +
            '<br/>' +
            '<input type="email" id="searchFeedbackEmail" name="email" placeholder="you@example.com"' +
                'style="border: 1px solid #007ac3; border-radius: 4px; width: -webkit-fill-available;">' +
            '</div>' +
            '</div>');
        contentDiv.append(contactDiv);
    
        // Date and URL
        const nowDateTime = $('<input type="hidden" id="feedback_date" name="feedback_date" value="' + currentDateTime + '">');
        const thisLocation = $('<input type="hidden" id="url" name="url" value="' + window.location.href + '">');
        contentDiv.append(nowDateTime);
        contentDiv.append(thisLocation);
    
        // Add Submit button
        const submitButton = $('<div id="submitFeedbackDiv">' +
        '<button type="submit" id="submitSearchPageFeedback" class="btn btn-primary" style="margin-top: 10px;">Submit</button>' +
        '</div>');
        contentDiv.append(submitButton);
    
        // Create the form element and append content
        const form = $('<form id="searchFeedbackForm"></form>').append(contentDiv);
    
        // Append title bar and form to the main div
        feedbackDiv.append(titleBar).append(form);
    
        // Append the main div to the .wh_content_area
        $('.wh_search_results').append(feedbackDiv);
    }
    
    // Call the function to append the div
    // appendSearchFeedbackForm();

    // Prevent default form submission
    $('#submitSearchPageFeedback').on('click', function(event) {
        event.preventDefault();

        // Get the comments value
        const comments = $('#searchFeedbackComments').val().trim();

        // Check if comments are empty or less than 15 characters
        if (comments.length < 15) {
            alert('Please provide comments with at least 15 characters.');
            return; // Stop the form submission
        }

        // Get the email value
        const email = $('#searchFeedbackEmail').val().trim();

        // Email validation regex
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        // Validate email
        if (email && !emailPattern.test(email)) {
            alert('Please enter a valid email address.');
            return; // Stop the form submission
        }

        // Collect form data using serialize()
        let formData = $('#searchFeedbackForm').serialize();

        // Prepend 'search.html feedback' to the comments value within the serialized form data
        formData = formData.replace('improve=' + encodeURIComponent(comments), 'improve=' + encodeURIComponent('search.html feedback: ' + comments));

        // Troubleshooting: Log the formData to check values
        // console.log("Serialized Form Data:", formData);

        $.ajax({
            type: 'POST',
            url: serverLocation,
            data: formData, // Send serialized data
            success: function (response) {
                // Troubleshooting: Log the response to check success
                // console.log("Response:", response);
                if (response.success) {
                    alert(response.message);
                    $('#searchFeedbackComments').val(''); // Reset the comments textarea
                    $('#searchFeedbackEmail').val(''); // Reset the email input if needed
                } 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');
                $('#submitSearchPageFeedback').prop('disabled', false);
            }
        });
    });

    // Toggle the checked state
    $('#labelRequestContact').on('click', function() {
        $('#searchFeedbackContact').prop('checked', function(i, value) {
            return !value;
        });
    });
}

// #endregion SEARCH FEEDBACK FORM

// #region Doc Gen Services
if (Variables.IsDefaultDataUserGuide){ SearchPath = '/ExpereEZConfig/DefaultData/UserGuide/' + 'search.html'; }
if (Variables.IsDefaultDataInstallGuide){ SearchPath = '/ExpereEZConfig/DefaultData/InstallationGuide/' + 'search.html'; }
if (Variables.IsDefaultDataODInstGuide){ SearchPath = '/ExpereEZConfig/DefaultData/OD-InstallGuide/' + 'search.html'; }
if (Variables.IsDefaultDataUpgradeGuide){ SearchPath = '/ExpereEZConfig/DefaultData/UpgradeGuide/' + 'search.html'; }
if (Variables.IsDefaultDataWebServGuide){ SearchPath = '/ExpereEZConfig/DefaultData/WebServicesGuide/' + 'search.html'; }
if (Variables.IsDGSChangelog){ SearchPath = '/DGS/Change-Log/' + 'search.html'; }
if (Variables.IsDGSImpStrat){ SearchPath = '/DGS/Implementation-Strategies/' + 'search.html'; }
if (Variables.IsDGSMgmtToolGuide){ SearchPath = '/DGS/Management-Tool/' + 'search.html'; }
if (Variables.IsDGSODInstallGuide){ SearchPath = '/DGS/OD-Installation-Guide/' + 'search.html'; }
if (Variables.IsDGSServInstallGuide){ SearchPath = '/DGS/Installation-Guide/' + 'search.html'; }
if (Variables.IsDGSServUpgradeGuide){ SearchPath = '/DGS/Upgrade-Process/' + 'search.html'; }
if (Variables.IsDGSToolSuite){ SearchPath = '/DGS/Tool-Suite/' + 'search.html'; }
if (Variables.IsDGSWebServices){ SearchPath = '/DGS/Web-Services/' + 'search.html'; }
if (Variables.IsEOriginalQuickGuide){ SearchPath = '/Expere/eOriginal/QuickGuide/' + 'search.html'; }
if (Variables.IsEZConfConsChangelog){ SearchPath = '/ExpereEZConfig/ChangeLog/' + 'search.html'; }
if (Variables.IsEZGatewayInstallGuide){ SearchPath = '/ExpereEZConfig/EZGateway/InstallGuide/' + 'search.html'; }
if (Variables.IsEZGatewayODInstGuide){ SearchPath = '/ExpereEZConfig/EZGateway/OD-Installation-Guide/' + 'search.html'; }
if (Variables.IsEZGatewayWebServGuide){ SearchPath = '/ExpereEZConfig/EZGateway/WebServices/' + 'search.html'; }
if (Variables.IsOAuthSetupGuide){ SearchPath = '/OAuth/Setup/' + 'search.html'; }
if (Variables.IsPnPInstallGuide){ SearchPath = '/ExpereEZConfig/InstallGuide/' + 'search.html'; }
if (Variables.IsPNPUpgradeGuide){ SearchPath = '/ExpereEZConfig/PackagesAndPackets/UpgradeGuide/' + 'search.html'; }
if (Variables.IsPNPUserGuide){ SearchPath = '/ExpereEZConfig/PackagesAndPackets/UserGuide/' + 'search.html'; }
if (Variables.IsPNPWebServGuide){ SearchPath = '/ExpereEZConfig/WebservicesGuide/' + 'search.html'; }
// #endregion

// #region Authoring
// 2023-04-21: All landing page items accounted for
if (Variables.IsAdminToolUG){ SearchPath = Variables.AdminToolUG + 'search.html'; }
if (Variables.IsAuthoringChangelog){ SearchPath = Variables.AuthoringRN + 'search.html'; }
if (Variables.IsAuthoringEnvInstUg){ SearchPath = Variables.AuthoringEnvInstUg + 'search.html'; }
if (Variables.IsDictionaryViewerUG){ SearchPath = Variables.DictionaryViewerUG + 'search.html'; }
if (Variables.IsEngineInstallationUG){ SearchPath = Variables.EngineInstallationUG + 'search.html'; }
if (Variables.IsReqEd3UG){ SearchPath = Variables.ReqEd3UG + 'search.html'; }
if (Variables.IsReqEd4UG){ SearchPath = Variables.ReqEd4UG + 'search.html'; }
// #endregion

// #region Engine
// 2023-04-21: All landing page items accounted for
if (Variables.IsDocViewerChangelog){ SearchPath = Variables.DocViewerChangelog + 'search.html'; }
if (Variables.IsDocViewerIntGuide){ SearchPath = Variables.DocViewerIntGuide + 'search.html'; }
if (Variables.IsDocViewerUserGuide){ SearchPath = Variables.DocViewerUserGuide + 'search.html'; }
if (Variables.IsEngineChangelog){ SearchPath = Variables.EngineChangelog + 'search.html'; }
if (Variables.IsExpereDeveloperGuide){ SearchPath = Variables.ExpereDeveloperGuide + 'search.html';}
if (Variables.IsExpereImpGuide){ SearchPath = Variables.ExpereImpGuide + 'search.html'; }
if (Variables.IsExpereSystemReq){ SearchPath = Variables.ExpereSystemReq + 'search.html'; }
if (Variables.IsExpereTestingSystem){ SearchPath = Variables.ExpereTestingSystem + 'search.html'; }
// #endregion

// #region I-32
// 2023-04-27: All landing page items accounted for
// if (IsI32){ SearchPath = '' + 'search.html'; }
if (Variables.IsI32Changelog){ SearchPath = Variables.I32Changelog + 'search.html'; }
if (Variables.IsI32FormsDesignUG){ SearchPath = Variables.I32FormsDesignUG + 'search.html'; }
if (Variables.IsI32ImageUpdateUG){ SearchPath = Variables.I32ImageUpdateUG + 'search.html'; }
// #endregion

// #region WK-ESign
// 2023-04-27: All landing page items accounted for
if (Variables.IsWKESignCaptureGuide){ SearchPath = Variables.WKESignCaptureGuide + 'search.html'; }
if (Variables.IsWKESignFAQ){ SearchPath = Variables.WKESignFAQ + 'search.html'; }
if (Variables.IsWKESignLegacyUserGuide){ SearchPath = Variables.WKESignLegacyUserguide + 'search.html'; }
if (Variables.IsWKESignOnsiteUG){ SearchPath = Variables.WKESignOnsiteUG + 'search.html'; }
if (Variables.IsWKESignPushStatusUG){ SearchPath = Variables.WKESignPushStatusUG + 'search.html'; }
if (Variables.IsWKESignReleaseNotes){ SearchPath = Variables.WKESignReleaseNotes + 'search.html'; }
if (Variables.IsWKESignSysReq){ SearchPath = Variables.WKESignSysReq + 'search.html'; }
if (Variables.IsWKESignUserGuide){ SearchPath = Variables.WKESignUserGuide + 'search.html'; }
if (Variables.IsWKESignWebServices){ SearchPath = Variables.WKESignWebServices + 'search.html'; }
// #endregion

// #region WK-Hosted-Expere (EDS)

if (Variables.IsWKHostedChangelog){ SearchPath = '/WK-Hosted-Expere/Change-Log/' + 'search.html'; }
if (Variables.IsWKHostedImpStrat){ SearchPath = '/WK-Hosted-Expere/Implementation-Strategies/' + 'search.html'; }
if (Variables.IsWKHostedToolSuite){ SearchPath = Variables.WKHostedToolSuite + 'search.html'; }
if (Variables.IsWKHostedWebServices){ SearchPath = '/WK-Hosted-Expere/Web-Services/' + 'search.html'; }
// #endregion

// #region Lending Systems
if (Variables.IsAssumptions){ SearchPath = Variables.Assumptions + 'search.html'; }
if (Variables.IsMortgage){ SearchPath = Variables.Mortgage + 'search.html'; }
if (Variables.IsSecAdmin){ SearchPath = Variables.SecAdmin + 'search.html'; }
if (Variables.IsSecAdminSelfHosted){ SearchPath = Variables.SecAdminSelfHosted + 'search.html'; }
if (Variables.IsVanceo){ SearchPath = Variables.Vanceo + 'search.html'; }
// #endregion



// if (!Variables.IsIndex && !Variables.IsSearch){
//     $('#searchForm').attr('action', SearchPath);
// }

// console.log("SearchPath = " + SearchPath);