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

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);
}
else{
    // If a url variable exists we need to take that value as priority
    if (getURLParameter('prod').length > 5){
        //get value of storage item
        var ProdCookieValue = sessionStorage.getItem('product');

        //get value of url variable
        var UrlProd = getURLParameter('prod');

        //#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 (
    IsChangelog || 
    IsAuthoring ||
    IsDGS ||
    IsDocViewer ||
    IsEZConfig ||
    IsOPPSA ||
    IsOAuth ||
    IsReqEdUG ||
    IsSearchPage ||
    IsWKHostedChangelog
    ) {

    HideDataElements();
    ShowHideProducts();
    RemoveNonMatchingAudienceElements();
    RemoveNonMatchingProductElements();
    MakeTablesInline();
    ShowValidRevItems();
    RemoveEmptyTocAccordians();
    // RemoveNonDisplayedDivs();
    RemoveNonDisplayedSections();
    HideTopicToc();
    DoesContentMatch();    
}
// #endregion


function DoesContentMatch() {
    // console.log(thisAud + ": " + thisProd + ": " + thisRev);
    if (!(IsWKES) &&
        ((sessionStorage.getItem('revision') = null) && 
            (sessionStorage.getItem('product') = null) && 
            (sessionStorage.getItem('audience') = null))
        ){
        //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 class='nocontent'>No content on this page matches the version of your application.<br/>" +
                    "Your application version: <b>" + var_rev + "</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=" + 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 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_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() {
    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;
}
