// resources\landingpages\js\lp_external.js

// #region TODO:
// - Create array variables and function for Product/ProductAbrev. This would allows us to have all products listed and then
//      we simply uncomment the desired product
// - Create array variables and function for productSummary. This would allows us to have all product summaries listed and then
//      we simply uncomment the desired summary
// #endregion


//#region FUNCTIONS - CHANGE NOTHING BELOW THIS LINE ///////////////////////////////////////////////////
// Function to include HTML
function includeHTML() {
    var z, i, elmnt, file, xhttp;
    /*loop through a collection of all HTML elements:*/
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        /*search for elements with a certain attribute:*/
        file = elmnt.getAttribute("w3-include-html");
        if (file) {
            /*make an HTTP request using the attribute value as the file name:*/
            xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4) {
                    if (this.status == 200) {
                        elmnt.innerHTML = this.responseText;
                    }
                    if (this.status == 404) {
                        elmnt.innerHTML = "Page not found.";
                    }
                    /*remove the attribute, and call this function once more:*/
                    elmnt.removeAttribute("w3-include-html");
                    includeHTML();
                }
            }
            xhttp.open("GET", file, true);
            xhttp.send();
            /*exit the function:*/
            return;
        }
    }
}

// Function to show/hide announcement based on date
function announcementTime() {
    if (announcementStart <= today && today >= announcementEnd) {
        // current date is within range
        $('#announcement').show();
    } else {
        // current date is out of range
        $('div#announcement').hide();
    }
}

// Function to clear the browser cache and reload the page
function clearCacheAndReload() {
    if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
        // Unregister service workers
        navigator.serviceWorker.getRegistrations().then(function(registrations) {
            for (let registration of registrations) {
                registration.unregister();
            }
        });
    }

    // Clear cache
    caches.keys().then(function(cacheNames) {
        cacheNames.forEach(function(cacheName) {
            caches.delete(cacheName);
        });
    });

    // Force a hard reload
    window.location.reload(true);
}

// Function to create list items for release notes
function createReleaseNoteListItem(item) {
    var listItem = $("<li></li>");
    var link = $("<a></a>").attr("href", item.link).text(item.title);
    listItem.append(link);

    // If the 'info' attribute is not blank, add an icon with tooltip
    if (item.info && item.info.trim() !== "") {
        var infoIcon = $("<span></span>")
            .addClass("custom-tooltip") // Add custom-tooltip class
            .css("margin-left", "5px")
            .attr("data-tooltip", item.info); // Set tooltip text using data-tooltip attribute
        listItem.append(infoIcon);
    }

    return listItem;
}

// Modify the function to create release notes panel
function createReleaseNotesPanel(panelData) {
    var panelElement = $("<div></div>").addClass("panel panel-primary");

    // Create panel heading
    var panelHeading = $("<div></div>").addClass("panel-heading").css("background-color", "#85bc20").css("color", "#ffffff").text(panelData.title);

    // Create panel body with list
    var panelBody = $("<div></div>").addClass("panel-body");
    var bulletList = $("<ul></ul>").addClass("no_bullets");

    // Add list items for each release note item
    panelData.items.forEach(function (item) {
        var listItem = createReleaseNoteListItem(item);
        bulletList.append(listItem);
    });

    panelBody.append(bulletList);

    // Append panel heading and body to panel element
    panelElement.append(panelHeading);
    panelElement.append(panelBody);

    return panelElement;
}

// Function to display showcase image
function displayShowcaseImage() {
    var showcaseImageDiv = document.getElementById('showcase_image');
    
    if (IsAuthoring) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/RE4-Laptop-Mockup.png" alt="Requirements Editor in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    } else if (IsDGS) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/PnP-Laptop-Mockup.png" alt="PnP in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    }
    else if (IsEngine) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/RE4-Laptop-Mockup.png" alt="Requirements Editor in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    }
    else if (IsI32) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/FormsDesign-Laptop-Mockup.png" alt="Forms Design in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    }
    else if (IsWKES) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/E-Sign-Laptop-Mockup.png" alt="DGS in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    }
    else if (IsWKHosted) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/PnP-Laptop-Mockup.png" alt="PnP in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    }
    else if (IsWKIS) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/RE4-Laptop-Mockup.png" alt="Requirements Editor in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    }
    else if (IsOneSumX) {
        if (display_showcase_image === "true") {
            showcaseImageDiv.innerHTML = '<img class="img-fluid img-rounded" src="/resources/landingpages/images/OSX-Laptop-Mockup.png" alt="DGS in laptop">';
        } else {
            showcaseImageDiv.remove();
        }
    }
}

