var current_mouse_x;
var current_mouse_y;

var browser_name = "default";
var browser_version = "";

if (navigator.appName == "Microsoft Internet Explorer") {
	browser_name = "msie";
	if (navigator.appVersion.match(/7\.0/))
		browser_version = 7;
	else if (navigator.appVersion.match(/8\.0/))
		browser_version = 8;
	else
		browser_version = 6;
}

// this function determines whether the event is the equivalent of the microsoft
// mouseleave or mouseenter events.
function isMouseLeaveOrEnter(e, handler) {
	var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
	while (reltg && reltg != handler) {
		reltg = reltg.parentNode;
	}
	return (reltg != handler);
}

function init() {
	var i=0;

	highlight_search_terms($('content'));

	if (document.forms[0] && document.forms[0].f_user) {
		if (document.forms[0].f_user.value)
			document.forms[0].f_pass.focus();
		else
			document.forms[0].f_user.focus();
	}

	/*
	**  This is a hack to get around the fact that IE does not
	**  support position:fixed.
	*/
	if (browser_name == 'msie' && browser_version < 9) { // if IE
		move_fixed_divs();
	}

	if (window.onLoad) {
		onLoad();
	}

	document.onmousemove = function(e) {
		if (document.body.scrollLeft >= 0 && document.all) {
			current_mouse_x = window.event.x+document.body.scrollLeft;
			current_mouse_y = window.event.y+document.body.scrollTop;
		} else {
			current_mouse_x = e.pageX;
			current_mouse_y = e.pageY;
		}
	}
}

// display an error msg
function display_error (msg) {
	display_msg_div ('error_msg', msg);
}

// display an msg
function display_msg (msg) {
	display_msg_div ('msg', msg);
}

// display a message div
function display_msg_div (div_name, msg) {
	var div = $(div_name);
	if (!div)
		div = window.opener.$(div_name);
	div.innerHTML = msg;
	div.style.display = 'block';
}

// hide a message div
function hide_msg_div (div_name) {
	var div = $(div_name);
	if (!div)
		div = window.opener.$(div_name);
	div.style.display = 'none';
}

// report an error and highlight input field. also clear
// input field and change class if necessary
function show_error (field, msg) {
	field.focus();
	display_error(msg);
	location.href = '#error_msg';
	field.className = 'show_error';
}

// restore input to good state - hide previous error
function hide_error (field) {
	$('error_msg').style.display = 'none';
	field.className = 'hide_error';
}

//  This function will hide Elements by object Class
function hideClass(objClass) {
	var ie = (document.all) ? true : false;
	var elements = (ie) ? document.all : document.getElementsByTagName('*');
	var classRx = new RegExp('\\b'+objClass+'\\b');
	for (i=0; i<elements.length; i++) {
		if (classRx.test (elements[i].className)) {
			elements[i].style.display = "none";
		}
	}
}

//  This function will show Elements by object Class
function showClass(objClass) {
	var ie = (document.all) ? true : false;
	var elements = (ie) ? document.all : document.getElementsByTagName('*');
	var classRx = new RegExp('\\b'+objClass+'\\b');
	for (i=0; i<elements.length; i++) {
		if (classRx.test (elements[i].className)) {
			elements[i].style.display = "block";
		}
	}
}

// handle ajax responses and report if there's an error
function handle_response (r) {
	if (!r) {
		display_error("ERROR: No response.");
		return;
	}

	var response = r.responseText.evalJSON();

	// handle error msg
	if (response.error_msg.length > 0) {
		display_error("ERROR: " + response.error_msg);
		return;
	}

	if (response.msg && response.msg.length > 0) {
		display_msg(response.msg);
	}

	return response;
}

// Update the contents of the page and print any error messages.
function update (response) {
	if (!response)
		return;

	// print errors
	if (response.error_msg.length) {
		alert("ERROR: "+response.error_msg);
		return;
	}

	// print the updated contents of the page
	for (var i=0; i < response.types.length; i++) {
		if (response.types[i] == 'msg' && response.msg.length) {
			alert(response.msg);
		} else {
			var div = document.getElementById('e_' + response.types[i]);
			if (div) {
				div.innerHTML = eval('response.' + response.types[i]);
				div.style.display = 'block';
			}
		}
	}
}

