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

// #region Define variables
var IsAudRev = window.location.href.indexOf("AudRevTest") != -1;
var IsAuthRN = window.location.href.indexOf("Authoring/ReleaseNotes") != -1;
var IsChangelog = window.location.href.indexOf("_changelog.html") != -1;
var IsDDTest = window.location.href.indexOf("Test/DefaultData") != -1;
var IsDVChangelog = window.location.href.indexOf("topics/exp_DDV_changelog.html") > 1;
var IsDGS = window.location.href.indexOf("DGS/Change-Log") != -1;
var IsDocumentPortal = window.location.href.indexOf("DocumentPortal/UserGuide") != -1;
var IsEZConfig = window.location.href.indexOf("ExpereEZConfig") != -1;
var IsEZConfigTest = window.location.href.indexOf("EZConfigTest") != -1;
var IsOAuth = window.location.href.indexOf("OAuth") != -1;
var IsOPPSA = window.location.href.indexOf("OPPSA") != -1;
var IsReqEdUG = window.location.href.indexOf("Authoring/RequirementsEditor") != -1;
var IsSearchPage = window.location.href.indexOf("/search.html?searchQuery") != -1;
var IsWKHostedChangelog = window.location.href.indexOf("WK-Hosted-Expere/Change-Log") != -1;
var IsWKHostedTest = window.location.href.indexOf("WK Hosted Expere ChangeLog") != -1;
var IsDocViewer = window.location.href.indexOf("DocViewer") != -1;
var IsDocMgmt = window.location.href.indexOf("\Expere\eOriginal\DocumentMgmt-IntGuide") != -1;

var IsSearchPage    = window.location.href.indexOf("/search.html") != -1;

// Landing pages
var IsAuthoringLP = window.location.href.indexOf("Authoring/index.html") != -1;


var currentPageName = getBaseName(window.location.href) + ".html";
var var_searchquery = getURLParameter('searchQuery');
var var_audience = getURLParameter('audience');
var var_rev = getURLParameter('rev');
var var_prod = getURLParameter('prod');
// #endregion

// #region MAIN
if (!(IsSearchPage)){
    document.cookie = "search_reloaded=no";
}

if (!(IsDVChangelog)) {
    if (IsAudRev ||
        IsAuthoringLP ||
        IsAuthRN ||
        IsDDTest ||
        IsDGS ||
        IsDocumentPortal ||
        IsDocViewer ||
        IsEZConfig ||
        IsEZConfigTest ||
        IsOPPSA ||
        IsOAuth ||
        IsReqEdUG ||
        IsSearchPage ||
        IsWKHostedChangelog ||
        IsWKHostedTest
    ) {
        // #region COOKIES
        // NOTE - THIS REGION IS FOR FUTURE USE FOR POTENTIALLY PERSISTING VARIABLES IN SEARCH PAGES
        // Place variables in cookie
        if(!(IsSearchPage)){
            var url = document.URL;
            var vars = "&" + url.substring(url.indexOf('?') + 1);
            document.cookie = "vars=" + vars + "; path=/";
            var AudienceCookieExists = document.cookie.match(/^(.*;)?\s*audience\s*=\s*[^;]+(.*)?$/);
            if (!(AudienceCookieExists)) { console.log("AudienceCookieExists");}
            document.cookie = "audience=" + var_audience + "; path=/";
            document.cookie = "product=" + var_prod + "; path=/";
            document.cookie = "revision=" + var_rev + "; path=/";
            // The following lines can be uncommented to remove the cookies after they load.
            // document.cookie = "audience=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
            // document.cookie = "product=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
            // document.cookie = "revision=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
        }
        

        // verify cookie
        let x = getCookie("vars");

        // #endregion

        // UpdateRevInUrl();

        CheckCookie();

        ModifySearchPageURL();

        HideDataElements();

        ModifyLinks();

        ShowHideProducts();

        RemoveNonMatchingAudienceElements();

        MakeTablesInline();

        ShowValidRevItems();

        RemoveEmptyTocAccordians();

        RemoveNonDisplayedSections();

        RemoveAllHrefVariables();

        HideTopicToc();

        DoesContentMatch();
    }
}
// #endregion


function CheckCookie() {
    audience = getCookie("audience");
    product = getCookie("product");
    revision = getCookie("revision");
    // if (audience != "") {
        console.log(audience);
    // }
    // if (product != "") {
        console.log(product);
    // }
    // if (revision != "") {
        console.log(revision);
    // }
}