// Function to populate Getting Started dynamically
function populateGettingStarted() {
    var gettingStartedList = $("#gettingStartedList");
    var gettingStartedSection = $("#gettingStartedSection");

    gettingStarted.forEach(function (item) {
        if (item.title.trim() !== "" && item.link.trim() !== "") {
            var listItem = $("<li></li>");
            var link = $("<a></a>").attr("href", item.link).attr("target", "_blank").text(item.title);
            listItem.append(link);
            // If the 'info' attribute is not blank, add an icon with tooltip
            if (item.info && item.info.trim() !== "") {
                var infoIcon = $("<span></span>")
                    .addClass("bi bi-info-circle custom-tooltip") // Add custom-tooltip class
                    .css("margin-left", "5px")
                    .attr("data-bs-toggle", "tooltip")
                    .attr("data-bs-placement", "top")
                    .attr("aria-label", item.info); // Set tooltip text using aria-label attribute
                listItem.append(infoIcon);
            }

            gettingStartedList.append(listItem);
        }
    });

    // Hide the section if there are no valid items
    if (gettingStartedList.children("li").length === 0) {
        gettingStartedSection.remove();
    }
}

// Function to populate User Guides dynamically
function populateInstallationGuides() {
    var installationGuidesList = $("#installationGuidesList");
    var installationGuidesSection = $("#installationGuidesSection");

    // Check if there are items in installationGuides
    if (installationGuides.length > 0) {
        installationGuidesSection.show(); // Show the section if there are items

        installationGuides.forEach(function (item) {
            var listItem = $("<li></li>");
            var link = $("<a></a>").attr("href", item.link).attr("target", "_blank").text(item.title);
            listItem.append(link);
            // If the 'info' attribute is not blank, add an icon with tooltip
            if (item.info && item.info.trim() !== "") {
                var infoIcon = $("<span></span>")
                    .addClass("bi bi-info-circle custom-tooltip") // Add custom-tooltip class
                    .css("margin-left", "5px")
                    .attr("data-bs-toggle", "tooltip")
                    .attr("data-bs-placement", "top")
                    .attr("aria-label", item.info); // Set tooltip text using aria-label attribute
                listItem.append(infoIcon);
            }

            installationGuidesList.append(listItem);
        });
    } else {
        installationGuidesSection.remove(); // Hide the section if there are no items
    }
}

// Function to populate User Guides dynamically
function populateImplementationGuides() {
    var implementationGuidesList = $("#implementationGuidesList");
    var implementationGuidesSection = $("#implementationGuidesSection");

    // Check if there are items in implementationGuides
    if (implementationGuides.length > 0) {
        implementationGuidesSection.show(); // Show the section if there are items

        implementationGuides.forEach(function (item) {
            var listItem = $("<li></li>");
            var link = $("<a></a>").attr("href", item.link).attr("target", "_blank").text(item.title);
            listItem.append(link);
            // If the 'info' attribute is not blank, add an icon with tooltip
            if (item.info && item.info.trim() !== "") {
                var infoIcon = $("<span></span>")
                    .addClass("bi bi-info-circle custom-tooltip") // Add custom-tooltip class
                    .css("margin-left", "5px")
                    .attr("data-bs-toggle", "tooltip")
                    .attr("data-bs-placement", "top")
                    .attr("aria-label", item.info); // Set tooltip text using aria-label attribute
                listItem.append(infoIcon);
            }

            implementationGuidesList.append(listItem);
        });
    } else {
        implementationGuidesSection.remove(); // Hide the section if there are no items
    }
}

// Function to populate User Guides dynamically
function populateUserGuides() {
    var userGuidesList = $("#userGuidesList");
    var userGuidesSection = $("#userGuidesSection");

    // Check if there are items in userGuides
    if (userGuides.length > 0) {
        userGuidesSection.show(); // Show the section if there are items

        userGuides.forEach(function (item) {
            var listItem = $("<li></li>");
            var link = $("<a></a>").attr("href", item.link).attr("target", "_blank").text(item.title);
            listItem.append(link);
            // If the 'info' attribute is not blank, add an icon with tooltip
            if (item.info && item.info.trim() !== "") {
                var infoIcon = $("<span></span>")
                    .addClass("bi bi-info-circle custom-tooltip") // Add custom-tooltip class
                    .css("margin-left", "5px")
                    .attr("data-bs-toggle", "tooltip")
                    .attr("data-bs-placement", "top")
                    .attr("aria-label", item.info); // Set tooltip text using aria-label attribute
                listItem.append(infoIcon);
            }

            userGuidesList.append(listItem);
        });
    } else {
        userGuidesSection.remove(); // Hide the section if there are no items
    }
}

