document.lastMarginTop = 0;
document.lastSpanLeft = 0;
document.nextMarginLeft = 0;
window.previousSelection= '';
function xform_visibility(j)
{
    var form = document.xform;
    if (form['a' + j].value == 0)
	form['n' + j].style.display = form['d' + j].style.display = 'none';
    else
	form['n' + j].style.display = form['d' + j].style.display = '';
}
function dform_visibility(j)
{
    var form = document.dform;
    if (form['t' + j].value == -1) {
	form['a' + j].style.display = form['m' + j].style.display = 'none';
	form['e' + j].style.display = 'none';
    } else {
	form['a' + j].style.display = form['m' + j].style.display = '';
	form['e' + j].style.display = '';
    }
}
function dform_reset(max)
{
    var form = document.dform;
    for (var j = 1; j <= max; j++) {
	form['t' + j].options[0].selected = 1;
	dform_visibility(j);
    }
    form.noattrs.checked = 0;
}
function rform_visibility(j)
{
    var form = document.rform;
    if (form['a' + j].value == 0)
	form['t' + j].style.display = 'none';
    else
	form['t' + j].style.display = '';
}
function rform_reset(max)
{
    var form = document.rform;
    for (var j = 1; j <= max; j++) {
	form['a' + j].options[0].selected = 1;
	rform_visibility(j);
    }
}
function aform_visibility()
{
    var form = document.aform;
    if (form['type'].value == 2)
	form['max'].disabled = 1;
    else {
	form['max'].disabled = 0;
	if (form['max'].value == 0)
	    form['max'].value = 32;
    }
}
function new_group_prompt()
{
    var form = document.mainform;
    var newgroup = prompt("Enter the new group's name:", '');
    var reg = new RegExp('^'+document.scrname+'/|^/');
    newgroup = newgroup.replace(reg, '');
    newgroup = newgroup.replace(/^\s+|\s+$/g, '');
    if (!newgroup.match(/^[-A-Za-z0-9_ ]+$/)) {
	alert('Invalid group name -- no punctuation allowed.');
	return;
    }
    var id = '+' + newgroup; // Names that start with a plus are new.
    var boxname = 'grpchk' + id;
    if (form[boxname]) {
	alert("That group name already exists.");
	return;
    }
    add_group_checkbox(id, '/' + newgroup, 0);
    set_group_checkboxes();
    grpchk_change(boxname, 1);
}
function add_group_checkbox(id, group, disabled)
{
    var boxname = 'grpchk' + id;
    if (disabled) {
	disabled = ' DISABLED';
	style = ' style="color:red"';
    } else {
	disabled = '';
	style = '';
    }
    var s = document.getElementById('lstgroup');
    s.innerHTML += '<nobr><input type=checkbox name=' + boxname + ' value="' + id + '"'
		+ disabled + ' onclick=\'grpchk_change("' + boxname + '", 0)\' tabindex=1>'
		+ '<span' + style + ' onclick=\'grpchk_change("' + boxname + '", -1)\'>'
		+ group + "</span></nobr>&nbsp;&nbsp;\n";
}
function set_group_checkboxes()
{
    var form = document.mainform;
    if (form.Groups.value == '')
	return;
    var lst = form.Groups.value.split(',');
    for (var j in lst) {
	var boxname = 'grpchk' + lst[j];
	if (!form[boxname]) {
	    var group = lst[j].replace(/^\+/, '');
	    add_group_checkbox(lst[j], '/' + group, 0);
	}
    }
    for (var j in lst) {
	var boxname = 'grpchk' + lst[j];
	grpchk_change(boxname, 1);
    }
}
function grpchk_change(boxname, set)
{
    var form = document.mainform;
    var box = form[boxname];
    var grps = form.Groups
    if (set < 0)
	box.checked = !box.checked;
    else if (set > 0)
	box.checked = 1;
    var x = ',' + grps.value + ',';
    var i = x.indexOf(',' + box.value + ',');
    if (box.checked) {
	if (i >= 0)
	    return;
	grps.value += (grps.value != '' ? ',' : '') + box.value;
    } else {
	if (i < 0)
	    return;
	x = x.substring(0, i+1) + x.substring(i + box.value.length + 2, x.length);
	if (x.length > 1)
	    grps.value = x.substring(1, x.length - 1);
	else
	    grps.value = '';
    }
}
function hilight()
{
    if (window.currentMenu)
	return;
    if (document.selection && document.selection.createRange) {
	var range = document.body.createTextRange();
	range.moveToElementText(this.span);
	range.collapse();
	range.moveEnd('character', this.len);
	// We didn't output any trailing spaces, so these are extras added by IE.
	var t = range.text.replace(/ +\r\n/g, "\r\n");
	if (t.length != range.text.length)
	    range.moveEnd('character', range.text.length - t.length);
	range.select();
    } else if (document.createRange) {
	var sel = window.getSelection();
	sel.removeAllRanges();
	var range = document.createRange();
	range.selectNode(this.span);
	var len = this.len;
	for (var node = this.span.childNodes[0]; node; ) {
	    if (node.nodeName.match(/^#text$/i)) {
		if (node.nodeValue.length >= len) {
		    range.setEnd(node, len);
		    break;
		}
		len -= node.nodeValue.length;
	    } else if (node.childNodes.length) {
		node = node.childNodes[0];
		continue;
	    }
	    while (!node.nextSibling)
		node = node.parentNode;
	    node = node.nextSibling;
	}
	sel.addRange(range);
    }
    window.previousSelection = '';
    window.inHilite = 1;
}
function lolight()
{
    if (window.currentMenu)
	return;
    if (document.selection && document.selection.createRange)
	document.selection.empty();
    else {
	window.getSelection().removeAllRanges();
	//this.span.style.backgroundColor = 'white';
    }
    window.previousSelection = '';
    window.inHilite = 0;
}
function populateMargin(first, last)
{
    var c = document.getElementById('pbContentDiv');
    var limit = last - first >= 10 ? first + 10 : last + 1;
    for (var i = first; i < limit; i++)
	newMargin(c, i);
    if (limit <= last)
	window.setTimeout('populateMargin(' + limit + ',' + last + ')', 100);
}
function newMargin(c, i)
{
    var x = document.annoData[i].split('|');
    var s = document.getElementById('s' + x[0]);
    if (!s)
	return;
    var annoID = x[1], type = x[2], uID = x[3], len = x[4], text = x[5], title = x[6];
    var fg_color = x[7], bg_color = x[8], border_color = x[9], fontattrs = x[10], url = x[11];
    var d = document.createElement('div');
    var newtop = s.offsetTop;
    var newleft = c.offsetLeft + c.offsetWidth + 1;
    for (var p = s.offsetParent; p; p = p.offsetParent)
	newtop += p.offsetTop;
    if (newtop == document.lastMarginTop) {
	if (s.offsetLeft < document.lastSpanLeft)
	    document.lastMarginTop = newtop += s.offsetHeight;
	else
	    newleft = document.nextMarginLeft;
    } else
	document.lastMarginTop = newtop;
    document.lastSpanLeft = s.offsetLeft;
    if (!window.marginArrowWidth || annoID == document.bookTarget) {
	if (newleft == document.nextMarginLeft)
	    newleft += window.marginArrowWidth / 2;
	var p = document.createElement('div');
	p.className = 'marginarrow';
	p.style.top = newtop + 'px';
	p.style.left = newleft + 'px';
	p.innerHTML = '&raquo;';
	document.body.appendChild(p);
	window.marginArrowWidth = p.offsetWidth;
	if (annoID != document.bookTarget)
	    p.style.display = 'none';
    }
    newleft += window.marginArrowWidth;
    d.id = 'd' + i;
    d.annoID = annoID;
    d.annoType = type;
    d.uID = uID;
    d.len = len;
    d.span = s;
    d.onmouseover = hilight;
    d.onmouseout = lolight;
    d.oncontextmenu = handle_action;
    d.className = 'marginitem';
    d.style.top = newtop + 'px';
    d.style.left = newleft + 'px';
    d.Disabled = document.annoTypes[type].Disabled;
    setIcon(d, type, document.bookNum, text, title, fg_color, bg_color, border_color, fontattrs, url);
    document.body.appendChild(d);
    document.nextMarginLeft = newleft + d.offsetWidth + 1;
}
function setIcon(obj, type, bookNum, text, title, fg_color, bg_color, border_color, fontattrs, url)
{
    if (fg_color == '')
	fg_color = 'black';
    if (bg_color == '')
	bg_color = 'white';
    if (border_color == '')
	border_color = 'gray';
    with (obj.style) {
	color = fg_color;
	borderColor = border_color;
	backgroundColor = bg_color;
	if (fontattrs.substring(0, 1) == 'b')
	    fontWeight = 'bold';
	if (fontattrs.substring(1, 2) == 'i')
	    fontStyle = 'italic';
	if (fontattrs.substring(2, 3) == 'c')
	    fontVariant = 'small-caps';
    }
    var lc = document.annoTypes[type].LeftClick;
    // XXX This kluge for IE deals with lack of inherit, but it disables hover color...
    var color_kluge = window.IE7 ? ' style="color:' + fg_color + '"' : '';
    if (lc == 'url' && url != '') {
	if (url.charAt(0) == '&')
	    url = 'read.php?b=' + bookNum + url;
	var target = '';
	if (url.match(/^[a-z]+:/) && !url.match(/^http:\/\/www\.prosaix\.com\/pbos/))
	    target = ' target="_blank"';
	text = '<a href="' + url + '"' + target + color_kluge + '>' + text + '</a>';
    } else if (lc == 'note' && url != '')
	text = '<a href="read.php?b=' + bookNum + url + '"' + color_kluge + '>' + text + '</a>';
    else if (lc == 'info')
	text = '<a href="javascript:show_anno(' + obj.annoID + ')"' + color_kluge + '>' + text + '</a>';
    obj.innerHTML = '<nobr>' + text + '</nobr>';
    if (title != '')
	obj.title = title;
}
function setChecks(field, set, group)
{
    var reg;
    if (!field)
	return;
    if (group != '')
	reg = new RegExp('(^|,)' + group + '(,|$)');
    else
	reg = new RegExp('.');
    if (!field.length) {
	if (!field.disabled)
	    field.checked = set;
	return;
    }
    for (var i = 0; i < field.length; i++) {
	if (field[i].disabled || field[i].checked == set
	 || !reg.exec(document.iconGroup[field[i].value]))
	    continue;
	field[i].checked = set;
    }
}
function addOption(grp, name, n)
{
    var optname = n ? 'on_group' : 'off_group';
    opt = document.groupform[optname];
    var j = opt.length++;
    opt.options[j].value = grp;
    opt.options[j].text = 'group ' + name;
}
function find_block_parent(node)
{
    while (!node.nodeName.match(/^(p|h[1-6]|li|td|th|blockquote|center|dd|dt|body)$/i))
	node = node.parentNode;
    return node;
}
function get_nest_string(node)
{
    var sep = '', nest = '', j;
    for (; node && !node.nodeName.match(/^body$/i); node = node.parentNode) {
	if (node.nodeName.match(/^(#text|tbody)$/i))
	    continue;
	if (node.nodeName.match(/^div$/i)) {
	    if (node.getAttribute('id') == 'pbContentDiv')
		break;
	}
	for (j = 0, sib = node.previousSibling; sib; sib = sib.previousSibling) {
	    if (sib.nodeName == node.nodeName)
		j++;
	}
	nest = node.nodeName + (j ? '#' + (j+1) : '') + sep + nest;
	sep = '/';
    }
    return nest;
}
function check_selection()
{
    if (window.currentMenu) {
	if (window.inCurrentMenu)
	    return true;
	hide_menu();
    }
    if (window.inHilite)
	window.previousSelection = '';
    else if (window.getSelection) {
	var sel = window.getSelection();
	if (!sel.isCollapsed) {
	    var range = sel.getRangeAt(0);
	    window.previousSelection = range.toString();
	} else
	    window.previousSelection = '';
    } else if (document.selection && document.selection.createRange) {
	var range = document.selection.createRange();
	window.previousSelection = range.text;
    }
    return true;
}
function handle_selection(e)
{
    var str, pos, parent;
    var m = document.getElementById('pbSelMenuDiv');
    if (window.currentMenu || window.inHilite)
	return true;
    if (!e)
	e = window.event;
    if (window.getSelection) {
	var sel = window.getSelection();
	if (sel.isCollapsed) {
	    window.previousSelection = '';
	    return true;
	}
	var range = sel.getRangeAt(0);
	str = range.toString();
	if (str == window.previousSelection)
	    return true;
	parent = find_block_parent(range.startContainer);
	pos = range.startOffset;
	if (parent != range.startContainer) {
	    var node = parent.childNodes[0];
	    while (node != range.startContainer) {
		if (node.nodeName.match(/^#text$/i))
		    pos += node.nodeValue.length;
		else if (node.childNodes.length) {
		    node = node.childNodes[0];
		    continue;
		}
		while (!node.nextSibling)
		    node = node.parentNode;
		node = node.nextSibling;
	    }
	}
	//alert(pos + ' (' + parent.nodeName + ')');
	//sel.removeAllRanges();
    } else if (document.selection && document.selection.createRange) {
	var range = document.selection.createRange();
	str = range.text;
	if (!str.length) {
	    window.previousSelection = '';
	    return true;
	}
	if (str == window.previousSelection)
	    return true;
	range.collapse();
	parent = find_block_parent(range.parentElement());
	var erange = range.duplicate();
	erange.moveToElementText(parent);
	range.setEndPoint('StartToStart', erange);
	var txt = range.text.replace(/\r/g, '');
	pos = txt.length;
	//document.selection.empty();
    } else
	return true;

    if (!str.match(/[^\t\n ]/i))
	return true;

    var form = document.selform;
    form.nest.value = '/' + get_nest_string(parent);
    form.pos.value = pos;
    form.sel.value = str;
    //alert(form.nest.value + ':' + pos + ' (' + str + ')');
    var c = document.getElementById('pbContentDiv');
    var y = e.clientY - c.offsetTop + document.body.scrollTop + 15; // XXX harcoded 15s
    var x = e.clientX - c.offsetLeft;
    if (x > c.offsetWidth - 200) // XXX 200 == m.offsetWidth
	x = c.offsetWidth - 200;
    x += document.body.scrollLeft;
    m.style.left = x;
    m.style.top = y;
    window.currentMenu = m;
    window.hideAfter = 0;
    //m.style.display = 'block';
    window.setTimeout('show_menu(' + y + ')', 10);

    return false;
}
function show_menu(y)
{
    var m = window.currentMenu;
    if (!m)
	return;
    m.style.display = 'block';
    if (window.innerHeight)
	winBottom = window.innerHeight + document.body.scrollTop;
    else
	winBottom = document.body.offsetHeight + document.body.scrollTop;
    //alert(winBottom + ', ' + document.body.scrollTop + ', ' + y + ', ' + m.offsetHeight);
    if (y + m.offsetHeight > winBottom - 18) {
	y -= 15*2 + m.offsetHeight; // XXX hardcoded 15
	if (y < 0)
	    y = 0;
	m.style.top = y;
    }
}
function handle_action(e)
{
    var m;
    if (!e)
	e = window.event;
    if (!(m = document.actionMenu)) {
	document.actionItems = new Array();
	m = document.actionMenu = document.createElement('div');
	m.onmouseover = mousein_menu;
	m.onmouseout = mouseout_menu;
	m.className = 'menulist';
	m.innerHTML = '<ul>'
		    + action_item('show', 'Show', "Show all the attributes of this annotation", 0)
		    + action_item('edit', 'Edit', "Edit the attributes of this annotation", 1)
		    + action_item('anchor', 'Re-Anchor', "Change connection of this annotation to just-selected text", 1)
		    + action_item('delete', 'Delete', "Delete this annotation and all associated data", 1)
		    + action_item('cancel', 'Cancel', "Do nothing", 0)
		    + '</ul>';
	m.style.display = 'none';
	document.body.appendChild(m);
	if (getCookie('pbNoHints'))
	    setActionHints(0);
    }
    var ed_on = document.getElementById('edit_action');
    var ed_off = document.getElementById('edit_inaction');
    var del_on = document.getElementById('delete_action');
    var del_off = document.getElementById('delete_inaction');
    var anc_on = document.getElementById('anchor_action');
    var anc_off = document.getElementById('anchor_inaction');
    //alert(this.uID + ',' + document.UserID);
    if (this.Disabled || this.uID != document.UserID) {
	ed_on.style.display = del_on.style.display = anc_on.style.display = 'none';
	ed_off.style.display = del_off.style.display = anc_off.style.display = 'block';
    } else {
	ed_on.style.display = del_on.style.display = 'block';
	ed_off.style.display = del_off.style.display = 'none';
	if (window.previousSelection == '') {
	    anc_on.style.display = 'none';
	    anc_off.style.display = 'block';
	} else {
	    anc_on.style.display = 'block';
	    anc_off.style.display = 'none';
	}
    }
    var y = e.clientY + 15 + document.body.scrollTop; // XXX hardcoded 15
    m.style.top = y;
    m.style.left = e.clientX + document.body.scrollLeft - 200; // XXX 200 == m.offsetWidth;
    document.annoID = this.annoID;
    document.annoType = this.annoType;
    window.currentMenu = m;
    window.hideAfter = 0;
    //m.style.display = 'block';
    window.setTimeout('show_menu(' + y + ')', 10);

    return false;
}
function action_item(act, text, help, include_inaction)
{
    var html = '<li id=' + act + '_action title="' + help + '">'
	     + '<a href="javascript:do_action(\'' + act + '\')">'
	     + text + '</a></li>';
    document.actionItems.push(act + '_action');
    if (include_inaction) {
	html += '<li id=' + act + '_inaction title="' + help + '"><div>'
	      + text + '</div></li>';
	document.actionItems.push(act + '_inaction');
    }
    return html;
}
function hide_menu()
{
    if (!window.currentMenu)
	return;
    window.currentMenu.style.display = 'none';
    window.currentMenu = 0;
    window.inCurrentMenu = 0;
    if (window.inHilite)
	lolight();
}
function maybe_hide_menu()
{
    if (!window.inCurrentMenu && !window.inMenuTrigger)
	hide_menu();
    return true;
}
function create_anno(type)
{
    hide_menu();
    setCookie('pbScrollPos', document.body.scrollTop, '/');
    var form = document.selform;
    form.tID.value = type;
    form.annoID.value = 0;
    form.submit();
}
function do_action(act)
{
    hide_menu();
    if (act == 'cancel')
	return;
    if (act == 'delete') {
	var ans = confirm('Delete the annotation?');
	if (!ans)
	    return;
    }
    setCookie('pbScrollPos', document.body.scrollTop, '/');
    if (act == 'anchor') {
	var form = document.selform;
	form.tID.value = document.annoType;
	form.annoID.value = document.annoID;
	form.submit();
    } else
	window.location = 'annotate.php?do=' + act + document.bookRef + document.sectRef + '&a=' + document.annoID;
}
function show_anno(id)
{
    document.annoID = id;
    do_action('show');
}
function mousein_menu()
{
    window.inCurrentMenu = 1;
}
function mouseout_menu()
{
    window.inCurrentMenu = 0;
    if (window.hideAfter && !window.inMenuTrigger)
	window.setTimeout('maybe_hide_menu()', window.hideAfter);
}
function mousein_booktitle(a, book_num, bkmk)
{
    a.bkmk = bkmk;
    mousein_trigger(a, book_num, 'pbBookMenuDiv');
    var act = document.getElementById('bkmk_action');
    var inact = document.getElementById('bkmk_inaction');
    if (bkmk == '') {
	act.style.display = 'none';
	inact.style.display = '';
    } else {
	act.style.display = '';
	inact.style.display = 'none';
    }
}
function mousein_trigger(a, item_num, menu_id)
{
    window.inMenuTrigger = 1;
    if (window.currentMenu) {
	if (document.item && document.item.num == item_num)
	    return;
	hide_menu();
    }
    var m = document.getElementById(menu_id);
    var y = a.offsetTop + document.body.scrollTop + 25; // XXX hardcoded 25
    var x = a.offsetLeft;
    for (var p = a.offsetParent; p; p = p.offsetParent) {
	y += p.offsetTop;
	x += p.offsetLeft;
    }
    if (window.innerWidth)
	winWidth = window.innerWidth - 16;
    else
	winWidth = document.body.offsetWidth;
    if (x > winWidth - 24 - 400) { // Keep 400 in sync with all.css
	x = winWidth - 24 - 400;
	if (x < 0)
	    x = 0;
    }
    m.style.top = y;
    m.style.left = x;
    a.num = item_num;
    document.item = a;
    window.currentMenu = m;
    window.hideAfter = 1000;
    window.setTimeout('show_menu(' + y + ')', 200);
}
function mouseout_trigger()
{
    window.inMenuTrigger = 0;
    if (window.currentMenu && !window.inCurrentMenu) {
	if (window.currentMenu.style.display != 'block')
	    window.currentMenu = 0;
	else
	    window.setTimeout('maybe_hide_menu()', window.hideAfter);
    }
}
function first_page()
{
    window.location = document.item.href;
}
function list_sections()
{
    window.location = 'toc-' + document.item.num + '.html';
}
function newest_bkmk()
{
    window.location = document.item.href.replace(/0$/, document.item.bkmk + '#pblnk');
}
function pageUp(url)
{
    var y = typeof(window.pageYOffset) == 'number' ? window.pageYOffset : document.body.scrollTop;
    if (window.innerHeight)
	window.scrollBy(0, -(window.innerHeight - 18)); // XXX hardcoded 18s
    else
	window.scrollBy(0, -(document.body.offsetHeight - 18));
    var y2 = typeof(window.pageYOffset) == 'number' ? window.pageYOffset : document.body.scrollTop;
    if (y == y2 && url != '') {
	setCookie('pbScrollPos', 999999, '/');
	window.location = url;
    }
}
function pageDown(url)
{
    var y = typeof(window.pageYOffset) == 'number' ? window.pageYOffset : document.body.scrollTop;
    if (window.innerHeight)
	window.scrollBy(0, window.innerHeight - 18);
    else
	window.scrollBy(0, document.body.offsetHeight - 18);
    var y2 = typeof(window.pageYOffset) == 'number' ? window.pageYOffset : document.body.scrollTop;
    if (y == y2 && url != '')
	window.location = url;
}
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
	begin = dc.indexOf(prefix);
	if (begin != 0)
	    return false;
    } else
	begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
	end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}
function setCookie(name, value, path, expires)
{
    // "expires" is the number of seconds to keep the cookie active
    // or 0 for a session cookie.
    if (expires) {
	var e = new Date();
	e.setTime(e.getTime() + expires * 1000);
	expires = e;
    }
    document.cookie = name + "=" + escape(value)
	+ ((expires) ? "; expires=" + expires.toGMTString() : "")
	+ ((path) ? "; path=" + path : "");
}
function setHints(on_off)
{
    setButtonHints(on_off);
    for (var t in document.annoTypes) {
	var obj = document.getElementById('atype' + t);
	if (obj)
	    obj.title = on_off ? document.annoTypes[t].HelpText : '';
    }
    setActionHints(on_off);
}
function setButtonHints(on_off)
{
    var h = new Array();
    if (on_off) {
	h['btn-bookmarks'] = "View all your bookmarks for the current book";
	h['btn-config'] = "Manage logins, groups, books, and extensibility features";
	h['btn-disable_hints'] = "disable popup hints on buttons and menu items";
	h['btn-dissect'] = "Leverage WordNet knowledge to help you analyze/annotate the current book";
	h['btn-editbook'] = "Edit this book's content";
	h['btn-editnote'] = "Edit this note's content";
	h['btn-help'] = "See some documentation on how PBOS works";
	h['btn-library'] = "Select a book to view; manage books";
	h['btn-margin'] = "Change how the Annotations appear in the margin";
	h['btn-newbook'] = "Add the content for a new book";
	h['btn-next_sect'] = "Go to next section of the current book";
	h['btn-page_down'] = "Go to next page, changing sections as necessary";
	h['btn-page_up'] = "Go to previous page, changing sections as necessary";
	h['btn-prev_sect'] = "Go to previous section of the current book";
	h['btn-reports'] = "analyze/extract/sort/summarize Annotations from the current book";
	h['btn-return_to_book'] = "Return to current book";
	h['btn-sect_list'] = "See and navigate to sections of the current book";
	h['btn-signin'] = "Registered-user login";
	h['btn-signout'] = "Logout and view the library as an unregistered user";
	h['btn-signup'] = "New-user registration and email verification";
	h['dbtn-next_sect'] = "There are no sections following this one";
	h['dbtn-prev_sect'] = "There are no sections prior to this one";
    }
    var re = new RegExp(/\/([^\/]+)\.png$/);
    for (var j = 1; ; j++) {
	var img = document.getElementById('btn' + j);
	if (!img)
	    break;
	var m = re.exec(img.src);
	if (m != null)
	    img.title = on_off ? h[m[1]] : '';
    }
}
function setActionHints(on_off)
{
    for (var j in document.actionItems) {
	var id = document.actionItems[j];
	var obj = document.getElementById(id);
	if (on_off) {
	    if (obj.help)
		obj.title = obj.help;
	} else {
	    obj.help = obj.title;
	    obj.title = '';
	}
    }
}
function myOnLoad()
{
    if (document.checkScrollPos) {
	var pos = getCookie('pbScrollPos');
	if (pos && pos != 0) {
	    window.scrollTo(0, pos);
	    setCookie('pbScrollPos', 0, '/');
	}
    }
    if (document.annoCount)
	populateMargin(1, document.annoCount);
}
function toggle_hints()
{
    var hints_off = getCookie('pbNoHints');
    var img = document.getElementById('btn1');
    if (hints_off) {
	setCookie('pbNoHints', 0, '/', 1);
	img.src = 'images/btn-disable_hints.png';
    } else {
	setCookie('pbNoHints', 1, '/', 90*24*60*60);
	img.src = 'images/btn-enable_hints.png';
    }
    setHints(hints_off);
}
function signout()
{
    setCookie('pbauth', '', '/', 1);
    window.location = '.';
}
function mark_sentences()
{
    var sect = document.sectform.text;
    var text = '';
    var lines = sect.value.split("\n");
    for (var j in lines) {
	line = lines[j].replace(/<>/g, '') + ' ';
	line = line.replace(/\r/g, '');
	if (!line.match(/^=/)) {
	    if (line == ' ' && j)
		lines[j-1] = lines[j-1].replace(/<>$/, '');
	    line = line.replace(/(\s)\./g, '$1\1');
	    line = line.replace(/(\s[A-Za-z])\./g, '$1\1');
	    line = line.replace(/\.(\s+[a-z])/g, '\1$1');
	    line = line.replace(/([.!?]\"\)?|[.!?]\)|[.!?])(\s|&nbsp;)/g, '$1<>$2');
	    line = line.replace(/<>(&nbsp;| ) +/g, '<> ');
	    line = line.replace(/\1/g, '.');
	}
	lines[j] = line.replace(/\s+$/, '');
    }
    sect.value = lines.join("\n");
}
function textarea_format_change(button_text)
{
    var s = document.getElementById('toolbar');
    var form = document.sectform;
    if (form.format.options[0].selected) {
	form.mark.disabled = 0;
	form.sub.value = button_text;
	s.style.display = '';
    } else {
	form.mark.disabled = 1;
	form.sub.value = 'Convert to Wiki';
	s.style.display = 'none';
    }
}
function section_text_changed()
{
    var form = document.sectform;
    var title = form.stitle;
    if (title.value != '')
	return;
    var sect = form.text;
    var re = new RegExp(/^(\s*<[^>]*>)*\s*== (.*) ==\s+=== (.*) ===(\s|$)/);
    var m = re.exec(sect.value);
    if (m == null) {
	re = new RegExp(/^(\s*<[^>]*>)*\s*== (.*) ==(\s|$)/);
	m = re.exec(sect.value);
	if (m == null)
	    return;
	title.value = m[2];
    } else
	title.value = m[2] + ' -- ' + m[3];
}
function output_tb_button(n, js, help)
{
    js = js.replace(/\"/, '"+\'"\'+"');
    document.write('<a href="javascript:' + js + '">');
    document.write('<img src="images/button_'+n+'.png" width=23 height=22 border=0 title="'+help+'"></a>');
}
function output_toolbar(v,extra)
{
    document.write('<span id=toolbar>');
    output_tb_button('bold', "insertWiki('"+v+"','\\'\\'\\'','\\'\\'\\'','Put bold text here',0)", 'Make selected text Bold');
    output_tb_button('italic', "insertWiki('"+v+"','\\'\\'','\\'\\'','Put italic text here',0)", 'Make selected text Italic');
    output_tb_button('link', "insertWiki('"+v+"','[[',']]','link text',1)", 'Turn selected text into a link');
    output_tb_button('hr', "insertWikiLine('"+v+"')", 'Add a horizontal line');
    document.write(extra + '</span>\n');
}
function insertWiki(tvar, wOpen, wClose, sampleText, geturl)
{
    var form = document.forms[0];
    var ta = form[tvar];
    if (document.selection && document.selection.createRange) {
	var sel = document.selection.createRange().text;
	if (!sel)
	    sel = sampleText;
	if (geturl)
	    wOpen += urlPrompt(sel);
	ta.focus();
	if (sel.charAt(sel.length - 1) == " ") // exclude ending space, if any
	    document.selection.createRange().text = wOpen + sel.substring(0, sel.length - 1) + wClose + " ";
	else
	    document.selection.createRange().text = wOpen + sel + wClose;
    } else if (ta.selectionStart || ta.selectionStart == '0') {
	var startPos = ta.selectionStart;
	var endPos = ta.selectionEnd;
	var scrollTop = ta.scrollTop;
	var sel = ta.value.substring(startPos, endPos);
	if (!sel)
	    sel = sampleText;
	if (geturl)
	    wOpen += urlPrompt(sel);
	if (sel.charAt(sel.length - 1) == " ") // exclude ending space, if any
	    subst = wOpen + sel.substring(0, sel.length - 1) + wClose + " ";
	else
	    subst = wOpen + sel + wClose;
	ta.value = ta.value.substring(0, startPos) + subst + ta.value.substring(endPos, ta.value.length);
	ta.focus();

	var cPos = startPos + wOpen.length + sel.length + wClose.length;
	ta.selectionStart = cPos;
	ta.selectionEnd = cPos;
	ta.scrollTop = scrollTop;
    }
    if (ta.createTextRange)
	ta.caretPos = document.selection.createRange().duplicate();
}
function insertWikiLine(tvar)
{
    insertWiki(tvar, '', "\n----\n", '', 0);
}
function urlPrompt(sel)
{
    var url = prompt("Enter the URL of the link:", 'http://');
    if (url == sel || url == 'http://' + sel)
	return '';
    return url + ' ';
}