function DoesContentMatch() {
    //Modify the article content if no items match the ver variable
    var RevCount = 0;
    $('[data-rev]').each(function () {
        RevCount = RevCount + 1;
    });
    if (RevCount == 0) {
        if (IsChangelog) {
            var msg = "<p>No content on this page matches the version of your application.<br/>" +
                "Your application version: " + var_rev + "</p>";
            $('article').html('');
            $('article').append(msg);
        }

    }
}

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 getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

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

function ModifyLinks() {
    $('a').each(function () {
        var oHref = $(this).attr('href');
        var HrefSplit = oHref.split('/'); //Split the href text into sections split by forward slash
        var HrefDomain = HrefSplit[2]; //Get the 2nd instance of the sections

        var tHref = oHref;
        var searchquery = var_searchquery;
        var audience = getCookie("audience");;
        var rev  = getCookie("revision");;
        var prod  = getCookie("product");;
        var AudVarForCombo;
        var RevVarForCombo;
        var ProdVarForCombo;
        var SearchQueryVarForCombo;
        var VariableCombo;
        // console.log(searchquery + "/" + audience + "/" + rev + "/" + prod);

        //#region Combo Values
        if (audience.length == 0 || audience === null || audience === "null" || audience === "") {
            AudVarForCombo = 2
        } else {
            AudVarForCombo = 11
        }
        if (revision.length == 0 || rev === null || rev === "null" || rev === "") {
            RevVarForCombo = 23
        } else {
            RevVarForCombo = 31
        }
        if (product.length == 0 || product === null || product === "null" || product === "") {
            ProdVarForCombo = 41
        } else {
            ProdVarForCombo = 53
        }
        if (searchquery.length == 0 || searchquery === null || searchquery === "null") {
            SearchQueryVarForCombo = 61
        } else {
            SearchQueryVarForCombo = 71
        }
        //#endregion

        VariableCombo = AudVarForCombo + RevVarForCombo + ProdVarForCombo + SearchQueryVarForCombo;
        console.log("VariableCombo = " + VariableCombo);
        // https://dev-documentation.wolterskluwerfs.com/Expere/Authoring/ReleaseNotes/webhelp/search.html?searchQuery=defect&audience=hosted&prod=DocGenServices&rev=22.2.0
        switch (VariableCombo) {
            case 127: //aud IS null, rev IS null, prod IS null, searchquery IS null
                // No variables, so add nothing
                break;
            case 135: //aud IS null, rev IS NOT null, prod IS null, searchquery IS null
                var tHref = oHref + "?rev=" + rev;
                break;
            case 136: //aud IS NOT null, rev IS null, prod IS null, searchquery IS null
                var tHref = oHref + "?audience=" + audience;
                break;
            case 137: //aud IS null, rev IS null, prod IS null, searchquery IS NOT null
                var tHref = oHref + "?searchQuery=" + searchquery;
                break;
            case 139: //aud IS null, rev IS null, prod IS NOT null, searchquery IS null
                var tHref = oHref + "?prod=" + prod;
                break;
            case 144: //aud IS NOT null, rev IS NOT null, prod IS null, searchquery IS null
                var tHref = oHref + "?audience=" + audience + "&rev=" + rev;
                break;
            case 145: //aud IS null, rev IS NOT null, prod IS null, searchquery IS NOT null
                var tHref = oHref + "?searchQuery=" + searchquery + "&rev=" + rev;
                break;
            case 146: //aud IS NOT null, rev IS null, prod IS null, searchquery IS NOT null
                var tHref = oHref + "?searchQuery=" + searchquery + "&audience=" + audience + "&rev=" + rev;
                break;
            case 147: //aud IS null, rev IS NOT null, prod IS NOT null, searchquery IS null
                var tHref = oHref + "?rev=" + rev + "&prod=" + prod;
                break;
            case 148: //aud IS NOT null, rev IS null, prod IS NOT null, searchquery IS null
                var tHref = oHref + "?audience=" + audience + "&prod=" + prod;
                break;
            case 149: //aud IS null, rev IS null, prod IS NOT null, searchquery IS NOT null
                var tHref = oHref + "?searchQuery=" + searchquery + "&prod=" + product;
                break;
            case 156: //aud IS NOT null, rev IS NOT null, prod IS NOT null, searchquery IS null
                var tHref = oHref + "?audience=" + audience + "&rev=" + rev + "&prod=" + prod;
                break;
            case 166: //aud IS NOT null, rev IS NOT null, prod IS NOT null. searchquery IS NOT null
                var tHref = oHref + "?searchQuery=" + searchquery + "&audience=" + audience + "&rev=" + rev + "&prod=" + prod;
                break;
        }
        // console.log(this);
        // console.log(oHref);
        // console.log(tHref);
        $(this).attr('href', tHref);
    });
}