// Function to populate Install and Upgrade Guides dynamically
function populateInstallUpgradeGuides() {
    var installUpgradeGuidesList = $("#installUpgradeGuidesList");
    var installUpgradeGuidesSection = $("#installUpgradeGuidesSection");

    // Check if there are items in userGuides
    if (installUpgradeGuides.length > 0) {
        installUpgradeGuidesSection.show(); // Show the section if there are items

        installUpgradeGuides.forEach(function (item) {
            var listItem = $("<li></li>");
            var link = $("<a></a>").attr("href", item.link).attr("target", "_blank").text(item.title);
            listItem.append(link);
            // If the 'info' attribute is not blank, add an icon with tooltip
            if (item.info && item.info.trim() !== "") {
                var infoIcon = $("<span></span>")
                    .addClass("bi bi-info-circle custom-tooltip") // Add custom-tooltip class
                    .css("margin-left", "5px")
                    .attr("data-bs-toggle", "tooltip")
                    .attr("data-bs-placement", "top")
                    .attr("aria-label", item.info); // Set tooltip text using aria-label attribute
                listItem.append(infoIcon);
            }

            installUpgradeGuidesList.append(listItem);
        });
    } else {
        installUpgradeGuidesSection.remove(); // Hide the section if there are no items
    }
}

// Function to populate OD-Related Install Guides dynamically
function populateODRelatedInstallGuides() {
    var odRelatedInstallGuidesList = $("#odRelatedInstallGuidesList");
    var odRelatedInstallGuidesSection = $("#odRelatedInstallGuidesSection");

    // Check if there are items in userGuides
    if (odRelatedInstallGuides.length > 0) {
        odRelatedInstallGuidesSection.show(); // Show the section if there are items

        odRelatedInstallGuides.forEach(function (item) {
            var listItem = $("<li></li>");
            var link = $("<a></a>").attr("href", item.link).attr("target", "_blank").text(item.title);
            listItem.append(link);
            // If the 'info' attribute is not blank, add an icon with tooltip
            if (item.info && item.info.trim() !== "") {
                var infoIcon = $("<span></span>")
                    .addClass("bi bi-info-circle custom-tooltip") // Add custom-tooltip class
                    .css("margin-left", "5px")
                    .attr("data-bs-toggle", "tooltip")
                    .attr("data-bs-placement", "top")
                    .attr("aria-label", item.info); // Set tooltip text using aria-label attribute
                listItem.append(infoIcon);
            }

            odRelatedInstallGuidesList.append(listItem);
        });
    } else {
        odRelatedInstallGuidesSection.remove(); // Hide the section if there are no items
    }
}

// Function to populate Feature Guides dynamically
function populateFeatureGuides() {
    var featureGuidesList = $("#featureGuidesList");
    var featureGuidesSection = $("#featureGuidesSection");

    featureGuides.forEach(function (item) {
        var listItem = $("<li></li>");
        var link = $("<a></a>").attr("href", item.link).text(item.title);
        listItem.append(link);
        // If the 'info' attribute is not blank, add an icon with tooltip
        if (item.info && item.info.trim() !== "") {
            var infoIcon = $("<span></span>")
                .addClass("bi bi-info-circle custom-tooltip") // Add custom-tooltip class
                .css("margin-left", "5px")
                .attr("data-bs-toggle", "tooltip")
                .attr("data-bs-placement", "top")
                .attr("aria-label", item.info); // Set tooltip text using aria-label attribute
            listItem.append(infoIcon);
        }

        featureGuidesList.append(listItem);
    });

    // Check if there are items in Feature Guides
    if (featureGuidesList.children().length === 0) {
        featureGuidesSection.remove(); // Hide the entire section if no items
    }
}

// Function to populate Related Documents dynamically
function populateRelatedDocuments() {
    var relatedDocumentsList = $("#relatedDocumentsList");
    var relatedDocumentsSection = $("#relatedDocumentsSection");

    relatedDocuments.forEach(function (item) {
        var listItem = $("<li></li>");
        var link = $("<a></a>").attr("href", item.link).text(item.title);
        listItem.append(link);
        relatedDocumentsList.append(listItem);
    });

    // Check if there are items in Related Documents
    if (relatedDocumentsList.children().length === 0) {
        relatedDocumentsSection.remove(); // Hide the entire section if no items
    }
}

