// jquery selectors
jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};


/*Navix191127 */
function scroll_lock(){
document.getElementById('content-container').classList.add('scroll_lock');
}

function scroll_lock_release(){
document.getElementById('content-container').classList.remove('scroll_lock');
}
/*//Navix191127 */


treeSelector = '#tree';

menuSelector = '#off-canvas-menu';
menuToggleSelector = '#sidebar-toggle';
searchToggle = '#schema-navbar-search';
remoconToggle = '#schema-navbar-remocon';


var mmenu = {};
var jqtree = {};
var nodes = [];
var initialMenuPath = [];

var defaultTitle = "(undefined)";

var scrollbarOptions = {
    theme: "minimal",
    scrollbarPosition: "inside",
	scrollInertia: 0
};

var scrollbarOptions2 = {
    theme: "minimal-dark",
    scrollbarPosition: "inside",
	scrollInertia: 0
};

var jqtree = {};
var nodes = [];
var initialMenuPath = [];

var defaultTitle = "(undefined)";
var click_id;
menuSelector = '#off-canvas-menu';

var scrollbarOptions = {
    theme: "minimal-dark",
	scrollInertia: 0
};
var nottop = false;

// data functions
function getTree() {
    return (typeof tocData === "undefined" ? [] : tocData);
}

function getLanguageData() {
    return (typeof languagesData === "undefined" ? [] : languagesData);
}

function getMenuData() {
    return (typeof menuData === "undefined" ? [] : menuData);
}


function isTouchDevice() {
    //return Modernizr.touch;
    return (('ontouchstart' in window) ||
        (navigator.maxTouchPoints > 0) ||
        (navigator.msMaxTouchPoints > 0));
}


function setActiveLanguageMenu( $item ) {
    
            var lang = $item.attr("data-value");
            var curLang = getCurrentLanguage();

            if(lang == curLang) {
                    $item.addClass("checked") 
            }
}

// helper function for language menu
function switchLanguage(newLang) {

    var curLang = getCurrentLanguage();

    if (curLang != newLang) {

        var curPath = current_path = window.location.pathname.split('/').pop();

        var newLocation = '../' + newLang + '/' + curPath;

        window.location.href = newLocation;

    }
}


// gets the current language 
function getCurrentLanguage() {

    return $('body').attr('data-culture');

}

function getCurrentNodeId() {

    return $("body").attr("data-node-id");

}

function getCurrentMenuPanel() {

    var currentNodeId = getCurrentNodeId();
    var currentLevel = nodes[currentNodeId];

    if (currentLevel && currentLevel.parent) {
        return $("#panel_" + currentLevel.parent.node.id);

    } else {
        return $("#panel_root");
    }

}
/*
function getDummyTreeNode() {

    return {
        label: "loading...",
        id: "loading",
        href: undefined,
        children: []
    };

}


function initializeNodesDictionary(treeNodes, parent) {

    treeNodes.forEach(function (node) {

        // store node to nodes dictionary
        nodes[node.id] = {
            node: node,
            parent: parent
        };

        if (node.nodes && node.nodes.length > 0) {
            initializeNodesDictionary(node.nodes, nodes[node.id]);
        }
    })
}
*/


function appendMenuLevel(parent, parentId, nodes) {


    if (nodes && nodes.length) {

        var list = $("<ul id='panel_" + parentId + "'></ul>");
        list.appendTo(parent);


        if (parentId == "root") {

			var menuHeadingValue = typeof menuHeading === "undefined" ? "(Menu)" : menuHeading;
            var menuHeadingElement = $("<li subheading='1'><a>" + menuHeadingValue + "</a></li>");
            menuHeadingElement.appendTo(list);

            // add navigation triplet home, index, glossary
            menuData.forEach(function (menuItem) {

                var listItem = $("<li entry-id='entry_" + menuItem.id + "' " + (getCurrentNodeId() === menuItem.id ? "current='1'" : "") + "><a href='" + menuItem.href + "'>" + (menuItem.name.length ? menuItem.name : defaultTitle) + "</a></li>");

                listItem.appendTo(list)

            });

            // append languages menu
            if (getLanguageData().length > 1) {

                var languagesMenuItem = $("<li><a>" + languagesHeading + "</a></li>");
                languagesMenuItem.appendTo(list);


                var languagesMenu = $("<ul id='panel_Languages" + parentId + "'></ul>");
                languagesMenu.appendTo(languagesMenuItem);

                getLanguageData().forEach(function (languageDataItem) {

                    var languagesMenuEntry = $("<li aspect='" + languageDataItem.data + "' " + (getCurrentLanguage() == languageDataItem.data ? "checked='1'" : "") + "><a>" + languageDataItem.name + "</a></li>");
                    if (getCurrentLanguage() != languageDataItem.data) {
                        languagesMenuEntry.bind('click', function (e) {
                            var lang = $(e.currentTarget).attr("aspect");
                            switchLanguage(lang);
                        });
                    }

                    languagesMenuEntry.appendTo(languagesMenu);

                });

            }

			var tocHeadingValue = typeof tocHeading === "undefined" ? "(Table of contents)" : tocHeading;
            var tocHeadingElement = $("<li subheading='1'><a>" + tocHeadingValue + "</a></li>");
            tocHeadingElement.appendTo(list);



        }


        nodes.forEach(function (node) {

            var listItem = $("<li entry-id='entry_" + node.id + "' " + (getCurrentNodeId() === node.id ? "current='1'" : "") + "><a href='" + node.href + "'>" + (node.text.length ? node.text : defaultTitle) + "</a></li>");

            listItem.appendTo(list);

            if (node.nodes && node.nodes.length > 0) {

                if (!isOnInitialPath(node.id)) {

                    var childList = $("<ul id='panel_" + node.id + "' panel-id='panel_" + node.id + "'></ul>");
                    childList.appendTo(listItem);

                    var defaultItem = $("<li class='loading'><a>loading...</a></li>");
                    defaultItem.appendTo(childList);

                } else {

                    appendMenuLevel(listItem, node.id, node.nodes);

                }

            }

        });
    }

}

