var uid = 1;
function addAnchor(el) {
    if (document.all) {
	new Insertion.Before(el, '<a name="faq_' + uid + '"></a>'); // because of annoying IE bug where .name doesn't make anchor reachable
    } else {
	var a = document.createElement('a');
	a.name = 'faq_' + uid;
	el.parentNode.insertBefore(a, el);
    }
    uid++;
    return 'faq_' + (uid-1);
}

function addTopLink(e) {
    var toplink = document.createElement('a');
    toplink.href = '#top';
    toplink.className = 'top';
    toplink.innerHTML = 'top';
    if (!e.firstChild) {
	e.appendChild(toplink);        
    } else {
	e.insertBefore(toplink, e.firstChild);
    }
}

function boxSection(startingElement) {
    var e = $(startingElement);
    var s = '';
    do {
	if (e.nodeName.toUpperCase() == 'H3') {
	    var anchor = addAnchor(e);
	    s += '<li><a href="#' + anchor + '" class="question">' + e.innerHTML + '</a></li>';
	    addTopLink(e);
	}
	e = e.nextSibling;
    } while (e && e.nodeName.toUpperCase() != 'H2');
    if (s) s = '<ul>' + s + '</ul>';
    return s;
}

function configureFAQ() {
    var top = $('faq');
    
    var topanchor = document.createElement('a');
    topanchor.setAttribute('name', 'top');
    //topanchor.name = 'top';
    top.parentNode.insertBefore(topanchor, top);
    
    var ul = $(document.createElement('ul'));
    ul.id = 'faq_toc';
    top.parentNode.insertBefore(ul, top);
    
    var sections = top.getElementsByTagName('h2');
    var s = '';
    for (var i = 0; i < sections.length; i++) {
	var questions = boxSection(sections[i]);
	var anchor = addAnchor(sections[i]);
	s += '<li><a href="#' + anchor + '" class="section">' + sections[i].innerHTML + '</a>' + questions + '</li>';
    }
    ul.update(s);
    // force jump to hash
    if (document.location.href.indexOf('#') != -1) {
        window.location = document.location.href;
    }
}

Event.observe(window, 'load', configureFAQ);