function ModifySearchPageURL(){
    if (IsSearchPage){
        console.log("IsSearchPage = " + IsSearchPage);

        // Has search been reloaded
        var HasSearchBeenReloaded = getCookie("search_reloaded");

        // if (HasSearchBeenReloaded == "no"){
            var audience = getCookie("audience");
            var product = getCookie("product");
            var revision = getCookie("revision");
            console.log(audience);
            console.log(product);
            console.log(revision);
            var VariablesString = "audience=" + audience + "&" + 
                "prod=" + product + "&" + 
                "rev=" + revision;
            console.log(VariablesString);
            
            //Append URL with variables
            var url = window.location.href;
            if(url.indexOf('?') > -1){
                if (!(audience.length == 0 || audience == null || audience == "null" || audience == "")){
                    url += '&audience=' + audience;    
                }
                if (!(product.length == 0 || product == null || product == "null" || product == "")){
                    url += '&prod=' + product;    
                }
                if (!(revision == "" || revision == null || revision == "null")){
                    url += '&rev=' + revision;    
                }
            }
            
            if(HasSearchBeenReloaded == "no"){
                // console.log("HasSearchBeenReloaded = " + HasSearchBeenReloaded);
                document.cookie = "search_reloaded=yes";
                window.location.href = url;
                ModifyLinks();
            }
            else{
                console.log("HasSearchBeenReloaded = " + HasSearchBeenReloaded);
                //Modify search_reloaded so that the page does not load continually
                document.cookie = "search_reloaded=no";
            }
        // }

    }
}

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=" + var_audience + "&rev=" + var_rev;
                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 RemoveNonDisplayedSections() {
    $('section').each(function () {
        if ($(this).css('display') == 'none') {
            $(this).remove();
        }
    });
}

function RemoveNonMatchingAudienceElements() {
    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 ShowHideProducts() {
    $('*').each(function () {
        var dataProdVal = ($(this).attr('data-product'));
        if (dataProdVal != null && dataProdVal == var_prod) {
            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() {
    $('*').each(function () {
        var curRev = ($(this).data('rev'));

        var var_revString = var_rev.toString();
        // console.log("var_revString = " + var_revString);
        if (!IsWKHostedChangelog) {
            var result = var_revString.substr(0, 5) + "0" + var_revString.substr(5);
        }

        if (curRev != undefined || curRev != null) {
            // ===== MODIFY var_rev IF NECESSARY =====
            //Get variables of build numbers for sorting
            var year = var_rev.substr(0, 2);
            // console.log("year = " + year);
            var relMaj = var_rev.substr((var_rev.indexOf(".") + 1), 2);
            // console.log("relMaj = " + relMaj);
            if (relMaj.includes(".")) {
                relMaj = "0" + relMaj.slice(0, -1);
                var relMin = var_rev.substr(7, 1);
                var build = var_rev.substr(9, 4);
            } else {
                var relMin = var_rev.substr((var_rev.lastIndexOf(".") + 1), 1);
                var build = var_rev.substr(10, 4);
            }
            // console.log("relMaj = " + relMaj);
            // console.log("relMin = " + relMin);

            var var_revNoDots = parseInt(var_rev.split(".").join(""));
            // console.log("var_revNoDots = " + var_revNoDots);

            // ===== MODIFY CURREV IF NECESSARY =====
            var curRevYear = curRev.substring(0, 2);
            var curRevMaj = curRev.substring((var_rev.indexOf(".") + 1), 2);
            if (curRevMaj.includes(".")) {
                curRevMaj = "0" + curRevMaj.slice(0, -1);
                var curRevMin = curRev.substr(7, 1);
                var curRevbuild = curRev.substr(9, 4);
            } else {
                var curRevMin = curRev.substr((var_rev.lastIndexOf(".") + 1), 1);
                var curRevbuild = curRev.substr(10, 4);
            }

            var curRevNoDots = parseInt(curRev.split(".").join(""));
            // console.log("curRevNoDots = " + curRevNoDots);
            // $(this).attr('rev',curRevNoDots);

            if (curRevNoDots <= var_revNoDots) {
                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');
                }
            }
        }
    });
}