function loadMenuPanel($panel) {


    var nodeId = $panel.attr("id").replace("panel_", "");
    var node = nodes[nodeId].node;

    var list = $('#' + $panel.attr("id") + " > ul")

    if (list.find("li.loading").length > 0) {

        list.find("li.loading").remove();

        node.nodes.forEach(function (child) {

            var listItem = $("<li entry-id='entry_" + child.id + "' " + (getCurrentNodeId() === child.id ? "current='1'" : "current='0'") + "><a href='" + child.href + "'>" + (child.text.length ? child.text : defaultTitle) + "</a></li>");

            listItem.appendTo(list);

            if (child.nodes && child.nodes.length > 0) {

                var childList = $("<ul id='panel_" + child.id + "' panel-id='panel_" + child.id + "'></ul>");
                childList.appendTo(listItem);

                var defaultItem = $("<li class='loading'><a>loading...</a></li>");
                defaultItem.appendTo(childList);

                mmenu.init(childList);

            }

        });

        mmenu.update();

    }
}


/*function calculateInitialSubTree(level) {


    if (level && level.node && level.node.id) {
        initialMenuPath.push(level.node.id);
    }

    if (level && level.parent) {
        calculateInitialSubTree(level.parent);
    }

}

function isOnInitialPath(nodeId) {

    var foundNodesOnPath = initialMenuPath.filter(function (pathId) {
        return pathId == nodeId;
    });

    return (foundNodesOnPath.length > 0);

}


function initializeMenu() {

    var menu = $(menuSelector);

    var menuOptions = {
        "slidingSubmenus": isTouchDevice(),
        "navbar": {
            "add": true,
            "title": projectTitle,
            "titleLink": "parent"
        }
    }

    menu.addClass("loading");

    setTimeout(function () {

        var currentNodeId = getCurrentNodeId();
        var currentMenuLevel = nodes[currentNodeId];

        calculateInitialSubTree(currentMenuLevel);

        // append tree data to menu
        appendMenuLevel(menu, 'root', getTree());

        $(menu).mmenu(menuOptions);

        mmenu = $(menu).data("mmenu");

        mmenu.openPanel(getCurrentMenuPanel());
        mmenu.setSelected($("entry_" + getCurrentNodeId()));

        mmenu.bind("openPanel", function ($panel) {

            loadMenuPanel($panel);

        });

        setTimeout(function () {

            menu.removeClass("loading");
        }, 500);

    }, 1);


}



function openInitialSubTree(currentId) {


    var treeContainer = $('#tree-container');

    var currentNode = nodes[currentId];

    if (currentNode && currentNode.parent) {

        initialMenuPath.forEach(function (nodeId) {

            var node = treeContainer.tree('getNodeById', nodeId);
            treeContainer.tree('openNode', node);

        });
    }

    var currentNode = treeContainer.tree('getNodeById', getCurrentNodeId());
    treeContainer.tree('selectNode', currentNode);


}*/

////function intializeSubTree(parent, nodes) {

////    nodes.forEach(function (node) {

////        var treeNode = {
////            label: node.text,
////            id: node.id,
////            href: node.href,
////            children: []
////        };

////        if (node.nodes && node.nodes.length) {

////            if (isOnInitialPath(node.id)) {

////                 intializeSubTree(treeNode.children, node.nodes);
////            } else {
////                treeNode.children.push(getDummyTreeNode());
////            }

////        }

////        parent.push(treeNode);

////    });

////}
function getDummyTreeNode() {

    return {
        label: "loading...",
        id: "loading",
        href: undefined,
        children: []
    };

}

function initializeNodesDictionary(treeNodes, parent) {

    treeNodes.forEach(function (node) {

        // store node to nodes dictionary
        nodes[node.id] = {
            node: node,
            parent: parent
        };

        if (node.nodes && node.nodes.length > 0) {
            initializeNodesDictionary(node.nodes, nodes[node.id]);
        }
    })
}

function calculateInitialSubTree(level) {


    if (level && level.node && level.node.id) {
        initialMenuPath.push(level.node.id);
    }

    if (level && level.parent) {
        calculateInitialSubTree(level.parent);
    }

}

function isOnInitialPath(nodeId) {

    var foundNodesOnPath = initialMenuPath.filter(function (pathId) {
        return pathId == nodeId;
    });

    return (foundNodesOnPath.length > 0);

}