function showhide(id) {
	var div = document.getElementById(id);
	if (div) {
		if (div.style.display == "none" || !div.style.display) {
			new Effect.BlindDown(div, {duration: 0.2, afterFinish: function(obj) { obj.element.style.display = 'block'; }});
		} else {
		new Effect.BlindUp(div, {duration: 0.2, afterFinish: function(obj) { obj.element.style.display = 'none'; }});
		}
	}
}

function toggle_div(div, anim) {
	if (anim == 'undefined')
		anim = false;

	if (div.style.display == 'none') {
		if (anim)
			new Effect.BlindDown(div, {duration:0.25});
		else
			div.style.display = 'block';
	} else {
		if (anim)
			new Effect.BlindUp(div, {duration:0.25});
		else
			div.style.display = 'none';
	}
}

// Toggle the contents of one element based on whether another div is hidden
// or showing.
//   div - the name of the div which is being toggled
//   contents - the name of the element which contents are being changed
//   show - the HTML which is shown in the contents element when div is shown
//   hide - the HTML which is shown in the contents element when div is hidden
function toggle_contents (div, contents, show, hide) {
	if (div.style.display == 'none') {
		contents.innerHTML = show;
	} else {
		contents.innerHTML = hide;
	}
}

function get_display_height() {
	var h;
	if (window.innerHeight) {
		h=window.innerHeight;
	} else if (document.documentElement.clientHeight) {
		h=document.documentElement.clientHeight;
	} else if (document.body.clientHeight) {
		h=document.body.clientHeight;
	}
	return h;
}

function scroll_top() {
	return filter_results (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function filter_results(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function get_true_left(e) {
	if (!e && this)
		e = this;

	var n = e.offsetLeft;
	var p = e.offsetParent;
	while (p != null) {
		n += p.offsetLeft;
		p = p.offsetParent;
	}
	return n;
}

function get_true_top(e) {
	if (!e && this)
		e = this;

	var n = e.offsetTop;
	var p = e.offsetParent;
	while (p != null) {
		n += p.offsetTop;
		p = p.offsetParent;
	}
	return n;
}

function get_url_parameter(strParamName){
	var args_str = location.href.split("?")[1];
	if (args_str) {
		var args = args_str.split(/[&#]/);
		for (var i=0; i < args.length; i++) {
			var params = args[i].split("=");
			if (params[0] == strParamName)
				return params[1];
		}
	}
	return "";
}

function get_search_terms() {
	var str = get_url_parameter("h");
	if (str.length == 0)
		return new Array();
	return str.split(/(,|%2c)/i);
}

function highlight_search_terms(div) {
	var terms = get_search_terms();
	var term_re = "";
	var i;

	for (i=0; i < terms.length; i++) {
		var term = terms[i].replace(/(%20|\+)+/, "\\s+");
		if (term.length) {
			if (term_re)
				term_re += "|";
			term_re += term;
		}
	}
	if (term_re.length) {
		var re = new RegExp("("+term_re+")", 'gi');
		div.innerHTML = div.innerHTML.replace(re, "<a name=term0></a><span class=search_highlight>$1</span>");
	}

	if (i>0 && location.href.indexOf('term0') == -1)
		location.href = location.href+"#term0";
}

/*
**  these "fixed_div" functions are for a work-around in IE6 that
**  doesn't allow a div to be in a fixed position.  This is only
**  used for IE6 browsers.
*/
var fixed_divs = new Array();
function add_fixed_div(div) {
	fixed_divs.push(div);
}
function remove_fixed_div(div) {
	for (var i=0; i < fixed_divs.length; i++) {
		if (fixed_divs[i] == div) {
			fixed_divs.splice(i, 1);
			return;
		}
	}
}
function move_fixed_divs() {
	for (var i=0; i < fixed_divs.length; i++) {
		fixed_divs[i].style.position = "absolute";
		fixed_divs[i].style.top = fixed_divs[i].getFixedPosition();
	}
	setTimeout("move_fixed_divs()", 10);
}

/*
**  toggle_stars() - uses ajax to "star" a document.
*/
function toggle_star(id, size) {
	var img = document.getElementById('star_'+id);
	var data = { doc_id: id };
	var a = new Ajax.Request('/util/ajax/stars', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onComplete: function(r) {

			var response = r.responseText.evalJSON();
			if (response.image) {
				src = '/images/commentary/star_'+response.image;
				if (size)
					src += '_'+size;
				img.src = src+'.png';

				img.onmouseover = "icon_help(this);";
			}
		}
	});
}

// add to folder popup
function show_add_to_folder(id, type) {
	var win = window.open('/research/folders/add_to_folder.php?id='+id+'&type='+type,
		'show_folder_chooser',
		'width=600,height=550,scrollbars=yes,toolbar=no,directories=no,menubar=no');
}

function popup(url, width, height) {
	if (!width)
		width = 800;
	if (!height)
		height = 800;
	window.open(url, 'popup',
		'width='+width+',height='+height+',scrollbars=yes,toolbar=no,directories=no,menubar=no');
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;}
function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;}
function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;}
function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;}
function posRight() {return posLeft()+pageWidth();}
function posBottom() {return posTop()+pageHeight();}

function set_busy_cursor(v) {

	document.body.style.cursor = (v?'wait':'default');
	zz = document.getElementsByTagName('a')
	for (var i=0;i < zz.length; i++) {
		if (v)
			zz[i].style.cursor = 'wait';
		else
			zz[i].style.cursor = 'pointer';
	}
	zz = document.getElementsByTagName('input')
	for (var i=0;i < zz.length; i++) {
		if (v)
			zz[i].style.cursor = 'wait';
		else if (zz[i].type == 'text')
			zz[i].style.cursor = 'text';
		else
			zz[i].style.cursor = 'default';
	}
}

function impersonateUser (uname) {
	if (!uname)
		uname = prompt('Please enter the username of the user you would like to impersonate.');
	var data = { uname: uname };
	var a = new Ajax.Request('/admin/impersonate', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onComplete: function(r) {

			var response = handle_response(r);

			// go to the user's homepage
			if (response && response.server) {
				window.location = 'https://' + response.server + '/home';
			}
	}});
}