// Function to populate Landing Pages dynamically
function populateLandingPages() {
    var landingPagesList = $("#landingPagesList");
    var landingPagesSection = $("#landingPagesSection");

    landingPages.forEach(function (item) {
        var listItem = $("<li></li>");
        var link = $("<a></a>").attr("href", item.link).attr("target", item.target || "_self").text(item.title);
        listItem.append(link);
        // Add bulleted list
        if (item.bullets && item.bullets.length > 0) {
            var bulletList = $("<ul></ul>");
            item.bullets.forEach(function(bullet) {
                bulletList.append("<li>" + bullet + "</li>");
            });
            listItem.append(bulletList);
        }
        landingPagesList.append(listItem);
    });

    // Check if there are items in Related Documents
    if (landingPagesList.children().length === 0) {
        landingPagesSection.remove(); // Hide the entire section if no items
    }
}

// Function to populate Release Calendars dynamically
function populateReleaseCalendars() {
    var releaseCalendarList = $("#releaseCalendarList");
    var releaseCalendarSection = $("#releaseCalendarSection");

    releaseCalendars.forEach(function (item) {
        var listItem = $("<li></li>");
        var link = $("<a></a>").attr("href", item.link).text(item.title);
        listItem.append(link);
        releaseCalendarList.append(listItem);
    });

    // Check if there are items in Release Calendars
    if (releaseCalendarList.children().length === 0) {
        releaseCalendarSection.remove(); // Hide the entire section if no items
    }
}

// Function to populate the Panels dynamically
function populatePanels() {
    
    // Assuming announcementContents, cardContents, and releaseNotesCard are arrays with panel data

    // Function to check if mainContent is empty
    function isMainContentEmpty(panelData) {
        return !panelData.mainContent.trim();
    }

    // Check if releaseNotesCard array is not empty
    if (releaseNotesCard && releaseNotesCard.length > 0) {
        var hasItems = false;
        releaseNotesCard.forEach(function (panelData) {
            if (panelData.items && panelData.items.length > 0) {
                hasItems = true;
                var panelElement = createPanelElement(panelData);

                // Iterate through release note items to check for 'info' attribute
                panelElement.find("ul.no_bullets").children("li").each(function(index, listItem) {
                    var item = panelData.items[index];
                    if (item && item.info && item.info.trim() !== "") {
                        
                        var infoIcon = $("<span></span>").addClass("bi bi-info-circle custom-tooltip").css("margin-left", "5px").attr("data-bs-toggle", "tooltip").attr("data-bs-placement", "top").attr("aria-label", item.info); // Use aria-label attribute
                        $(listItem).append(infoIcon);
                    }
                });

                // Prepend the panel to the content row
                $("#messageCards").prepend(panelElement);
            }
        });
        if (!hasItems) {
            console.log("No release notes available.");
        }
    } else {
        console.log("No release notes available.");
    }

    // Check if announcementContents array is not empty
    if (announcementContents.length > 0) {
        announcementContents.forEach(function (panelData) {
            // Check if mainContent is empty
            if (isMainContentEmpty(panelData)) {
                // If mainContent is empty, update it with a message
                panelData.mainContent = "There are no announcements at this time.";
            }
            var panelElement = createPanelElement(panelData);
            // Append the panel to the content row
            $("#messageCards").append(panelElement);
        });
    }

    // Check if cardContents array is not empty
    if (cardContents.length > 0) {
        cardContents.forEach(function (panelData) {
            var panelElement = createPanelElement(panelData);
            // Append the panel to the content row
            $("#messageCards").append(panelElement);
        });
    }
    
    // Enable Bootstrap tooltips globally
    $('[data-bs-toggle="tooltip"]').tooltip();
}