function openInitialSubTree(currentId) {


    var treeContainer = $('.tree1');

    var currentNode = nodes[currentId];

    if (currentNode && currentNode.parent) {

        initialMenuPath.forEach(function (nodeId) {

            var node = treeContainer.tree('getNodeById', nodeId);
            treeContainer.tree('openNode', node);

        });
    }

    var currentNode = treeContainer.tree('getNodeById', getCurrentNodeId());
    treeContainer.tree('selectNode', currentNode);

}

function intializeSubTree(parent, nodes) {

    nodes.forEach(function (node) {

        var treeNode = {
            label: node.text,
            id: node.id,
            href: node.href,
            children: []
        };

        if (node.nodes && node.nodes.length) {
            intializeSubTree(treeNode.children, node.nodes);
        }
        parent.push(treeNode);
    });
}


function insertNavMenu() {
    
    var additionalClass = "visible-sm";
    var menuDropdown = $(".navbar-dropdown");
	var menuHeadingValue = typeof menuHeading === "undefined" ? "(Menu)" : menuHeading;
    var menuHeader = $("<li class='dropdown-header " + additionalClass + "'>" + menuHeadingValue + "</li>");
    if( menuDropdown ) {
    
        $(".navbar-menu li").each( function() {

           var item = $( this ).clone();
            
            item.addClass( additionalClass );
            item.removeClass( "active" );
            

            
            item.prependTo( menuDropdown );


        });
        
        menuHeader.prependTo(menuDropdown);
    }
}

function initializeTree() {


    var firstTreeLevel = [];

    var currentNodeId = getCurrentNodeId();
    var currentMenuLevel = nodes[currentNodeId];

    calculateInitialSubTree(currentMenuLevel);

     getTree().forEach(function (node) {

        var treeNode = {
            label: node.text,
            id: node.id,
            href: node.href,
            children: []
        };

        if (node.nodes && node.nodes.length) {

            if (isOnInitialPath(node.id)) {
                intializeSubTree(treeNode.children, node.nodes);
            } else {
                treeNode.children.push(getDummyTreeNode());
            }

        }

        firstTreeLevel.push(treeNode);

    });

    var menu = $(menuSelector);

	var tocHeadingValue = typeof tocHeading === "undefined" ? "(Table of contents)" : tocHeading;
    var treeTitle = $("<div id='tree-title'>" + tocHeadingValue + "</div>").appendTo(menu);
    var treeContainer = $("<div id='tree-container'></div>").appendTo(menu);

    var options = {

        data: firstTreeLevel,
        slide: false,
        closedIcon: '&#xe602',
        openedIcon: '&#xe600',
        onCreateLi: function (node, $li) {

            $li.find('.jqtree-title').attr("title", node.name);
            
            if( node.class ) {
                $li.addClass( node.class );
            }
        }
    }

    var jqtree = treeContainer.tree(options);

    openInitialSubTree();

    jqtree.bind(
        'tree.click',
        function (event) {

            var node = event.node;

            if (node.href) {

                window.location = node.href;
                event.preventDefault();

            }

        }
    );

    jqtree.bind(
        'tree.open',
        function (event) {

            var node = event.node;

            var treeNode = event.node ; // jqtree.tree('getNodeById', node.id); 

            var realNode = nodes[node.id].node;

            var data = {
                label: realNode.text,
                id: realNode.id,
                href: realNode.href
            };

            var children = realNode.nodes.map(function (realChildNode) {

                var childNode = {
                    label: realChildNode.text,
                    id: realChildNode.id,
                    href: realChildNode.href,
                    children: []
                };

                if (realChildNode.nodes && realChildNode.nodes.length) {
                    childNode.children.push(getDummyTreeNode());
                }

                return childNode;

            });

            jqtree.tree('loadData', children, treeNode);
        }
    );
}

function tryor(fn, v) {
    "use strict";

    try {
        return fn();
    } catch (e) {
        return v;
    }
};

function toArray(list, start) {
  var start = start || 0;
  var i = list.length - start;
  var ret = new Array(i);
  while (i--) {
    ret[i] = list[i + start];
  }
  return ret;
}

function trim(string) {
  if (typeof string !== 'string') {
    return string;
  }

  return string.replace(/\r?\n|\r/g, "").trim();
}

function showKeys(keys, activeKeys) {
    keys.forEach(function(key) {
        if (activeKeys.some(function(id) { return id === key.id })) {
            key.style.display = 'block';
        } else {
            key.style.display = 'none';
        }
    });
}