/*
**  This function will display the text editor window.  The first
**  parameter is boolean to specify show or hide.  The second parameter
**  is the type that we want to edit.  This can be ctitle, teaser, summary,
** commentary, or note_add.
*/
function show_texteditor(v, url, id, name) {
	if (v) {
		$('texteditor_save').onclick = function() {
				save_texteditor(url, id, name);
				show_texteditor(false);
			};

		var data = { action: "get_"+name, id: id };
		var a = new Ajax.Request(url, { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
			onSuccess: function(r) {
				var response = r.responseText.evalJSON();
				if (response.text)
					tinyMCE.activeEditor.setContent(response.text);
				$('texteditor_container').style.display = 'block';
				update(response);
				resize_texteditor();
		}});

	} else {
		$('texteditor_container').style.display = 'none';
	}
}

function save_texteditor(url, id, name) {
	var html = tinyMCE.activeEditor.getContent();
	var data = { action: "save_"+name, id: id, value: html };
	var a = new Ajax.Request(url, { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onSuccess: function(r) {
			var response = r.responseText.evalJSON();
			update(response);
	}});
}

/*
**  These are functions called every 0.5 seconds while the respective
**  windows are displayed.  They monitor the size of the browser
**  window and resize themselves accordingly.
*/
function resize_texteditor() {
	if ($('texteditor_container').style.display != 'block')
		return;
	$('texteditor_container').style.height = (pageHeight()-115)+"px";
	$('texteditor_tbl').style.height = (pageHeight()-200);
	$('texteditor_ifr').style.height = (pageHeight()-200);
	setTimeout("resize_texteditor()", 500);
}

/*
**  This function shows and hides the "Waiting" screen.
**  It uses a timer to only display the waiting notice if we have
**  already waited more than 1 second.  This way it doesn't just
**  flash up the screen unnecessarily when it's snappy.  It will only
**  show it when things are running slow.
*/
var waiting_list = new Array();
var waiting_timeout = null;
function ed_show_waiting(v, delay) {
	if (v) {
		if (waiting_list.push(1) == 1) {
			set_busy_cursor(true);
			ed_show_waiting_appear();
		}
	} else {
		waiting_list.pop();
		if (waiting_list.length == 0) {
			$('waiting_container').hide();
			clearTimeout(waiting_timeout);
			set_busy_cursor(false);
		}
	}
	$('wlist').innerHTML = waiting_list.length + ' item remaining';
}
function ed_show_waiting_appear() {
	$('waiting_container').style.display = 'block';
}

