﻿function searchGoogle(query){
    var win = window.open("http://www.google.com/search?hl=en&lr=&domains=" + window.location.host + "&q=" + query + "&btnG=Search&sitesearch=" + window.location.host);
}


function createTOC(dest, source){
    var _ul;
    function _createTOC(el){
        var _toc = [];
        $(el).find('h1,h2,h3').addClass('gen_toc_element');
        var selectedElements = $(el).find('.gen_toc_element');
        var _lvl = 0;
        var _text = null;
        selectedElements.each(function(i, _h){
            _h.id = "anc_" + i;
            _text = _h.innerHTML;
            _text = _text.replace(/<.*?>/g, "");
            _h.innerHTML = _text;
            _toc.push([Number(_h.tagName.substring(1)), "anc_" + i, _text]);
            $(_h).before("<a name=\"anc_" + i + "\"></a>");
        });
        selectedElements.removeClass("gen_toc_element");
        return _toc;
    }
    
    function _getToc(_toc){
        //passe på at vi står på topp
        var _lvl = _toc[0][0];
        var _root = (_ul = document.createElement("ul"));
        var _li = null;
        _ul.appendChild(_li = document.createElement("li"));
        _li.innerHTML = "<a href=\"#anc_top\">Til Toppen</a>";
        var i = null;
        for (i = 1; i < _lvl; i++) {
            _li = document.createElement("li");
            _ul.appendChild(_li);
            _ul = document.createElement("ul");
            _li.appendChild(_ul);
        }
        
        var _item = null;
        for (i = 0; i < _toc.length; i++) {
            _item = _toc[i];
            if (_lvl < _item[0]) {
                //gå ned
                _ul.appendChild(_li = document.createElement("li"));
                _li.appendChild(_ul = document.createElement("ul"));
            }
            if (_lvl > _item[0]) {
                //gå opp
                _ul = _ul.parentNode.parentNode;
            }
            
            _lvl = _item[0];
            _li = document.createElement("li");
            _li.innerHTML = "<a href=\"#" + _item[1] + "\">" + _item[2] + "</a>";
            _ul.appendChild(_li);
        }
        return _root;
    }
    
    var _container = null;
    var _content = null;
    
    if ((_container = document.getElementById(dest)) && (_content = document.getElementById(source))) {
        var _toc = _createTOC(_content);
        var _nodes = _getToc(_toc);
        _container.appendChild(_nodes);
    }
}