function initializeTree2() {
    var menuContents = $('#menu-contents');
    var scrollbar = menuContents.mCustomScrollbar(scrollbarOptions);

    var vars = [], max = 0, hash = "", array = "";
    var url = window.location.search;
    var page_rtn = false;

    hash  = url.slice(1).split('&');    
    max = hash.length;
    for (var i = 0; i < max; i++) {
        array = hash[i].split('=');
        vars.push(array[0]);
        vars[array[0]] = array[1];
    }

    var pageLinkId = vars;
    
    var firstTreeLevel = [];


    if (pageLinkId["page"] != null) {
        nottop = true;
    }

    var currentNodeId = getCurrentNodeId();

    var currentMenuLevel = nodes[currentNodeId];

    calculateInitialSubTree(currentMenuLevel);

     getTree().forEach(function (node) {

        var treeNode = {
            label: node.text,
            id: node.id,
            href: node.href,
            children: []
        };

        if (node.nodes && node.nodes.length) {

            if (isOnInitialPath(node.id)) {
                intializeSubTree(treeNode.children, node.nodes);
            }

        }

        firstTreeLevel.push(treeNode);

    });

    var len = firstTreeLevel.length;

    for ( i = 0; i < len; i++) {
        if (firstTreeLevel[i].id == currentNodeId) {
            firstTreeLevel2 = firstTreeLevel[i];
            firstTreeLevel = [];
            firstTreeLevel[0] = firstTreeLevel2;
            break;
        }
    }

    if (i == len) {
        if (currentMenuLevel == undefined || currentMenuLevel.parent == undefined) {
            return;
        }
        var id = currentMenuLevel.parent.node.id;
        for ( i = 0; i < len; i++) {
            if (firstTreeLevel[i].id == id) {
                firstTreeLevel2 = firstTreeLevel[i];
                firstTreeLevel = [];
                firstTreeLevel[0] = firstTreeLevel2;
                break;
            }
        }
        if (i == len) {
            var id = currentMenuLevel.parent.parent.node.id;
            for ( i = 0; i < len; i++) {
                if (firstTreeLevel[i].id == id) {
                    firstTreeLevel2 = firstTreeLevel[i];
                    firstTreeLevel = [];
                    firstTreeLevel[0] = firstTreeLevel2;
                    break;
                }
            }
        }
        nottop = true;
    }

    var len = firstTreeLevel[0].children.length;
    var top = $("#tree1");
    var div = ""
    for ( i = 0; i < len; i++) {
        div += "<div id='menu-tree-" + i + "'></div>";
    }

    top.append(div);

    for ( i = 0; i < len; i++) {

        var array = [].concat(firstTreeLevel[0].children[i]);
        var options = {

            data: array,
            slide: true,
            autoOpen: false,
            closedIcon: '&#xe602',
            openedIcon: '&#xe600',
            autoEscape:true,
            selectable:true
        }

        var treeContainer = $("#"+"menu-tree-"+i);
        var currentId2 =  "(undefined)";
        var currentNode = nodes[currentId2];

        if (currentNode && currentNode.parent) {
            initialMenuPath.forEach(function (nodeId) {
                var node = treeContainer.tree('getNodeById', nodeId);
                treeContainer.tree('openNode', node);
            });
        }

        var currentNode = treeContainer.tree('getNodeById', getCurrentNodeId());
        treeContainer.tree('selectNode', currentNode);

        var menu_tree = $("#"+"menu-tree-"+i);
        menu_tree.css("border-bottom", "1px");
        menu_tree.css("border-bottom-color", "black");
        menu_tree.css("border-bottom-style", "solid");
        var jqtree = menu_tree.tree(options);

        jqtree.bind(
            'tree.click',
            function (event) {
                var parents = 'menu-tree-';
                divObj = document.getElementsByTagName('div');
                matchObj= new RegExp(parents);
                var menu_count = 0;
                for(i=0; i < divObj.length; i++){
                    if(divObj[i].id.match(matchObj)){
                        menu_count++;
                    }
                }

                click_id = this.id;
                for (i = 0; i < menu_count; i++) {
                    var menu_tree = $("#"+"menu-tree-"+i);
                    if (menu_tree[0].id == click_id) {
                        continue;
                    }
                    var tree = menu_tree.tree("getTree");
                    tree.iterate(function(node) {
                        if (node.is_open) {
                            menu_tree.tree("closeNode", node);
                        }
                    });
                }

                var node = event.node;

                if (node.hasChildren()) {
                    $.cookie("node", node.id);
                } else {
                    $.cookie("node", node.parent.id);
                }

                var level = node.getLevel();

                if (node.hasChildren()) {       
                    var node_serch = node.getPreviousSibling();
                    while (node_serch != null) {
                        if (node_serch != null && node_serch.is_open){
                            jqtree.tree('closeNode', node_serch);
                            break;
                        }
                        node_serch = node_serch.getPreviousSibling();
                        if (node_serch == null) {
                            break;
                        }
                    }

                    node_serch = node.getNextSibling();
                    while (node_serch != null) {
                        if (node_serch != null && node_serch.is_open){
                            jqtree.tree('closeNode', node_serch);
                            break;
                        }
                        node_serch = node_serch.getNextSibling();
                        if (node_serch == null) {
                            break;
                        }
                    }
                }

/*                setTimeout(function() {
                    var w = $(window).innerWidth();
                    var h = $(document).height();
                    var footerTop = $("footer").position().top
                    var containerHeight = $(".container").outerHeight();

                    if ( window.matchMedia("(min-width: 992px)").matches ){
                        if (h - footerTop >= 0) {
                            $("footer").css("position", "fixed");
                            $("#off-canvas-menu").css("bottom","0px");
                            $("#off-canvas-menu").css("margin-bottom","50px");
                        }
                    } else {
                        if ((containerHeight + 70) - footerTop <= 0 || h - (containerHeight + 120) >= 0) {
                            $("footer").css("position", "fixed");
                        } else {
                            $("footer").css("position", "relative");
                        }
                    }

                }, 180);
*/
                if (node.href) {
                    if (node.hasChildren()) {
                        jqtree.tree('toggle', node);
                        return true;
                    }


                    window.location = node.href;
                    event.preventDefault();

                }
            }
        );

        jqtree.bind(
            'tree.open',
            function (event) {

                if (page_rtn == true) {
                    $('.content-container').animate({
                        scrollTop: $('#'+this.id).get( 0 ).offsetTop
                    },"fast", "swing");
                    page_rtn = false;
                } else {
                    var pos = $('#'+click_id).get( 0 ).offsetTop;
                    $('.content-container').animate({
                        scrollTop:  pos
                    },"fast", "swing");
                }

                var node = event.node;

                var level = node.getLevel();
                if (level == 1) {
                    var node_serch = node.getPreviousSibling();
                }

                var treeNode = event.node ; // jqtree.tree('getNodeById', node.id); 

                var realNode = nodes[node.id].node;

                var data = {
                    label: realNode.text,
                    id: realNode.id,
                    href: realNode.href
                };

                var children = realNode.nodes.map(function (realChildNode) {

                    var childNode = {
                        label: realChildNode.text,
                        id: realChildNode.id,
                        href: realChildNode.href,
                        children: []
                    };

                    if (realChildNode.nodes && realChildNode.nodes.length) {
                        childNode.children.push(getDummyTreeNode());
                    }

                    return childNode;
                });

                jqtree.tree('loadData', children, treeNode);
            }
        );

        if (id != undefined && id != currentNodeId) {
            var node = jqtree.tree('getNodeById', currentNodeId);
            if (node == undefined) {
                nottop = true;
                continue;
            } else {
                var level = node.getLevel();
                jqtree.tree('openNode', node);
                if (level == 2) {
                    var node2 = jqtree.tree('getNodeById', currentNodeId);
                    jqtree.tree('openNode', node2);
                }
                page_rtn = true;
            }
        }

        var getcookie = $.cookie("node");
        if (nottop && getcookie == undefined) {
            nottop = false;

            if (pageLinkId["page"] != null) {
                currentNodeId = pageLinkId["page"];
            }

            var node = jqtree.tree('getNodeById', currentNodeId);

            if (node == undefined) {
                nottop = true;
            } else {

                var level = node.getLevel();

                if (node.href) {
                    if (node.hasChildren()) {
                        jqtree.tree('openNode', node);
                        if(level == 2) {
                            var node2 = jqtree.tree('getNodeById', currentNodeId);
                            jqtree.tree('openNode', node2);
                        }
                        page_rtn = true;
                    }
                }
            }
        }

        if (getcookie != undefined) {
            var node = jqtree.tree('getNodeById', getcookie);

            if (node == undefined) {
                nottop = true;
                continue;
            }

            var level = node.getLevel();

            if (node.href) {
                if (node.hasChildren()) {
                    jqtree.tree('openNode', node);
                    if(level == 2) {
                        var node2 = jqtree.tree('getNodeById', getcookie);
                        jqtree.tree('openNode', node2);
                    }
                    page_rtn = true;
                }
            }
            $.removeCookie("node");
        }
    }

}