function createPanelElement(panelData) {
    // Check if panelData is undefined or null
    if (!panelData) {
        console.error("Panel data is undefined or null");
        return null;
    }

    // Create panel element with a custom class
    var panelElement = $("<div></div>").addClass("panel panel-primary");

    // Check if panelData is defined and has the 'type' property
    if (panelData && panelData.type) {
        // Set border color based on panel type (announcement or others)
        if (panelData.type === "announcement") {
            panelElement.css("border-color", "#85bc20");
        }
    }

    // Create panel heading
    var panelHeading = $("<div></div>").addClass("panel-heading");

    // Prepend Bootstrap icon based on title conditions
    var titleIcon;
    if (panelData && panelData.title) {
        if (panelData.title.toLowerCase().includes("announcement")) {
            titleIcon = "megaphone";
        } else if (panelData.title.toLowerCase().includes("contact")) {
            titleIcon = "telephone";
        } else if (panelData.title.toLowerCase().includes("release note")) {
            titleIcon = "card-list";
        } else {
            titleIcon = "envelope";
        }
        var iconElement = $("<span></span>").addClass("bi").addClass("bi-" + titleIcon);
        panelHeading.append(iconElement);
        panelHeading.append(" " + panelData.title);
    }

    // Check if panelData is defined and has the 'type' property
    if (panelData && panelData.type) {
        // Set background color based on panel type (announcement or others)
        if (panelData.type === "announcement") {
            panelHeading.css("background-color", "#85bc20");
            panelElement.addClass("announcementCard");
        } else if (panelData.type === "release note") {
            panelHeading.css("background-color", "#337ab7");
            panelElement.addClass("releaseNotesCard");
        } else {
            panelHeading.css("background-color", "#337ab7");
            panelElement.addClass("messageCard");
        }
        panelHeading.css("color", "#ffffff");
    }

    var panelBody = $("<div></div>").addClass("panel-body");

    // Append main content if available
    if (panelData && panelData.mainContent) {
        panelBody.html("<p>" + panelData.mainContent + "</p>");
    }

    // Append items or bullet points if available
    if (panelData && panelData.items && panelData.items.length > 0) {
        var itemList = $("<ul></ul>").addClass("no_bullets");
        panelData.items.forEach(function (item) {
            var listItem = $("<li></li>");
            var link = $("<a></a>").attr("href", item.link).attr("target", "_blank").text(item.title);
            listItem.append(link);
            itemList.append(listItem);
        });
        panelBody.append(itemList);
    } else if (panelData && panelData.bulletPoints && panelData.bulletPoints.length > 0) {
        var bulletList = $("<ul></ul>").addClass("no_bullets");
        panelData.bulletPoints.forEach(function (item) {
            var listItem = $("<li></li>").html(item);
            bulletList.append(listItem);
        });
        panelBody.append(bulletList);
    }

    // Append panel heading and body to panel element
    panelElement.append(panelHeading);
    panelElement.append(panelBody);

    return panelElement;
}

// Define a function to create and show the tooltip
function createTooltip(iconElement, tooltipText) {
    var tooltip = $("<div></div>")
        .addClass("custom-tooltip")
        .text(tooltipText)
        .appendTo("body");

    // Position the tooltip relative to the icon
    var iconPosition = $(iconElement).offset();
    tooltip.css({
        top: iconPosition.top + $(iconElement).outerHeight() + 5, // Adjusting the top position
        left: iconPosition.left
    });

    // Show the tooltip on icon hover
    $(iconElement).on("mouseenter", function() {
        tooltip.show();
    }).on("mouseleave", function() {
        tooltip.hide();
    });
}

// Function to initialize tooltips for release notes items
function initializeTooltips() {
    $(".release-note-item").each(function() {
        var iconElement = $(this).find(".bi-info-circle");
        var tooltipText = $(this).data("info");
        createTooltip(iconElement, tooltipText);
    });
}

// Override the createPopper function with your custom implementation
window.createPopper = initializeTooltips;







//#region FTS Functions
// Function to show or hide the search form
function showHideSearch() {
    // Check the value of showSearch variable
    if (showSearch.toLowerCase() === "true") {
        // Show the search form
        $('#searchForm').show();
    } else {
        // Hide the search form
        $('#searchForm').remove();
    }
}



//#endregion






// Document ready function
$(document).ready(function () {
    // Set document title
    document.title = myProduct + " Documentation";

    // Populate product name
    $(".productname").text(myProduct);

    // Populate product Summary
    $(".productSummary").html(productSummary);

    // Set documentation feedback URL
    $("#product_docfdbkurl").attr("href", DocFeedbackUrl);

    // Include HTML
    includeHTML();
    
    // Trigger showHideSearch function
    showHideSearch();

    // Trigger displayShowcaseImage function
    displayShowcaseImage();

    //#region Trigger population of sections
    populateGettingStarted();

    populateInstallationGuides();

    populateInstallUpgradeGuides();

    populateImplementationGuides();

    // Trigger population of Release Notes Archives
    // populateReleaseNotesArchives();

    // Trigger population of User Guides
    populateUserGuides();

    populateODRelatedInstallGuides();

    populateFeatureGuides();

    populateRelatedDocuments();

    populateReleaseCalendars();

    populateLandingPages();

    populatePanels();
    //#endregion

    // Trigger population of the Panels
    createPanelElement(announcementContents[1]);  // Change index based on your data structure
    createPanelElement(cardContents[1]);  // Change index based on your data structure

    // Trigger announcement logic
    // announcementTime();

    // Call initializeTooltips()
    initializeTooltips();
});
// #endregion