// when the user clicks enter, anticipate what form they are trying to submit
// based upon what buttons are present on the page and what values are filled out
document.onkeydown = fnTrapKeyDown;
function fnTrapKeyDown(e) {
	var intKeyPressed = document.all? event.keyCode: e.which;
	if (intKeyPressed == 13) {

		if ($('login_btn') && $('login_form') && $('f_pass').value != '' &&
				$('f_pass').value != 'password' && $('f_user').value != '' &&
				$('f_user').value != 'username') { // login
			// we don't check for username or password being filled out because
			// if they don't fill it out, they'll get an error which is the behavior
			// we want
			// this is not a real button, so just submit the form
			$('login_form').submit();

		} else if ($('quick_search_btn') && $('q') && $('q').value != ''
				&& $('quick_search_form')) {
			// quick search (in CPC's header)
			// this is not a real button, so just submit the form
			$('quick_search_form').submit();

		} else if ($('search_btn') && $('q2') && $('q2').value != '') {
			// advanced search or specific doctype search
			$('search_btn').click();

		} else if ($('glossary_search_btn') && $('phrase') && $('phrase').value != '') {
			// glossary popup search
			$('glossary_search_btn').click();

		} else if ($('citation_lookup_btn') && $('lookup') && $('lookup').value != '') {
			// citation lookup popup search
			$('citation_lookup_btn').click();

		} else if ($('document_id_lookup_btn') && $('lookup') && $('lookup').value != '') {
			// document_id lookup popup search
			$('document_id_lookup_btn').click();

		} else if ($('create_new_folder_btn') && $('new_folder') && $('new_folder').value != '') {
			// create a new folder
			$('create_new_folder_btn').click();

		} else if ($('jumpto_btn')) {
			// library jump to a document - if a text box is on the page, make sure
			// that's filled out
			if ($('number') && $('number').value == '')
					return false;
			else if ($('citation') && $('citation').value == '')
					return false;
			else if ($('section') && $('section').value == '')
					return false;
			else if ($('section_id') && $('section_id').value == '')
					return false;
			$('jumpto_btn').click();
		}
		return false;
	}
}

function showGlossary (toggle) {
	window.open('/tools/glossary.php', 'glossary',
		'width=500,height=600,scrollbars=no,toolbar=no,directories=no,menubar=no');
}

function showCitationLookup (toggle) {
	window.open('/tools/citation_lookup.php', 'citation_lookup', 
		'width=650,height=550,scrollbars=no,toolbar=no,directories=no,menubar=no');
}

function showDocumentIdLookup (toggle) {
	window.open('/tools/document_lookup.php', 'document_id_lookup',
		'width=650,height=550,scrollbars=no,toolbar=no,directories=no,menubar=no');
}

function generate_random_string (len) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i = 0; i < len; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

// populate the dropdown with object options to select from
//   cname = name of object class
//   select = the dropdown object
//   add = if set to false, will not give user option of adding object
//   otype = can use to narrow down your dropdown options
function populate_object_dropdown(cname, select, id, add, otype) {
	ed_show_waiting(true);
	if (!select)
		return;
	if (add != false)
		add = true;
	var data = { type: 'list', obj_class: cname, otype: otype };
	new Ajax.Request(
		'/util/ajax_object.php',
		{
			method: 'post',
			parameters: 'data='+encodeURIComponent(Object.toJSON(data)),
			onComplete: function(r) {
				var response = handle_response(r);
				// clear the list first
				select.options.length = 0;

				if (response.list) {
					// add to the list
					var start = -1;
					if (add)
						start = -2;
					select.options[0] = new Option('Please select ...', start);
					if (add)
						select.options[1] = new Option("Add a new "+response.obj_class, start+1);
					for (var i = 0; i < response.list.length; i++) {
						// str += response.list[i].id + ": " + response.list[i].name + "\n";
						select.options[i-start] = new Option(response.list[i].name, response.list[i].id);
						if (response.list[i].id == id)
							select.selectedIndex = i-start;
					}
				}
				ed_show_waiting(false);
			}
		});
}