$(function () {

    $("body").addClass("loading");

    // get device class
    var device = (isTouchDevice() ? "mobile" : "desktop");

    $("body").addClass(device);
    
    setTimeout(function () {
        $("#off-canvas-menu").addClass("animated");
        $("#content-container").addClass("animated");
    }, 1000);
    
    

    $("." + device + "-hidden-sm").addClass("hidden-sm");
    $("." + device + "-hidden-md").addClass("hidden-md");
    $("." + device + "-hidden-xs").addClass("hidden-xs");
    $("." + device + "-hidden-lg").addClass("hidden-lg");

    $("." + device + "-visible-sm").addClass("visible-sm");
    $("." + device + "-visible-md").addClass("visible-md");
    $("." + device + "-visible-xs").addClass("visible-xs");
    $("." + device + "-visible-lg").addClass("visible-lg");

    // initialize nodes dictionary
    initializeNodesDictionary(getTree(), undefined);
    initializeNodesDictionary(getMenuData(), undefined);

    $(".break-tr").remove();

    var margin = $(window).innerWidth() - 1281;
    if (margin >= 0) {
        var left = margin / 2;
        $("#content-container, #off-canvas-menu").css("margin-left", left);
        $(".schema-root-page .content-container").css("margin-left", left - 256);
    } else {
        $("#content-container, #off-canvas-menu, .schema-root-page .content-container").css("margin-left", "");
    }

    if (margin >= 0) {
        $(".schema-navbar-toggle").css("right", left);
        $(".schema-navbar-brand").css("margin-left", left);
        $("#toTop-right").css("margin-right", left);
    } else {
        $(".schema-navbar-toggle").css("right", "");
        $(".schema-navbar-brand").css("margin-left", "");
        $("#toTop-right").css("margin-right", "");
    }

/* ================= modal ================= */

    var body = $("body").append("<div id='glayLayer'></div><div id='overLayer'></div>");

    $('#helps').hide();
    $('#helps').css("visibility", "visible");
    $('#trademarks').hide();
    $('#trademarks').css("visibility", "visible");
    $('#font-size-img').css("visibility", "visible");

    function centerModal(modal_content,modal_contentID){
        modal_content.css({
            "margin-top":(modal_contentID.height()-modal_content.height())/2+"px",
        });
        var a = modal_content.css("margin-top");
    }

    $('#help').click(function () {
        $(".modal-dialog").css("width", "");
        $(".modal-dialog").css("margin", "");
        $("#off-canvas-menu").css("z-index", "");
        $(".schema-navbar").css("z-index", "");
        $("#glayLayer").css("z-index", "");

        var container = $(".off-canvas");
        var activeClass = "showMenu";
        container.removeClass(activeClass);
		/*Navix191127 */
		scroll_lock_release();
		/*//Navix191127 */
		

        $("#off-canvas-menu").css("z-index", 1);
        $(".schema-navbar").css("z-index", 1);
        $("#glayLayer").css("z-index", $("#off-canvas-menu").css("z-index") + 1);
        $('#glayLayer').fadeIn(200);
        $("#overLayer").append($('#helps'));
        $('#helps').show();
        $("#overLayer").show();
        var h = $(document).height();
        var w = $(document).width();
        if( window.matchMedia("(max-width: 609px)").matches ){
            $('#help-top').css('height', h - 85);
            $('#help-top').css('max-height', h - 85);
        } else {
            $('#help-top').css('height', "");
            $('#help-top').css('max-height', "");
            var help_w = $('#modal-content_help').width();
            $("#helps").css("width", help_w);
            $("#helps").css("margin-left", (w - help_w)/2);
            var help_h = $('#modal-content_help').height();
            $("#helps").css("height", help_h + 30);
            $("#helps").css("top", (h - help_h - 60)/2);
        }
    });

    $( window ).resize(function() {
        centerModal($('#modal-content_font_size'),$("#font-size-img"));
        var h = $(document).height();
        var w = $(document).width();
        if( window.matchMedia("(max-width: 609px)").matches ){
            $("#helps").css("width", "");
            $("#helps").css("margin-left","");
            $("#helps").css("height","");
            $("#helps").css("top","");
            $('#help-top').css('height', h - 85);
            $('#help-top').css('max-height', h - 85);
        } else {
            $('#help-top').css('height', "");
            $('#help-top').css('max-height', "");
            var help_w = $('#modal-content_help').width();
            $("#helps").css("width", help_w);
            $("#helps").css("margin-left", (w - help_w)/2);
            var help_h = $('#modal-content_help').height();
            $("#helps").css("height", help_h + 30);
            $("#helps").css("top", (h - help_h - 60)/2);
        }
    });
    $('#trademark').click(function () {
        $(".modal-dialog").css("width", "initial");
        $(".modal-dialog").css("margin", "initial");
        $("#off-canvas-menu").css("z-index", "");
        $(".schema-navbar").css("z-index", "");
        $("#glayLayer").css("z-index", "");

        var container = $(".off-canvas");
        var activeClass = "showMenu";
        container.removeClass(activeClass);
		/*Navix191127 */
		scroll_lock_release();
		/*//Navix191127 */

        $("#off-canvas-menu").css("z-index", 1);
        $(".schema-navbar").css("z-index", 1);
        $("#glayLayer").css("z-index", $("#off-canvas-menu").css("z-index") + 1);
        $('#glayLayer').fadeIn(200);
        $("#overLayer").append($('#trademarks'));
        $('#trademarks').show();
        $("#overLayer").show();
        trade_size();
    });

    $( window ).resize(function() {
        centerModal($('#modal-content_font_size'),$("#font-size-img"));
        trade_size();
    });

    function trade_size() {
        var h = $(document).height();
        var w = $(document).width();
        if( window.matchMedia("(max-width: 430px)").matches ){
            $("#trademarks").css("margin-left","");
            $("#trademarks").css("margin-right","");
            $("#trademarks").css("top","");
            $("#trademarks").css("bottom","");
            var trademark_h = $('#modal-content_trademark').height();
            $("#trademarks").css("top", (h - trademark_h - 60)/2);
            $('#modal-content_trademark').css('width', w-10);
            $('#modal-content_trademark').css('margin-left',5);
        } else {
            $("#trademarks").css("top", "");
            $('#modal-content_trademark').css('width', "");
            $('#modal-content_trademark').css('margin-left',"");
            $('#trademark-top').css('height', "");
            $('#trademark-top').css('max-height', "");
            var trademark_w = $('#modal-content_trademark').width();
            $("#trademarks").css("margin-left", (w - trademark_w)/2);
            $("#trademarks").css("margin-right", (w - trademark_w)/2);
            var trademark_h = $('#modal-content_trademark').height();
            $("#trademarks").css("top", (h - trademark_h - 60)/2);
            $("#trademarks").css("bottom", (h - trademark_h - 60)/2);
        }
    
    }

    $("#trademarks .close").click(function(){
        $("#glayLayer").fadeOut(500);
        $("#overLayer").hide();
        $('#trademarks').hide();
        //$("#off-canvas-menu").css("z-index", "");
    });

    var size = $.cookie('size');
    if(size == 'large') {
        $('html').css('font-size','120%');
        $('#font-size-img-LtoS').hide();
        $('#font-size-img-StoL').show();
        if( window.matchMedia("(min-width: 992px)").matches ){
            $('.content-container .container').css("padding-right", "14.16rem");
        }
        $('ul.jqtree-tree > li > div').css("text-indent","-1.25rem");
        
    }else {
        $('html').css('font-size','100%');
        $('#font-size-img-StoL').hide();
        $('#font-size-img-LtoS').show();
        $('.content-container .container').css("padding-right", "");
        $('ul.jqtree-tree > li > div').css("text-indent","");
    }

    $('.font-size-img').click(function() {
        var size = $.cookie('size');
        if (size == 'large') {
            $('html').css('font-size','100%')
            $('#font-size-img-StoL').hide();
            $('#font-size-img-LtoS').show();
            $.cookie("size", "standard");
            var a = $.cookie("size");
            $('.content-container .container').css("padding-right", "");
            $('ul.jqtree-tree > li > div').css("text-indent","");
        } else {
            $('html').css('font-size','120%')
            $('#font-size-img-LtoS').hide();
            $('#font-size-img-StoL').show();
            $.cookie("size", "large");
            var a = $.cookie("size");
            if( window.matchMedia("(min-width: 992px)").matches ){
                $('.content-container .container').css("padding-right", "14.16rem");
            }
        $('ul.jqtree-tree > li > div').css("text-indent","-1.25rem");
        }
    });

    $("#helps .close").click(function(){
        $("#glayLayer").fadeOut(500);
        $("#overLayer").hide();
        $('#helps').hide();
        //$("#off-canvas-menu").css("z-index", "");
    });

    $("#menu-close .close").click(function(){
        $("#glayLayer").hide();
        var container = $(".off-canvas");
        var activeClass = "showMenu";
        container.removeClass(activeClass);
		/*Navix191127 */
		scroll_lock_release();
		/*//Navix191127 */
		
		
		
    });

    $("#glayLayer,#menu-close").click(function(){
        if ($("#search-collapse").css("display") == "block") {
            $("#search-collapse").collapse('hide');
        }
        $("#glayLayer").fadeOut(500);
        $("#overLayer").hide();
        $('#helps').hide();
        $('#trademarks').hide();
        var container = $(".off-canvas");
        var activeClass = "showMenu";
        container.removeClass(activeClass);
		
	/*Navix191127 */
	scroll_lock_release();
	/*//Navix191127 */
       
	/*   var duration = 500;
        var rcmenu = $(".rc-menu");
        $("#controller").css("z-index", "");
        rcmenu.css({'-webkit-transform':'translate3d(256px,0,0)', '-webkit-transition':'-webkit-transform 900ms cubic-bezier(0,0,0.25,1)',
        '-ms-transform':'translate3d(256px,0,0)', '-ms-transition':'-ms-transform 900ms cubic-bezier(0,0,0.25,1)'});*/
   });

    $("#schema-navbar-printer").click(function(){
        window.print();
        if ($("#search-collapse").css("display") == "block") {
            $("#search-collapse").collapse('hide');
        }
    });

     /*var duration = 600;
    var rcmenu = $(".rc-menu");
   $(remoconToggle).on("click", function(){
        $("#off-canvas-menu").css("z-index", "");
        $(".schema-navbar").css("z-index", "");
        $("#glayLayer").css("z-index", "");

        var zindex = rcmenu.css("z-index");
        $("#glayLayer").css("z-index", zindex - 10);
        if ($("#search-collapse").css("display") == "block") {
            $("#search-collapse").collapse('hide');
        }
        $("#glayLayer").fadeIn(500);
        var h = $(document).height();
        var svg = $("#svgid");
        var svgselect = $("#selected_keys");
        var doc = $(document);
        var svgID = document.getElementById('svgid');
        svg.attr("height", h - 50 - 15 + "px");
        rcmenu.css({'-webkit-transform':'translate3d(-256px,0,0)', '-ms-transform':'translate3d(-256px,0,0)', 
        '-webkit-transition':'-webkit-transform 400ms cubic-bezier(0,0,0.25,1)', '-ms-transition':'-ms-transform 400ms cubic-bezier(0,0,0.25,1)'});
        var screen = document.getElementById('svgid').contentDocument.getElementById('screen');
        screen.style.opacity = 0.8;
        var rckey = document.querySelector('page-meta').querySelectorAll('RCKey');
        var activeRcKeys = tryor(function() {return toArray(rckey) .map(function(meta) {return trim(meta.textContent);});}, []);
        var svgNodes = document.getElementById('svgid').contentDocument.getElementById('selected_keys');
        var selects = Array.prototype.slice.call(svgNodes.childNodes);
        var svgKeys = [];
        var j = 0;
        for (var i = 0, len = svgNodes.childNodes.length; i < len; i++) {
          if (svgNodes.childNodes[i].nodeName === 'g'){
             svgKeys[j] = selects[i];
             j++;
          }
        }

        showKeys(svgKeys, activeRcKeys);
    });

    $("#rc-close .close").click(function(){
        $("#glayLayer").fadeOut(500);
        rcmenu.stop(true).animate({"right": "-256px"}, duration);
        rcmenu.css({'-webkit-transform':'translate3d(256px,0,0)', '-webkit-transition':'-webkit-transform 900ms cubic-bezier(0,0,0.25,1)', 
        '-ms-transform':'translate3d(256px,0,0)', '-ms-transition':'-ms-transform 900ms cubic-bezier(0,0,0.25,1)'});
    });
*/

    // initialize navbar menu toggle 
    $(menuToggleSelector).click(function () {
		
		/*Navix191127 */
		scroll_lock();
		/*//Navix191127 */
		
	
        $("#off-canvas-menu").css("z-index", "");
 
        $("#off-canvas-menu").css("margin-bottom","0px");
        if ($("#search-collapse").css("display") == "block") {
            $("#search-collapse").collapse('hide');
        }

        var zindex = $("#off-canvas-menu").css("z-index");
        $(".schema-navbar").css("z-index", zindex - 10);
        $("#glayLayer").css("z-index", zindex - 10);

        var container = $(".off-canvas");
        var activeClass = "showMenu";
		

        if (!container.hasClass(activeClass)) {
            container.addClass(activeClass);
			
				
            $("#glayLayer").fadeIn(500);
			
        } else {
            container.removeClass(activeClass);
        };

    });

    $(searchToggle).click(function () {
        setTimeout( function(){
    //最初からフォーカス設定があれば合わせておく
    $("input").focus();
} , 500)
$("#off-canvas-menu").css("z-index", "");
        $(".schema-navbar").css("z-index", "");
        $("#glayLayer").css("z-index", "");
        $("#overLayer").css("z-index", "");

        if ($("#glayLayer").css("display") == "block") {
            $("#glayLayer").fadeOut(500);
            $("#off-canvas-menu").css("z-index", "");
            $("#glayLayer").css("z-index", "");
         } else {
            var zindex = $(".schema-navbar").css("z-index");
            $("#off-canvas-menu").css("z-index", zindex - 10);
            $("#glayLayer").css("z-index", zindex - 5);
            $("#glayLayer").fadeIn(500);
        }
    });

    $(document).on('click', '.breadcrumb li, .heading', function() {
        $.removeCookie("node");        
    });

    // set current language => main menu
    $('.navbar').find('.langMenuItem').each(function() {
       setActiveLanguageMenu( $( this ) );
    });
    
    
    // activate popupovers for lexicon links
    var popoverOptions = {
        container: "body",
        placement: "bottom",
        trigger: "hover",
        delay: {
            show: 200,
            hide: 100
        }
    };

    $('.lexicon-link').popover(popoverOptions);

    $("body").removeClass("loading");

    $(".container").each(function(){
        var txt = $(this).html();
        $(this).html(txt.replace(/<sup>/g,''));
        var txt = $(this).html();
        $(this).html(txt.replace(/®/g,'<sup>®</sup>'));
        var txt2 = $(this).html();
        $(this).html(txt2.replace(/[*]/g,'<sup>*</sup>'));
    });

    // initialize nodes dictionary
    initializeNodesDictionary(getTree(), undefined);

    initializeTree2();

    if( window.matchMedia("(min-width: 992px)").matches ){
        var size = $.cookie('size');
        if(size == 'large') {
            $('.content-container .container').css("padding-right", "14.16rem");
            $('ul.jqtree-tree > li > div').css("text-indent","-1.25rem");
        }
    } else {
        var h = $(document).height();
        $('.content-container .container').css("padding-right", "");
        $('ul.jqtree-tree > li > div').css("text-indent","");
    }
});

