(function() {
    // Highlight the glossar words

    var glossar_link_class_name = 'glossaryLink';
    var word_char = /\w/;

    var climb = function(node, word, url){
        // traverse childnodes
        if (node.nodeType == node.TEXT_NODE) {
            checkforhighlight(node, word, url, 0);
            return
        }
        if (!node || !node.hasChildNodes || node.nodeName == 'TABLE') {
            return false
        }
        var i;
        for (i=0;i<node.childNodes.length;i++) {
            climb(node.childNodes[i], word, url);
        }
    }

    var checkforhighlight = function(node, word, url, start_index) {
        if (node.parentNode.nodeName != 'P' &&
            node.parentNode.nodeName != 'DIV') {
            return
        }
        if (node.parentNode.className == glossar_link_class_name) {
            return
        }
        ind = node.nodeValue.toLowerCase().indexOf(
            word.toLowerCase(), start_index);
        if (ind == -1) {
            return
        }
        if (ind > 0 && word_char.test(node.nodeValue[ind-1])) {
            // Substring match -> ignore
            checkforhighlight(node, word, url, ind+1);
            return 
        }
        var char_after = node.nodeValue[ind + word.length];
        if (typeof(char_after) != "undefined" &&
            word_char.test(char_after)) {
            // Substring match -> ignore
            checkforhighlight(node, word, url, ind+1);
            return
        }
        par = node.parentNode;
        contents = node.nodeValue;

        // make 3 shiny new nodes
        hiword = document.createElement("a");
        hiword.className = glossar_link_class_name;
        hiword.href = url;
        hiword.appendChild(
            document.createTextNode(
                contents.substr(ind, word.length)));
        par.insertBefore(
            document.createTextNode(contents.substr(0, ind)), node);
        par.insertBefore(hiword,node);
        var text_after = par.insertBefore(
            document.createTextNode(
                contents.substr(ind+word.length)), node);
        checkforhighlight(text_after, word, url, 0);
        par.removeChild(node);
    }

    var set_position = function(div, x, y, y_offset) {
        var x = x - 20;
        var y_offset = div.height() + 5 + y_offset;
        var y = y - y_offset;
        div.css({
            'left': x + 'px',
            'top': y + 'px'
        });
        div.addClass('visible');
        return y_offset;
    }

    var get_terms_and_highlight = function() {
        $.getJSON(
            uc_site_url + '/glossary-terms.json', null, function(data) {
            $().ready(function() {
                var node = document.getElementById('main_slot');
                $.map(data['terms'], function(term) {
                    climb(node, term.term, term.url);
                });

            });
        });
    };

    get_terms_and_highlight();

})();


