// ========== 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;
// Landing pages
var IsAuthoringLP       = window.location.href.indexOf("Authoring/index.html") != -1;


var currentPageName     = getBaseName(window.location.href) + ".html";
var audienceExists      = getURLParameter('audience');
var revExists           = getURLParameter('rev');
var prodExists          = getURLParameter('prod');
// #endregion

// #region MAIN
if (IsDVChangelog){
    //
} else{
    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
        var url = document.URL;
        var vars = "&" + url.substring(url.indexOf('?')+1);
        document.cookie = "vars=" + vars + "; path=/";
        sessionStorage.setItem('rev',revExists);
    
        // verify cookie
        let x = getCookie("vars");
    
        // #endregion
    
    
        HideDataElements();
    
        ModifyLinks();
        
        ShowHideProducts();
        
        RemoveNonMatchingAudienceElements();
    
        MakeTablesInline();
    
        ShowValidRevItems();
    
        RemoveEmptyTocAccordians();
    
        RemoveNonDisplayedSections();
    
        RemoveAllHrefVariables();
    
        HideTopicToc();
    
        DoesContentMatch();
        } 
}
// #endregion



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: " + revExists + "</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 audience = audienceExists;
        var rev = revExists;
        var prod = prodExists
        var AudVarForCombo;
        var RevVarForCombo;
        var ProdVarForCombo;
        var VariableCombo;

        if (audience === "" || audience === null || audience === undefined || audience === "null") {
            AudVarForCombo = 1
        }
        else{
            AudVarForCombo = 3
        }
        if (rev === "" || rev === null || rev === undefined || rev === "null") {
            RevVarForCombo = 5
        }
        else{
            RevVarForCombo = 8
        }
        if (prod === "" || prod === null || prod === undefined || prod === "null") {
            ProdVarForCombo = 15
        }
        else{
            ProdVarForCombo = 23
        }

        VariableCombo = AudVarForCombo + RevVarForCombo + ProdVarForCombo;
        console.log("VariableCombo = " + VariableCombo);
        switch(VariableCombo){
            case 21:  //aud IS null, rev IS null, prod IS null
            // No variables, so add nothing
            break;
            case 23:  //aud IS NOT null, rev IS null, prod IS null
            var tHref = oHref + "?audience=" + audience;
            break;
            case 24:  //aud IS null, rev IS NOT null, prod IS null
            var tHref = oHref + "?rev=" + rev;
            break;
            case 26:  //aud IS NOT null, rev IS NOT null, prod IS null
            var tHref = oHref + "?audience=" + audience + "&rev=" + rev;
            break;
            case 29:  //aud IS null, rev IS null, prod IS NOT null
            var tHref = oHref + "?prod=" + prod;
            break;
            case 31:  //aud IS NOT null, rev IS null, prod IS NOT null
            var tHref = oHref + "?audience=" + audience + "&prod=" + prod;
            break;
            case 32:  //aud IS null, rev IS NOT null, prod IS NOT null
            var tHref = oHref + "?rev=" + rev + "&prod=" + prod;
            break;
            case 34:  //aud IS NOT null, rev IS NOT null, prod IS NOT null
            var tHref = oHref + "?audience=" + audience + "&rev=" + rev + "&prod=" + prod;
            break;
            }
            
            $(this).attr('href', tHref);
        });
}

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=" + audienceExists + "&rev=" + revExists;
                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(audienceExists) {
        // 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 == prodExists){
            if (($(this).hasClass("ph")) || ($(this).hasClass("topicref"))){
                console.log("Showing " + dataProdVal);
                $(this).css('display', 'inline');
                var id = $(this).attr("id");
                if (id) {
                    console.log("ShowHideProducts: " + id + ", display:inline");
                }
            }
            else{
                console.log(dataProdVal + " does not equal " + prodExists);
                $(this).css('display', 'block');
            }   
        }
    });
}

function ShowValidRevItems(){
    $('*').each(function() {
        var curRev = ($(this).data('rev'));

        var revExistsString = revExists.toString();
        // console.log("revExistsString = " + revExistsString);
        if(!IsWKHostedChangelog){
            var result = revExistsString.substr(0,5) + "0" + revExistsString.substr(5);
        }
        
        if (curRev != undefined || curRev != null) {
            // ===== MODIFY REVEXISTS IF NECESSARY =====
            //Get variables of build numbers for sorting
            var year = revExists.substr(0,2);
            // console.log("year = " + year);
            var relMaj = revExists.substr((revExists.indexOf(".") + 1),2);
            // console.log("relMaj = " + relMaj);
            if (relMaj.includes(".")){
                relMaj = "0" + relMaj.slice(0, -1);
                var relMin = revExists.substr(7,1);
                var build = revExists.substr(9,4);
            }
            else {
                var relMin = revExists.substr((revExists.lastIndexOf(".") + 1),1);
                var build = revExists.substr(10,4);
            }
            // console.log("relMin = " + relMin);
            
            var revExistsNoDots = parseInt(revExists.split(".").join(""));
            // console.log("revExistsNoDots = " + revExistsNoDots);

            // ===== MODIFY CURREV IF NECESSARY =====
            var curRevYear = curRev.substring(0,2);
            var curRevMaj = curRev.substring((revExists.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((revExists.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 <= revExistsNoDots) {
                    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');
                    }
                }
            }
    });
}