$(window).resize(function () {
    var timer = false;

    if (timer !== false) {
      clearTimeout(timer);
    }

    timer = setTimeout(function() {
        var w = $(window).innerWidth();
        var h = $(document).height();
        var svg = $("#svgid");
        svg.attr("height", h - 50 - 15 + "px");

        $("#toTop-right").hide();

        if( window.matchMedia("(min-width: 992px)").matches ){
            var size = $.cookie('size');
            if(size == 'large') {
                $('.content-container .container').css("padding-right", "14.16rem");
                $('ul.jqtree-tree > li > div').css("text-indent","-1.25rem");
            }
        } else {
            var overallH = $(".container-overall-languages").height();
            if (overallH ==null) {
                $('.content-container .container').css("padding-right", "");
                $('ul.jqtree-tree > li > div').css("text-indent","");
            }
        }
        
        var margin = w - 1281;

        if (margin >= 0) {
            var left = margin / 2;
            $(".off-canvas #content-container, #off-canvas-menu").css("margin-left", left);
            $(".schema-root-page .content-container").css("margin-left", left - 256);
        } else {
            $(".off-canvas #content-container, #off-canvas-menu, .schema-root-page .content-container").css("margin-left", "");
        }

        if (margin >= 0) {
            $(".schema-navbar-toggle").css("right", left);
            $(".schema-navbar-brand").css("margin-left", left);
            $("#toTop-right").css("margin-right", left);
        } else {
            $(".schema-navbar-toggle").css("right", "");
            $(".schema-navbar-brand").css("margin-left", "");
            $("#toTop-right").css("margin-right", "");
        }
    },50);
});


//Sticky heder 191203
  $(function() {
    var $win = $("#content-container");
      
      $boxtorio=$('#off-canvas-menu,.schema-navbar,#content-container');
        $boxtorio.addClass('show_toplogo');

    $win.on('load scroll', function() {
      var value = $(this).scrollTop();

      if ( value < 100 ) {
        $boxtorio.addClass('show_toplogo');
      } else {
        $boxtorio.removeClass('show_toplogo');
      }
    });
  });

////

window.onunload = function() {};

