// ========== dynamic-profiling.js
// This code provides the functionality for webhelp that relies on InfoDev's Dynamic Profiling.

//#region TODO: 
// - Replace method of comparing versions with versionCompare function at:
//    https://gist.github.com/TheDistantSea/8021359
//      0 if the versions are equal
//      a negative integer iff v1 < v2
//      a positive integer iff v1 > v2
//      NaN if either version string is in the wrong format
//#endregion


$(document).ready(function() {
    var currentPageName = getBaseName(window.location.href) + ".html";
    const var_searchquery = getURLParameter('searchQuery');

    //#region Create storage items

    // Helper function to handle session storage
    function handleSessionStorage(key) {
        if (!(sessionStorage.getItem(key))) {  // storage item doesn't exist
            const value = getURLParameter(key);
            sessionStorage.setItem(key, value);
        } else {  // storage item exists
            // If a url variable exists we need to take that value as priority
            const storedValue = sessionStorage.getItem(key);
            const urlValue = getURLParameter(key);
            if (urlValue && urlValue.length > 5 && storedValue !== urlValue) {
                sessionStorage.setItem(key, urlValue);
            }
        }
    }

    // Create storage items for audience, product, and revision
    ['audience', 'product', 'revision'].forEach(handleSessionStorage);

    //#endregion Create cookies

    // #region MAIN
    if (
        Variables.IsChangelog || 
        Variables.IsAuthoring ||
        Variables.IsDGS ||
        Variables.IsDocViewer ||
        Variables.IsEZConfig ||
        Variables.IsOPPSA ||
        Variables.IsOAuth ||
        Variables.IsReqEdUG ||
        Variables.IsSearchPage ||
        Variables.IsWKHostedChangelog
    ) {
        HideDataElements();
        ShowHideProducts();
        RemoveNonMatchingAudienceElements();
        RemoveNonMatchingProductElements();
        MakeTablesInline();
        ShowValidRevItems();
        // RemoveEmptyTocAccordians();
        RemoveNonDisplayedSections();
        HideTopicToc();
        DoesContentMatch();    
    }
    // #endregion

    function DoesContentMatch() {
        // console.log(thisAud + ": " + thisProd + ": " + thisRev);
        if (!(Variables.IsWKES) &&
            !sessionStorage.getItem('revision') && 
            !sessionStorage.getItem('product') && 
            !sessionStorage.getItem('audience')
        ) {
            // Modify the article content if no items match the ver variable
            let RevCount = 0;
            $('[data-rev]').each(function () {
                RevCount++;
            });
            if (RevCount === 0) {
                if (Variables.IsChangelog) {
                    const msg = "<p class='nocontent'>No content on this page matches the version of your application.<br/>" +
                        "Your application version: <b>" + sessionStorage.getItem('revision') + "</b></p>" + 
                        "<p>Consider accessing this page through the Documentation Page link at the top right of this page.</p>";
                    $('article').html('');
                    $('article').append(msg);
                    $('.landing-page-arrow').css('display', 'block');
                }
            }
        }
    }

    function getBaseName(url) {
        if (!url || (url && url.length === 0)) {
            return "";
        }
        var index = url.lastIndexOf("/") + 1;
        var filenameWithExtension = url.substr(index);
        var basename = filenameWithExtension.split(/[.?&#]+/)[0];

        // Handle '/mypage/' type paths
        if (basename.length === 0) {
            url = url.substr(0, index - 1);
            basename = getBaseName(url);
        }
        return basename ? basename : "";
    }

    function getURLParameter(name) {
        return decodeURI(
            (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
        );
    }

    function HideDataElements() {
        $('[data-audience]').css('display', 'none');
        // $('[data-rev]').css('display', 'none');
        $('[data-product]').css('display', 'none');
    }

    function HideTopicToc() {
        $('#wh_topic_toc').css('display', 'none');
        // make topic body wider
        // $('#wh_topic_body').css('width', '100%');
        $('#wh_topic_content').css('margin-left', '40px');
        $('#wh_topic_content').css('margin-right', '40px');
    }

    function isObjectEmpty(obj) {
        for (var name in obj) {
            return false;
        }
        return true;
    }

    function MakeTablesInline() {
        // Make all tables inline-tables
        $('*').each(function () {
            // var curAud = ($(this).data('audience'));
            if ($(this).is('table')) {
                $(this).css('display', 'inline-table');
            }
        });
    }

    function PrependSearchStatement() {
        var Disclaimer = "<b>IMPORTANT:</b> Your search contains the items found on this search page.<br/>";
        Disclaimer += "Due to content profiling, selecting an item below may result in no items displayed regardless of these search results."
        $("<div class='DPDisclaimer'><p>" + Disclaimer + "</p></div>").insertBefore('#results');
    }

    function RemoveAllHrefVariables() {
        // remove all href variables if the href contains the page name
        $('a').each(function () {
            if ($(this).parents('#wh_publication_toc')) {
                // Do nothing. This ensures that left nav links still contain the url variables.
            } else {
                var currentHref = $(this).attr('href');
                if (currentHref.indexOf(currentPageName) == -1) {
                    // does NOT contain page name INCLUDING EXTENSION
                } else {
                    var variablesToRemove = "?audience=" + sessionStorage.getItem('audience') + "&rev=" + sessionStorage.getItem('revision');
                    var newHref = currentHref.replace(variablesToRemove, '');
                    $(this).attr('href', newHref);
                }
            }
        });
    }

    function RemoveEmptyTocAccordians() {
        $(".wh_main_page_toc_accordion_header").find("span:empty").closest('.wh_main_page_toc_accordion_header').remove();
        $("a[style$='display: none;']").closest('.wh_main_page_toc_accordion_header').remove();
    }

    function RemoveNonDisplayedDivs() {
        $('div').each(function () {
            if ($(this).css('display') == 'none') {
                $(this).remove();
            }
        });
    }

    function RemoveNonDisplayedSections() {
        $('section').each(function () {
            if ($(this).css('display') == 'none') {
                $(this).remove();
            }
        });
    }

    function RemoveNonMatchingAudienceElements() {
        var var_audience = sessionStorage.getItem('audience');
        switch (var_audience) {
            // When adding a new audience variable, be sure to include the variable in the dynamic profiling ditaval.
            case "installed":
                $('[data-audience=hosted]').remove();
                $('[data-audience=installed]').css('display', 'inline');
                $('[data-audience=integrator]').remove();
                break;
            case "hosted":
                $('[data-audience=hosted]').css('display', 'inline');
                $('[data-audience=installed]').remove();
                $('[data-audience=integrator]').css('display', 'inline');
                break;
            case "integrator":
                $('[data-audience=hosted]').remove();
                $('[data-audience=installed]').css('display', 'inline');
                $('[data-audience=integrator]').css('display', 'inline');
                break;
        }
    }

    function RemoveNonMatchingProductElements() {
        var var_product = sessionStorage.getItem('product');

        $('*').each(function () {
            var curProd = ($(this).data('product'));

            if (curProd != undefined && curProd != null) {
                console.log("curProd: " + curProd);
                if (curProd === var_product) {
                    $(this).css('display', 'inline');
                } else {
                    $(this).hide();
                }
            }
        });
    }

    function ShowHideProducts() {
        $('*').each(function () {
            var dataProdVal = ($(this).attr('data-product'));
            if (dataProdVal != null && dataProdVal === var_product) {
                if (($(this).hasClass("ph")) || ($(this).hasClass("topicref"))) {
                    $(this).css('display', 'inline');
                    var id = $(this).attr("id");
                    if (id) {
                        console.log("ShowHideProducts: " + id + ", display:inline");
                    }
                } else {
                    $(this).css('display', 'block');
                }
            }
        });
    }

    function ShowValidRevItems() {
        var var_rev = sessionStorage.getItem('revision');
        $('*').each(function () {
            var curRev = ($(this).data('rev'));
            if (curRev) {
                var EqualRevs = versionCompare(var_rev, curRev, true);
                if (EqualRevs > -1) {
                    if ($(this).is('section') || $(this).is('p')) {
                        $(this).css('display', 'block');
                    } else if ($(this).is('li')) {
                        $(this).css('display', 'list-item');
                    } else if ($(this).is('tr')) {
                        $(this).css('display', 'table-row');
                    } else {
                        $(this).css('display', 'inline-block');
                    }
                }
            }
        });
    }

    function versionCompare(v1, v2, options) {
        var lexicographical = options && options.lexicographical,
            zeroExtend = options && options.zeroExtend,
            v1parts = v1.split('.'),
            v2parts = v2.split('.');

        function isValidPart(x) {
            return (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/).test(x);
        }

        if (!v1parts.every(isValidPart) || !v2parts.every(isValidPart)) {
            return NaN;
        }

        if (zeroExtend) {
            while (v1parts.length < v2parts.length) v1parts.push("0");
            while (v2parts.length < v1parts.length) v2parts.push("0");
        }

        if (!lexicographical) {
            v1parts = v1parts.map(Number);
            v2parts = v2parts.map(Number);
        }

        for (var i = 0; i < v1parts.length; ++i) {
            if (v2parts.length == i) {
                return 1;
            }

            if (v1parts[i] === v2parts[i]) {
                continue;
            } else if (v1parts[i] > v2parts[i]) {
                return 1;
            } else {
                return -1;
            }
        }

        if (v1parts.length != v2parts.length) {
            return -1;
        }

        return 0;
    }
});