/* Copyright (C) 2017 Trend Micro Inc. All rights reserved. */
var globals = {
    "currentEnvironment": "dsaas",
    "isSafari": false
}

window.exports = { 
fixExamples: function () {
        var jsonBlocks = document.getElementsByClassName("prettyprinted");
        for(var i = 0; i < jsonBlocks.length; i++){
        var spanBlocks = jsonBlocks[i].children;
        for(var j = 0; j < spanBlocks.length; j++){
            var spanBlock = spanBlocks[j];
            if(spanBlock.innerText === "\"null\"" || (spanBlock.innerText === "99999" && spanBlock.className === "lit")){
            spanBlock.textContent = "null";
            spanBlock.className = "var";
            }else if(spanBlock.innerText === "\"EMPTY_STRING\""){
            spanBlock.textContent = "\"\"";
            }
        }
        }
    }
}

$(function() {
    adjustSidebarPosition();
    globals.isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)

    $(window).on('activate.bs.scrollspy', function (e) {
        var lowestLink = $('#apinav li.active>a').last();
        updateURL();

        var scrollFactor = viewPortPosition(lowestLink);

        if (scrollFactor != 0) {
            var scrollAmount = lowestLink[0].getBoundingClientRect().top - $('.sidebar').height() * 0.5;
            $('.sidebar').animate({scrollTop: ($(".sidebar").scrollTop() + scrollAmount)}, 100);
        }
    });

    $.getJSON('search_index.json', function(response){
        var index = elasticlunr.Index.load(response.index);
        var titles = response.titles;
        $('#search').on('keyup', function(){
            var query = $(this).val();
            var results = index.search(query, null);
            $('#search_results').empty();
            if (results.length > 0) {
                $('#search_results').show();
            }else {
                $('#search_results').hide();
            }
            
            for(result of results){
                if($('#' + result.ref).is(':visible')){
                    $('#search_results').append('<a class="list-group-item" href="#' + result.ref + '">' + titles[result.ref] + '</a>');
                }
            }
        });
        $('.search-item').show();
    }).fail(function() {
        var message = 'An error occurred while loading the search index. The search bar will be hidden.';
        if (window.location.protocol === 'file:') {
            message +=  "\n" + "Your browser may have disabled file access from local files.";
        }
        console.error(message);
    });

    $('body').click(function(){
        $('#search').val('');
        $('#search_results').empty();
        $('#search_results').hide();
    });

    $(window).resize(function(){
        adjustSidebarPosition();
    });

    $('#menu_navbar a').click(function() {
        if ($(window).width() < 768 ) {
            $('#menu_navbar').collapse('hide');
        }
    });
    
    $('#apinav a').click(function(){
        if ($(window).width() < 768 ) {
            $('#apinav').collapse('hide');
        }
    });

    $('#api_nav_button').click(function(){
        if ($(window).width() < 768 ) {
            $('#menu_navbar').collapse('hide');
        }
    });

    $('#menu_collapse_button').click(function(){
        if($(window).width() < 768 ){
            $('#apinav').collapse('hide');
        }
    });

    $('.toggle-environment').click(function(){
        toggleEnvironment($(this).data("value"));
    });

    $('.datatype-reference>a, .data-type>a').click(function(){
        var elemID = this.getAttribute("href");
        $(elemID).parents(".collapse").collapse("show");
        $(elemID).collapse("show");
        $('html, body').animate({
            scrollTop: $(elemID).offset().top - 50
        });
    });

    $(".clickable-row").click(function() {
        window.document.location = $(this).data("href");
    });

    processURL();
});

function toggleEnvironment(environment){
    var lowestLink = $('#apinav li.active>a').last().attr("href");
    if(lowestLink == null){
        lowestLink = "#overview";
    }

    $('.dsaas').hide();
    $('.aws').hide();
    $('.azure').hide();
    $('.onprem').hide();
    $('.' + environment).show();
    globals.currentEnvironment = environment;
    
    updateURL();

    // ensure that if elements get hidden or shown, the user stays in the current section
    $(lowestLink)[0].scrollIntoView();

    // scroll window to make scrollspy get the proper activated link
    window.setTimeout(function() {
        window.scrollBy(0, 1);
        window.scrollBy(0, -1);
    }, 1);
    
    $('.toggle-environment').removeClass("active");
    $('.toggle-environment[data-value=' + environment + ']').addClass("active");
}

function updateURL(){
    var lowestLink = $('#apinav li.active>a').last().attr("href");
    if(lowestLink == null){
        lowestLink = "#overview";
    }
    if (!globals.isSafari && history.replaceState) {
        history.replaceState(null, null, "?env=" + globals.currentEnvironment + lowestLink);
    }else {
        var currentElem = $(lowestLink);

        // remove id before setting url to prevent window from jumping to the section
        currentElem.removeAttr('id');

        location.href = location.origin + location.pathname + "?env=" + globals.currentEnvironment + lowestLink;
        
        // add the id back
        currentElem.attr('id',lowestLink.slice(1));
    }
}

function viewPortPosition (el) {
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();
    if (rect.top < $('#menu_navbar').height()) {
        return -1; // at top
    } else if (rect.bottom > (window.innerHeight || $(window).height())) {
        return 1; // at bottom
    } 

    return 0;   
}

function adjustSidebarPosition(){
    $('.sidebar').css('top', $('.navbar').height() + 'px');
}

function processURL() {
    var validEnvironments={
        "dsaas": "",
        "aws": "",
        "azure": "",
        "onprem": ""
    };
    var param = window.location.href.slice(window.location.href.indexOf('?env=') + 5, window.location.href.indexOf('#')).trim();
    var hash = location.hash;
    if(param in validEnvironments){
        toggleEnvironment(param);
    }else{
        toggleEnvironment("dsaas");
    }
    if(hash){
        $("html, body").animate({ scrollTop: $(hash).offset().top });
    }
}