// upload a shell file. may need to create a new shell file, or just update
// existing shell file.
//   id = the id of the shell file
//   url = the url which we are uploading
//   otype = the name of the textbox containing the url
function upload_shell(id, url, otype) {
	if (url.indexOf('/organizations') == 0) {
		alert('You can not update a local file.');
	} else {
		var data = { obj_class: 'shell', id: id, type: 'upload', url: url, otype: otype };
		var a = new Ajax.Request('/util/ajax_object.php', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
			onComplete: function(r) {
				var response = handle_response(r);
				window.location.reload();
				alert('The changes have been saved.');
		}});
	}
}

function submitEnter(myfield, e, url) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
		location.href = url;
		return false;
	} else
	return true;
}

function email_account(id, pw) {
	var data = { obj_class: 'user', id: id, type: 'email_account', password: pw };
	var a = new Ajax.Request('/util/ajax_object.php', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onComplete: function(r) {
			var response = handle_response(r);
			window.location.href = '/home';
			alert('The user has been emailed his username and password.');
	}});
}

// perform an advanced search with doctype and gentype and date constraints. also
// use for pagination (sort and page).
function search_library (page) {
	// get the query
	var query = $('q2').value;

	// get search parameters
	var data;
	var advanced = $('search_constraints');
	if (advanced && advanced.style.display == 'block') {
		var sort = $('sort').value;
		var date_after = $('date_after').value;
		if (date_after == 'Issued after')
			date_after = '';
		var date_before = $('date_before').value;
		if (date_before == 'Issued prior to')
			date_before = '';

		// get the list of doctypes
		var doctypes = new Array();
		var dts = document.getElementsByName('doctypes[]');
		if (dts && dts.length > 0) {
			for (var i = 0; i < dts.length; i++) {
				if (dts[i].checked) {
					if (dts[i].value == 'cca' || dts[i].value == 'plr'
							|| dts[i].value == 'tam') {
						doctypes.push('wd');

					} else {
						doctypes.push(dts[i].value);
					}
				}
			}
		}

		if (doctypes.length == 0) {
			display_error('Please select at least one type of document to search from.');
			return;
		}

		// get search parameters
		data = { query: query, types: doctypes,
			date_after: date_after, date_before: date_before,
			page: page, sort: sort };

	} else data = { query: query, page: page };

	ed_show_waiting(true);
	new Ajax.Request(
		'/util/ajax/search', {
		method: 'post',
		parameters: 'data='+encodeURIComponent(Object.toJSON(data)),
		onComplete: function(r) {
			var response = handle_response(r);

			var suggested = '';
			if (response && response.numsuggested > 0) {
				suggested = '<div id=\"search_suggested\"> \
				<h5>Did you mean ...</h5><ul>';
				// show the values stored
				for (var i in response.suggested) {
					suggested += '<li><a href=\"'+response.suggested[i]+
						'\" target=\"_blank\">'+i+'</a>\n';
				}
				suggested += '</ul></div>';
			}

			// fill in the number of results and the total time to load
			$('e_results_num').innerHTML = addCommas(response.numresults) + ' results \
			(' + response.total_time +' seconds)';

			if (!response || response.numresults <= 0) {
				str = '';
				if (suggested != '')
					str += suggested;
				str += '<p class=\"plain_msg\">No results found.</p>';

			} else { // prints the pagination and results
				if (response.num_pages > 0) {
					var start = 1;
					var num = 5;
					if (response.page - 5 > 1)
						start = response.page - 5;
					if (response.page < 5)
						num = 10;
					var end = response.num_pages;
					if (response.page + num < response.num_pages)
						end = response.page + num;

					var pager = '';
					if (response.num_pages > 1) {
						pager = ' \
						<div class=\"center\"> \
						<table id=\"search_pager\"> \
							<tr><td>';
						if (response.page > 1)
							pager += ' \
							<div id=\"search_previous\"> \
							<a href=\"javascript:search_library('+(response.page-1)+
							');\">Previous</a> \
							</div>';

						pager += ' \
						</td><td class=\"center\"> \
						<h5>More Results</h5>';
						for ( ; start <= end; start++) {
							if (start == response.page)
								pager += '<div id=\"current_page\" class=\"bold\">' + start + '</div>';
							else pager += ' \
							<div><a href=\"javascript:search_library('
							+start+');\">' + start + '</a></div>';
						}

						pager += '</td><td>';
						if (response.page < response.num_pages)
							pager += ' \
							<div id=\"search_next\"> \
							<a href=\"javascript:search_library('
							+(response.page+1)+');\">Next</a> \
							</div>';
						pager += ' \
							</td></tr> \
							</table> \
						</div>';
					}
				}

				str = '<div class=\"right padding20_top\">'+response.saved_search+'</div>'
					+suggested+response.results+pager;
			}

			ed_show_waiting(false);
			window.location = '#results'; // jump down to see the results
			$('results').innerHTML = str;
		}
	});
}

