// ========== 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

// #region Define variables and storage items
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');

//#region Create storage items

//#region Audience storage item
if (!(sessionStorage.getItem('audience'))) {  //storage item doesn't exist
    var var_audience = getURLParameter('audience');
    sessionStorage.setItem('audience', var_audience);
}
else{  //storage item exists
    // If a url variable exists we need to take that value as priority
    if (getURLParameter('audience').length > 5){
        //get value of storage item
        var AudCookieValue = sessionStorage.getItem('audience');

        //get value of url variable
        var UrlAud = getURLParameter('audience');

        //#region compare the two values
        //   if not equal, then remove and reset the storage item
        //#endregion
        if ((!(AudCookieValue === UrlAud)) && 
                (!(UrlAud == null))){
            sessionStorage.setItem('audience', UrlAud);
        }
        else{
            sessionStorage.setItem('audience', AudCookieValue);
        }
    }
}
//#endregion Audience storage item

//#region Product storage item
// if (!(sessionStorage.getItem('product'))) {  //storage item doesn't exist
//     var var_product = getURLParameter('prod');
//     sessionStorage.setItem('product', var_product);
// }

console.log(getURLParameter('prod').length);
    // If a url variable exists we need to take that value as priority
    if (getURLParameter('prod').length >3){
        //get value of storage item
        var ProdCookieValue = sessionStorage.getItem('product');

        //get value of url variable
        var UrlProd = getURLParameter('prod');
        console.log(UrlProd + ": " + ProdCookieValue);
        //#region compare the two values
        //   if not equal, then remove and reset the storage item
        //#endregion
        if ((!(ProdCookieValue === UrlProd)) && 
                (!(UrlProd == null))){
            sessionStorage.setItem('audience', UrlProd);
        }
        else{
            sessionStorage.setItem('product', ProdCookieValue);
        }
    }

//#endregion Product storage item

//#region Revision storage item
if (!(sessionStorage.getItem('revision'))) {  //storage item doesn't exists
    var var_rev = getURLParameter('rev');
    sessionStorage.setItem('revision', var_rev);
} 
else{ //storage item exists
    //get value of storage item
    var RevCookieValue = sessionStorage.getItem('revision');

    //get value of url variable
    var UrlRev = getURLParameter('rev');

    //#region compare the two values
    //  0 if the versions are equal
    //  a negative integer if v1 < v2
    //  a positive integer if v1 > v2
    //  NaN if either version string is in the wrong format
    //#endregion
    var CompStatus = versionCompare(RevCookieValue, UrlRev);

    //if not equal, delete the cookie and create a new one with Url value
    if (CompStatus != 0 && (!isNaN(parseInt(CompStatus)))){
        sessionStorage.setItem('revision', UrlRev);
    }
}
// #region Beau's original code
// var var_audience = getURLParameter('audience') || getCookie('audience');
// if (!var_audience) {
//     throw new Error('var_audience does not contain a value.')
// }
// document.cookie = "audience =" + var_audience;

// var var_prod = getURLParameter('prod') || getCookie('product');
// if (!var_prod) {
//     throw new Error('var_prod does not contain a value.')
// }
// document.cookie = "product =" + var_prod;

// var var_rev = getURLParameter('rev') || getCookie('revision');
// if (!var_rev) {
//     throw new Error('var_rev does not contain a value.')
// }
// document.cookie = "revision =" + var_rev;
// #endregion Beau's original code
//#endregion Revision cookie

//#endregion Create cookies


// #region MAIN
if (!(IsDVChangelog)) {
    if (IsAudRev ||
        IsAuthoringLP ||
        IsAuthRN ||
        IsDDTest ||
        IsDGS ||
        IsDocumentPortal ||
        IsDocViewer ||
        IsEZConfig ||
        IsEZConfigTest ||
        IsOPPSA ||
        IsOAuth ||
        IsReqEdUG ||
        IsSearchPage ||
        IsWKHostedChangelog ||
        IsWKHostedTest
    ) {
        // UpdateRevInUrl();

        // ModifySearchPageURL();

        HideDataElements();

        // ModifyLinks();

        ShowHideProducts();

        RemoveNonMatchingAudienceElements();

        RemoveNonMatchingProductElements();

        MakeTablesInline();

        ShowValidRevItems();

        RemoveEmptyTocAccordians();

        RemoveNonDisplayedSections();

        // RemoveAllHrefVariables();

        HideTopicToc();

        DoesContentMatch();

        if (IsSearchPage){
            PrependSearchStatement();
        }
    }
}
// #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: " + 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 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 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);
//         console.log(this);

//         // if (IsSearchPage){
//         //     console.log(IsSearchPage);
//         //     $('.searchresult').find('a').each(function () {
//         //         console.log("Found this: " + this);
//         // }
//         // )}

//     });
// }

// function ModifySearchPageURL(){
//     // TODO: Modify links based on cookies to avoid reloading

//     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"){
//                 // Reload the page to include variables in URL
//                 // console.log("HasSearchBeenReloaded = " + HasSearchBeenReloaded);

//                 //#region Unnecessary if using cookies
//                 // document.cookie = "search_reloaded=yes";
//                 // window.location.href = url;
//                 //#endregion

//                 ModifyLinks();
//             }
//             else{
//                 console.log("HasSearchBeenReloaded = " + HasSearchBeenReloaded);
//                 //Modify search_reloaded so that the page does not load continually
//                 document.cookie = "search_reloaded=no";
//             }
//         // }

//     }
// }

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');
    $(".DPDisclaimer").css({
        'display' : 'block',
        'padding' : '10px',
        'margin-left' : '40px',
        'margin-right' : '40px',
        'border-radius' : '10px',
        'font-size' : '20px',
        'background' : 'rgb(219 219 219)',
        'border' : 'solid 5px rgb(110, 187, 31)',
        'margin-bottom' : '1em'
    })
}

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() {
    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_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() {
    $('*').each(function () {
        var curRev = ($(this).data('rev'));
        var_rev = sessionStorage.getItem('revision');

        if (curRev != undefined || curRev != null) {
            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;
}