// add commas to a number (ex. 40000 to 40,000)
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}

	return x1 + x2;
}

// print an image object
function print_image (obj) {
	if(obj.onmouseover || obj.onmouseout) {
		return " \
		  <img src=\""+obj.src+"\" id=\""+obj.id+"\" class=\"pointer\" \
		  onmouseover=\"icon_help(this, '"+obj.help+"'); "+obj.onmouseover+"\" \
		  onmouseout=\"icon_help(this); "+obj.onmouseout+"\" alt=\""+obj.alt+"\" \
		  onclick=\""+obj.onclick+"\">&nbsp;";
	}
	else {
		return " \
		  <img src=\""+obj.src+"\" id=\""+obj.id+"\" class=\"pointer\" \
		  onmouseover=\"icon_help(this, '"+obj.help+"')\" \
		  onmouseout=\"icon_help(this)\" alt=\""+obj.alt+"\" \
		  onclick=\""+obj.onclick+"\">&nbsp;";
	}
}

// select all of the 'chk' options
function select_all_options(type, chk) {
	var all = $(type+'_all').checked;
	var none = $(type+'_none');
	if (all) {
		if (none)
			none.checked = false;
		for(i = 0; i < chk.length; i++)
			chk[i].checked = true;
	}
}

// uncheck the "all" checkbox because all options are no longer selected
function uncheck_box(type, chk) {
	var all = $(type+'_all');
	var none = $(type+'_none');
	for(i = 0; i < chk.length; i++) {
		if (!chk[i].checked) {
			all.checked = false;
		}
		if (none && chk[i].checked) {
			none.checked = false;
		}
	}
}

// select none of the 'chk' options
function select_none_options(type, chk) {
	var all = $(type+'_all');
	all.checked = false;
	for(i = 0; i < chk.length; i++) {
		if (!chk[i].disabled)
			chk[i].checked = false;
	}
}

function icon_help(img, msg) {
	var top = current_mouse_y + 5;
	var left = current_mouse_x + 5;

	//Tried event.screenY, event.pageY, current_mouse_y, etc. to get the mouse position
	//to work across all the browsers. Unfortunately none of these options work across
	//the board but IE seemed to be okay with clientX and clientY.
	if (browser_name == "msie") {
		top = event.clientY + (document.documentElement.scrollTop || document.body.scrollTop) + 5;
		left = event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) + 5;
	}

	var div = document.getElementById('iconhelp');
	if (msg) {
		div.innerHTML = msg;
		div.style.top = top+'px';
		div.style.left = left+'px';
		div.style.display = "block";
	} else {
		div.style.display = "none";
	}
}

function glossary_lookup(element, term) {
	var top = current_mouse_y + 10;
	var dim = element.getDimensions();

	var div = $('glossary');
	if (div) {
		$('glossary_header').innerHTML = decodeURI(term).replace(/\+/g," ");
		$('glossary_inner').innerHTML = "";
		div.style.top = top+'px';
		div.style.display = 'block';

		new Ajax.Request("/util/ajax/glossary?term="+term,
			{
				method: "get",
				onSuccess: function(r) {
					$('glossary_inner').innerHTML = r.responseText +
						"<div class=\"button_grey30_upper margin20_top\" onclick=\"glossary_hide();\">Close</div>";
				},
				onFailure: function(r) {
					$('glossary_inner').innerHTML = "<p class=\"italic\">Could not load definition.</p>" +
						"<div class=\"button_grey30_upper margin20_top\" onclick=\"glossary_hide();\">Close</div>";
				}
			});
	}
}

function glossary_hide() {
	$('glossary').hide();
}

