var loaded = false;
var cookiedomain = '';
var helpwin = null;
 
// Determine browser type
var opera = !!(window.opera && /Opera( |\/)/i.exec(navigator.userAgent));
var op7 = !!(window.opera && /Opera( |\/)7/i.exec(navigator.userAgent));
var op8 = !!(window.opera && /Opera( |\/)8/i.exec(navigator.userAgent));
var ie = (navigator.appName == 'Microsoft Internet Explorer');
var safari = (navigator.userAgent.indexOf('Safari') >= 0);
var ff = (navigator.userAgent.indexOf('Firefox') >= 0);

// Debug mode
var debug = 1;
var missingfields = [];

var browser = navigator.userAgent;
if (browser.indexOf('MSIE') >= 0) { browser = 'ie'; }
else if (browser.indexOf('Opera') >= 0) { browser = 'opera'; }
else { browser = 'mozilla'; }

function pageLoaded () {
	loaded = true;
	topMenuInit();
}

function pageResize () {
	try { windowACResize('alert'); } catch (err) {}
	try { windowACResize('confirm'); } catch (err) {}
	try { windowACResize('suspend'); } catch (err) {}
	try { windowACResize('resume'); } catch (err) {}
	try { helpDialogueClose(); } catch (err) {}
}

function pageScroll () {
	try { windowACResize('alert'); } catch (err) {}
	try { windowACResize('confirm'); } catch (err) {}
	try { windowACResize('suspend'); } catch (err) {}
	try { windowACResize('resume'); } catch (err) {}
}

function topMenuInit () {
	if (typeof(global) == 'undefined') { global = {}; }
	if (typeof(global['tbmenu']) == 'undefined') { global['tbmenu'] = {}; }

	var tbmenu = document.getElementById('tbmenu');

	if (!tbmenu) { return; }
		
	// Find out how many menu items there are
	var tdlist = getTags('td', tbmenu);
	var alist = getTags('a', tbmenu);
	var max = alist.length;

	// Set initial top bar menu parameters
	global['tbmenu']['change'] = false;
	global['tbmenu']['animate'] = false;
	global['tbmenu']['list'] = [];
	for (var i=0; i<max; i++) {
		global['tbmenu']['list'].push({ status: 0, toggle: false });

		// Tie mouse events to menu link
		var obj = document.getElementById('menulink'+(i+1));
		addEventSimple(obj, 'mouseover', topMenuOver);
		addEventSimple(obj, 'mouseout', topMenuOut);
		if (browser != 'ie') { addEventSimple(obj, 'mousemove', topMenuOver); }
	}
}

function topMenuOver (e) {
	if (typeof(global['tbmenu']) == 'undefined') { return; }

	var event = e || window.event;
	var target = window.event ? event.srcElement : event.target;
	
	if (target.id) {
		var matches = target.id.match(/(\d+)$/);
		if (matches[1]) {
			var index = parseInt(matches[1]);

			global['tbmenu']['list'][index-1]['toggle'] = true;
			if (!global['tbmenu']['animate']) {
				global['tbmenu']['animate'] = true;
				topMenuStatus();
			}
		}
	}
}

function topMenuOut (e) {
	if (typeof(global['tbmenu']) == 'undefined') { return; }

	var event = e || window.event;
	var target = window.event ? event.srcElement : event.target;
	
	if (target.id) {
		var matches = target.id.match(/(\d+)$/);
		if (matches[1]) {
			var index = parseInt(matches[1]);

			global['tbmenu']['list'][index-1]['toggle'] = false;
			if (!global['tbmenu']['animate']) {
				global['tbmenu']['animate'] = true;
				topMenuStatus();
			}
		}
	}
}

function topMenuStatus () {
	if (typeof(global['tbmenu']) == 'undefined') { return; }
	
	global['tbmenu']['change'] = false;
	
	for (var i=0; i<global['tbmenu']['list'].length; i++) {
		if (global['tbmenu']['list'][i]['toggle']) {
			if (global['tbmenu']['list'][i]['status'] < 8) {
				if (browser == 'ie') {
					global['tbmenu']['list'][i]['status'] = 8;
				}
				else {
					global['tbmenu']['list'][i]['status']++;
				}
				global['tbmenu']['change'] = true;
			}
		}
		else {
			if (global['tbmenu']['list'][i]['status'] > 0) {
				if (browser == 'ie') {
					global['tbmenu']['list'][i]['status'] = 0;
				}
				else {
					global['tbmenu']['list'][i]['status']--;
				}
				global['tbmenu']['change'] = true;
			}
		}
	}

	if (global['tbmenu']['change']) {
		for (var i=0; i<global['tbmenu']['list'].length; i++) {
			var l = (i == 0) ? 0 : global['tbmenu']['list'][i-1]['status'];
			var r = (i == global['tbmenu']['list'].length - 1) ? 0 : global['tbmenu']['list'][i+1]['status'];
			var b = global['tbmenu']['list'][i]['status'];
			var divl = document.getElementById('menudiv'+i);
			var divr = document.getElementById('menudiv'+(i+1));
			var bar = document.getElementById('menu'+(i+1));
			divl.className = sprintf('div div%d%d', l, b);
			divr.className = sprintf('div div%d%d', b, r);
			bar.className = sprintf('bar bar%d', b);
		}
	
		if (browser == 'ie') { topMenuStatus(); }
		else { setTimeout('topMenuStatus()', 50); }
	}
	else {
		global['tbmenu']['animate'] = false;
	}
}

function changeSideBar (nocookie) {
	if (!loaded) { return; }
	
	var sidebarelement = document.getElementById('sidebar');
	var sidebarcontrol = document.getElementById('sidebarcontrol');

	if (!sidebarcontrol) { return; }

	// Sidebar is being opened
	if (sidebarcontrol.className == 'sidebarcontrolleft') {
		sidebarcontrol.className = 'sidebarcontrolright';
		elementDisplay(sidebarelement, true);

		// Open is default status for sidebar, so we clear winstatus if open
		if (!nocookie) { setWinCookie('u_global-sidebar', 0); }
	}

	// Sidebar is being closed
	else {
		sidebarcontrol.className = 'sidebarcontrolleft';
		elementDisplay(sidebarelement, false);

		// Open is default status for sidebar, so we set closed
		if (!nocookie) { setWinCookie('u_global-sidebar', 2); }
	}

	// Additional sidebar functions
	var arglist = new Array('sidebarlist');
	var args = getArgs(arglist);

	if (args && args['sidebarlist']) {
		var funcs = args['sidebarlist'].split(';');
		for (var i=0; i<funcs.length; i++) { eval(funcs[i]); }
	}

	// Update the sortbox item offset top when page structure changes (due to sidebar)
	try { sortBoxResizeAll(); } catch (err) {}
	try { sortBoxItemOffsetTopRefreshAll(); } catch (err) {}

	// Update any code boxes
	try { codeBoxRefreshAll(); } catch (err) {}

	// A delayed action to fix IE
	setTimeout('changeSideBarHighlight()', 10);

	// Hide help dialogue if it is available
	try { helpDialogueClose(); } catch (err) {}
}

function changeSideBarHighlight (status) {
	if (!loaded) return;
	
	var sidebarcontrol = document.getElementById('sidebarcontrol');
	
	if (status) {
		sidebarcontrol.style.backgroundPosition = (sidebarcontrol.className == 'sidebarcontrolleft') ? '-36px 0px' : '-12px 0px';
	}
	else {
		sidebarcontrol.style.backgroundPosition = (sidebarcontrol.className == 'sidebarcontrolleft') ? '-24px 0px' : '0px 0px';
	}
}

function changeLeftBar () {
	if (!loaded) return;
	
	var arrow = document.getElementById('leftbararrow');
	var content = document.getElementById('content');
	var leftbarelement = document.getElementById('leftbar');

	if (!arrow.style) return;

	if (arrow.src == leftbararrowright.src) {
		arrow.src = leftbararrowleft.src;
		elementDisplay(leftbarelement, true);
	}
	else {
		arrow.src = leftbararrowright.src;
		elementDisplay(leftbarelement, false);
	}
	content.setAttribute('width', '100%');
}

function changeLeftBarHighlight (status) {
	if (!loaded) return;

	var leftbarelement = document.getElementById('leftbarcontrol');

	if (status == 'on') {
		leftbarelement.className = 'leftbarcontrolon';
	}
	else {
		leftbarelement.className = 'leftbarcontrol';
	}
}

function changeImgButton (id, status) {
	if (!loaded) return;
	
	var button = document.getElementById('button'+id);

	if (button.src) {
		switch (status) {
			case 'up':
				button.src = buttonimages[id+'up'].src;
				break;
			case 'over':
				button.src = buttonimages[id+'over'].src;
				break;
			case 'down':
				button.src = buttonimages[id+'down'].src;
				break;
		}
	}
}

function changeFormButton (id, status) {
	//if (!loaded) return;
	
	var button = document.getElementById('button'+id);

	if (button && button.className) {
		switch (status) {
			case 'up':
				button.className = 'mainbutton';
				break;
			case 'over':
				button.className = 'mainbuttonover';
				break;
			case 'down':
				button.className = 'mainbuttondown';
				break;
		}
	}
}

function fixContentWindow () {
	// Hide help dialogue if it is available
	try { helpDialogueClose(); } catch (err) {}

	// Update the sortbox item offset top when page structure changes (due to sub-windows)
	try { sortBoxResizeAll(); } catch (err) {}
	try { sortBoxItemOffsetTopRefreshAll(); } catch (err) {}

	// fix for the content area
	//changeSideBar();
	//changeSideBar();
}

// defvalue is the default value for a window: 1=open; 2=closed
// type: 0 = window, 1 = subwindow, 2 = smallwindow
// nocookie: determines whether or not to store into cookie
function changeMinMaxBar (buttonid, windowid, type, defvalue, nocookie) {
	if (!loaded) return;
	
	var button = document.getElementById(buttonid);
	var winpanel = document.getElementById(windowid);

	if (button.src && winpanel.style) {
		// smallwindow
		if (type == 2) {
			// smallwindow is being opened
			if (button.src == smallbararrowdown.src) {
				button.src = smallbararrowup.src;
				elementDisplay(winpanel, true);
				if (!nocookie) {
					if (defvalue == 1) setWinCookie(windowid, 0);
					else setWinCookie(windowid, 1);
				}
			}
			// smallwindow is being closed
			else {
				button.src = smallbararrowdown.src;
				elementDisplay(winpanel, false);
				if (!nocookie) {
					if (defvalue == 2) setWinCookie(windowid, 0);
					else setWinCookie(windowid, 2);
				}
			}
		}

		// subwindow
		else if (type == 1) {
			// subwindow is being opened
			if (button.src == subbararrowdown.src) {
				button.src = subbararrowup.src;
				elementDisplay(winpanel, true);
				if (!nocookie) {
					if (defvalue == 1) setWinCookie(windowid, 0);
					else setWinCookie(windowid, 1);
				}
			}
			// subwindow is being closed
			else {
				button.src = subbararrowdown.src;
				elementDisplay(winpanel, false);
				if (!nocookie) {
					if (defvalue == 2) setWinCookie(windowid, 0);
					else setWinCookie(windowid, 2);
				}
			}
		}

		// regular window
		else {
			// window is being opened
			if (button.src == bararrowdown.src) {
				button.src = bararrowup.src;
				elementDisplay(winpanel, true);
				if (!nocookie) {
					if (defvalue == 1) setWinCookie(windowid, 0);
					else setWinCookie(windowid, 1);
				}
			}
			// window is being closed
			else {
				button.src = bararrowdown.src;
				elementDisplay(winpanel, false);
				if (!nocookie) {
					if (defvalue == 2) setWinCookie(windowid, 0);
					else setWinCookie(windowid, 2);
				}
			}
		}
	}

	fixContentWindow();

	// Update any code boxes
	try { codeBoxRefreshAll(); } catch (err) {}
}

function isWindowOpen (windowid) {
	if (!loaded) { return; }

	var winpanel = document.getElementById(windowid);
	if (winpanel) {
		return winpanel.style.display == 'none' ? false : true;
	}
	return false;
}

// COOKIE FUNCTIONS

function setCookie (name, value) {
	var expiredate = new Date();
	var fieldlist = new Array();

	expiredate.setTime(expiredate.getTime() + (2 * 365 * 24 * 3600 * 1000));

	fieldlist.push(name+'='+escape(value));
	fieldlist.push('path=/');
	fieldlist.push('domain='+cookiedomain);
	fieldlist.push('expires='+expiredate.toGMTString());

	document.cookie = fieldlist.join(';');	
}

function getCookie (name) {
	var cookieraw = document.cookie;
	if (name == '' || cookieraw.length == 0) return false;

	var locfront = cookieraw.indexOf(name+'=');
	if (locfront == -1) return false;

	var locend = cookieraw.indexOf(';', locfront);
	if (locend == -1) locend = cookieraw.length;

	locfront += name.length + 1;
	return unescape(cookieraw.substring(locfront, locend));
}

function clearCookie (name) {
	var fieldlist = new Array();

	if (getCookie(name)) {
		fieldlist.push(name+'=');
		fieldlist.push('path=/');
		fieldlist.push('domain='+cookiedomain);
		fieldlist.push('expire=Thu, 01-Jan-70 00:00:01 GMT');
		document.cookie = fieldlist.join(';');
	}
}

function setExternalCookie (name, value, def) {
	if (typeof(global) == 'undefined') { global = {}; }
	if (typeof(global['cookies']) == 'undefined') { global['cookies'] = {}; }
	if (typeof(global['cookies']['external']) == 'undefined') { global['cookies']['external'] = {}; }

	// Clear out value if equal to default value
	if (typeof(def) != 'undefined' && value == def) {
		delete global['cookies']['external'][name];
	}
	else {
		global['cookies']['external'][name] = value;
	}
	
	var freeze = freezeForCookie('external');

	setCookie('external', freeze);
}

function getExternalCookie (name) {
	thawForCookie('external', getCookie('external'));

	return global['cookies']['external'][name];
}

function freezeForCookie (index) {
	if (typeof(global) == 'undefined' || typeof(global['cookies']) == 'undefined' || typeof(global['cookies']['external']) == 'undefined') { return; }

	var values = [];
	for (var key in global['cookies'][index]) {
		values.push(key + '[[e]]' + global['cookies'][index][key]);
	}

	return values.join('[[s]]');
}

function thawForCookie (index, freeze) {
	if (typeof(global) == 'undefined') { global = {}; }
	if (typeof(global['cookies']) == 'undefined') { global['cookies'] = {}; }
	if (typeof(global['cookies']['external']) == 'undefined') { global['cookies']['external'] = {}; }
	
	var pairs = freeze ? freeze.split('[[s]]') : [];
	for (var i=0; i<pairs.length; i++) {
		var pair = pairs[0].split('[[e]]');
		global['cookies'][index][pair[0]] = pair[1];
	}
}

function readWinCookie (windowid) {
	var wincookies = document.cookie.split(';');
	for (var i=0; i<wincookies.length; i++) {
		var pair = wincookies[i].split('=');
		if (pair[0] == windowid) {
			return pair[1];
		}
	}
	return '';
}

function setWinCookie (windowid, value) {
	var cookievalue = '';
	var expiredate = new Date();
	expiredate.setTime(expiredate.getTime() + (2 * 365 * 24 * 3600 * 1000));

	if (numeric(value, false, true, false)) {
		minmaxwindows[windowid] = value;
	}
	for (var i in minmaxwindows) {
		if (minmaxwindows[i] != null) {
			cookievalue = cookievalue + i + '=' + minmaxwindows[i] + '|';
		}
	}
	cookievalue = cookievalue.substring(0, cookievalue.length-1);
	cookiedoc = 'csWindows='+cookievalue+'; path/; expires='+expiredate.toGMTString()+';';
	if (cookiedomain) { cookiedoc = cookiedoc+' domain='+cookiedomain+';'; }
	document.cookie = cookiedoc;
}

function deleteWinCookie () {
	document.cookie = 'csWindows=; path=/; domain='+cookiedomain+'; expires=Thu, 01-Jan-70 00:00:01 GMT';
}

// MESSAGE FUNCTIONS

function messageToggle (id, url) {
	var iframe = document.getElementById('frame_'+id);
	var row = document.getElementById('row_'+id);
	if (row) {
		row.style.display = row.style.display == 'none' ? '' : 'none';
		if (iframe.src.indexOf(blankpage) >= 0) { iframe.src = url; }
	}
}

function createMaskIframe (id) {
	var iframe = document.createElement('iframe');
	iframe.id = id;
	iframe.setAttribute('width', '0');
	iframe.setAttribute('height', '0');
	iframe.setAttribute('border', '0');
	iframe.setAttribute('frameborder', '0');
	iframe.setAttribute('scrolling', 'no');
	iframe.style.position = 'absolute';
	iframe.style.top = 0;
	iframe.style.left = 0;
	iframe.style.border = 'solid 0px';
	iframe.style.display = 'none';
	return iframe;
}

function loadOpener (url, leaveopen) {
	opener.location = url;
	if (!leaveopen) { window.close(); }
}

function statusAlert (winid, notice, warning) {
	if (!loaded) return;
	
	var statusbar = document.getElementById(winid+'_statusloc');
	var noticeloc = null;
	var barcopy = null;

	if (warning) {
		noticeloc = document.getElementById('warningtextloc');
		noticeloc.removeChild(noticeloc.firstChild);
		noticeloc.appendChild(document.createTextNode(notice));
		barcopy = document.getElementById('warningtemplate').cloneNode(true);
	}
	else {
		noticeloc = document.getElementById('statusbarloc');
		
		if (noticeloc.firstChild) {
			noticeloc.removeChild(noticeloc.firstChild);
		}

		noticeloc.appendChild(document.createTextNode(notice));
		barcopy = document.getElementById('statusbartemplate').cloneNode(true);
	}
	
	while (statusbar.firstChild) {
		statusbar.removeChild(statusbar.firstChild);
	}

	elementDisplay(barcopy, true);
	statusbar.appendChild(barcopy);
}

function validNumber (numb) {
	var valid = true;
	for (var i=0; i<numb.length; i++) {
		var numbchar = numb.substr(i,1);
		if (!(numbchar == '0' || numbchar == '1' || numbchar == '2' || numbchar == '3' || numbchar == '4' ||
					numbchar == '5' || numbchar == '6' || numbchar == '7' || numbchar == '8' || numbchar == '9')) {
			valid = false;
		}
	}
	return valid;
}

function strReplace (string, search, replace) {
	var s = string;
	var pos = s.indexOf(search);
	while (pos >= 0) {
		s = s.substring(0, pos) + replace + s.substring(pos+search.length);
		pos = s.indexOf(search);
	}
	return s;
}

function condCheck (cond, formname) {
	var pcond = cond;
	var matches = new Array();
	var changes = new Array();

	changes['F_V'] = 'document.'+formname+'.::FIELDNAME::.value';
	changes['F_L'] = 'document.'+formname+'.::FIELDNAME::.length';
	changes['F_C'] = 'document.'+formname+'.::FIELDNAME::.checked';
	changes['F_D'] = 'document.'+formname+'.::FIELDNAME::.disabled';
	changes['F_SV'] = 'document.'+formname+'.::FIELDNAME::.options[document.'+formname+'.::FIELDNAME::.selectedIndex].value';
	changes['F_ST'] = 'document.'+formname+'.::FIELDNAME::.options[document.'+formname+'.::FIELDNAME::.selectedIndex].text';
	changes['F_SI'] = 'document.'+formname+'.::FIELDNAME::.selectedIndex';
	changes['F_RV'] = 'radioValue(formname,"::FIELDNAME::")';
	changes['ID_V'] = 'document.getElementById("::FIELDNAME::").value';
	changes['ID_C'] = 'document.getElementById("::FIELDNAME::").checked';

	while (matches = pcond.match(/\[(F|ID)\](\w+)\[(SV|SI|ST|V|RV|C|D|L)\]/)) {
		var key = matches[1] + '_' + matches[3];
		var processed = strReplace(changes[key], '::FIELDNAME::', matches[2]);
		
		pcond = strReplace(pcond, matches[0], processed);
	}

	return eval(pcond);
}

function radioValue (formname, fieldname) {
	var radio = eval('document.'+formname+'.'+fieldname);

	for (var i=0; i<radio.length; i++) {
		if (radio[i].checked) { return radio[i].value; }
	}

	return null;
}

function errorMsgCheck (msg, formname) {
	var emsg = msg;
	var search = new Array('[F]', '[C]', '[V]', '[S1]', '[S2]', '[S3]', '[L]');
	var replace = new Array('document.'+formname+'.', '.checked', '.value', '.options[document.'+formname+'.', '.selectedIndex].value', '.selectedIndex', '.length');
	
	if (emsg.indexOf('EVAL::') == 0) {
		// cut out header EVAL::
		emsg = emsg.substr(6);

		// search and replace tags
		while (findNeedles(emsg, search)) {
			for (var i=0; i<search.length; i++) {
				if (emsg.indexOf(search[i]) >= 0) {
					var cloc = emsg.indexOf(search[i]);
					emsg = emsg.substr(0,cloc) + replace[i] + emsg.substr(cloc+search[i].length);
				}
			}
		}

		emsg = eval(emsg);
		windowAlert(emsg);
	}
	else {
		windowAlert(emsg);
	}
}

function findNeedles (haystack, searches) {
	var found = false;
	for (var i=0; i<searches.length; i++) {
		if (haystack.indexOf(searches[i]) >= 0) {
			found = true;
		}
	}

	return found;
}

function displayCheck (cond, formname, id, action) {
	var element = document.getElementById(id);
	var label = document.getElementById('label_'+id);

	if (!element && action.indexOf('eval') != 0) {
		if (debug) { missingfields.push(id); }
		return;
	}

	var cstatus = condCheck(cond, formname) ? true : false;
	
	if (action == 'show') { elementDisplay(element, cstatus); }
	else if (action == 'hide') { elementDisplay(element, !cstatus); }
	else if (action == 'check') { element.checked = cstatus ? true : false; }
	else if (action == 'uncheck') { element.checked = cstatus ? false : true; }
	else if (action == 'disable') {
		element.disabled = cstatus ? 1 : 0;
		if (label) { label.className = cstatus ? 'disabled' : ''; }
	}
	else if (action == 'disable_uncheck') {
		element.disabled = cstatus ? 1 : 0;
		if (cstatus) { element.checked = false; }
		if (label) { label.className = cstatus ? 'disabled' : ''; }
	}
	else if (action.indexOf('eval') == 0) {
		var parts = action.split(':');
		if (cstatus) { eval(parts[1]); }
	}
	else { alert(action+' is invalid action!'); }
}

function elementDisplay (element, toggle) {
	if (!element) { return; }

	if (toggle == 'auto') {
		toggle = (element.style.display == 'none') ? 1 : 0;
	}

	element.style.display = toggle ? '' : 'none';
	return;
}

function idDisplay (id, toggle) {
	var element = document.getElementById(id);
	if (element) { elementDisplay(element, toggle); }
}

function initFieldCheck (formname) {
	var count = 1;
	while (eval('document.'+formname+'.fieldcheck'+count)) {
		var docvalue = eval('document.'+formname+'.fieldcheck'+count+'.value');
		var param = docvalue.split('::');
		if (param && param.length == 4) {
			fieldchecks[param[2]] = new Array(param[0], param[1], param[3]);
			displayCheck(param[0], param[1], param[2], param[3]);
		}
		count++;
	}

	fixContentWindow();
}

function fieldCheck () {
	for (var i=0; i<fieldCheck.arguments.length; i++) {
		var param = fieldchecks[fieldCheck.arguments[i]];
		if (param && param.length == 3) {
			displayCheck(param[0], param[1], fieldCheck.arguments[i], param[2]);
		}
	}

	fixContentWindow();
}

function fieldCheckAll () {
	var arglist = new Array('formname');
	var args = getArgs(arglist);
	
	var count = 1;
	while (eval('document.'+args['formname']+'.fieldcheck'+count)) {
		var docvalue = eval('document.'+args['formname']+'.fieldcheck'+count+'.value');
		var param = docvalue.split('::');
		displayCheck(param[0], param[1], param[2], param[3]);
		count++;
	}

	fixContentWindow();
}

function Dependency (fieldname, formname, condition, show) {
	this.fieldname = fieldname;
	this.formname = formname;
	this.condition = condition;
	this.show = show;
}

function itemCompare (formname, boxname, boxindex, hiddenname, textarray, baseformat) {
	var box = eval('document.'+formname+'.'+boxname);
	var bformat = eval('document.'+formname+'.'+baseformat);

	if (boxindex >= 0 && boxindex < box.options.length) {
		var item = itemFormat(formname, hiddenname, textarray, null, true);
		var newvalue = item[1];
		var oldvalue = box.options[boxindex].value;
		var hash_new = hashCreate(newvalue);
		var hash_old = hashCreate(oldvalue);

		if (!hashCompare(hash_new, hash_old)) { return false; }
	}

	// This compares the current value to what an empty answer choice would be
	else if (boxindex < 0) {

		// For Opera 7, we just return true, as the check can't work properly.
		if (op7 || op8) { return true; }

		// This is the item format to compare the cleared fields to -- this lets
		// us determine if anything has changed.
		var saveitem = itemFormat(formname, hiddenname, textarray, null, true);
		if (bformat.value == '') {
			var saveindex = box.selectedIndex;
			itemClear(formname, hiddenname, boxname);
			var clearitem = itemFormat(formname, hiddenname, textarray, null, true);
			box.selectedIndex = saveindex;
			itemPopulate(formname, saveitem[1]);
			bformat.value = clearitem[1];
		}

		if (bformat.value != saveitem[1]) {
			return false;
		}
	}

	return true;
}

function itemReformat (formname, boxname, hiddenname, textarray) {
	var box = eval('document.'+formname+'.'+boxname);
	var cindex = box.selectedIndex;

	if (cindex >= 0 && cindex < box.options.length) {
		var item = itemFormat(formname, hiddenname, textarray, null, true);
		box.options[cindex].value = item[1];
	}
}

function itemAdd (formname, boxname, hiddenname, textarray, textvalue, itemname, emptyname, nxtfunc) {
	var box = eval('document.'+formname+'.'+boxname);
	var item = itemFormat(formname, hiddenname, textarray, emptyname);
	
	if (item) {
		var itemtext = item[0];
		if (textvalue) {
			itemtext = textvalue;
		}
		box.length++;
		box.options[box.length-1].text = itemtext;
		box.options[box.length-1].value = item[1];
		box.selectedIndex = -1;

		try { sortBoxItemAdd(boxname); } catch (err) {}
		try { sortBoxScrollDown(boxname); } catch (err) {}

		itemClear(formname, hiddenname, boxname);

		if (nxtfunc) { eval(nxtfunc); }

		return new Array(itemtext, item[1]);
	}

	return;
}

function itemModify (formname, boxname, hiddenname, textarray, textvalue, itemname, emptyname, nxtfunc) {
	var box = eval('document.'+formname+'.'+boxname);
	var boxsel = box.selectedIndex;
	var errormsg = 'Please select a';

	if (boxsel == -1) {
		if (firstVowel(itemname)) {
			errormsg = errormsg + 'n';
		}
		errormsg = errormsg + ' ' + itemname + ' first!';
		windowAlert(errormsg);
		return;
	}

	var item = itemFormat(formname, hiddenname, textarray, emptyname);

	if (item) {
		var itemtext = item[0];
		if (textvalue) {
			itemtext = textvalue;
		}
		box.options[boxsel].text = itemtext;
		box.options[boxsel].value = item[1];

		try { sortBoxItemModify(boxname); } catch (err) {}

		//itemClear(formname, hiddenname, boxname);

		if (nxtfunc) {
			eval(nxtfunc);
		}

		return new Array(itemtext, item[1]);
	}

	return;
}

function itemFormat (formname, hiddenname, textarray, emptyname, ignoreerrors) {
	var fieldlist = eval('document.'+formname+'.'+hiddenname+'.value');
	var format = new Array();

	if (fieldlist) {
		var fields = fieldlist.split('&');
		var text = '';
		var value = '';
		for (var i=0; i<fields.length; i++) {
			// parts = [
			// 1 => combo of (type[3] + fieldname)
			// 			type ([T] = text, [R] = radio, [C] = checkbox, [S] = selectbox, [M] = multi-selectbox)
			// 2 => condition (* = required else evaluated with condCheck)
			// 3 => error msg (optional)
			// ]
			var parts = fields[i].split('|');
			var type = parts[0].substr(0,3);
			var fieldname = unescape(parts[0].substr(3));
			var condition = unescape(parts[1]);
			var errormsg = parts.length > 2 ? unescape(parts[2]) : '';
			var fieldvalue = itemValue(formname, fieldname, type);
			var displayerror = false;

			// This should actually skip any text values that are empty string or
			// consist of only spaces, as that will be converted to empty string
			//if (text == '') {
			if (text.match(/^\s*$/)) {
				if (textarray) {
					var tarray = textarray.split(',');
					for (var j=0; j<tarray.length; j++) {
						if (fieldname == tarray[j]) {
							text = fieldvalue;
						}
					}
				}
			}

			if (!ignoreerrors) {
				if (condition == '*') {
					if (fieldvalue == '') { displayerror = true; }
				}
				else if (condition != '') {
					if (!condCheck(condition, formname)) { displayerror = true; }
				}
			
				if (displayerror) {
					if (errormsg != '') { errorMsgCheck(errormsg, formname); }
					return false;
				}
			}

			format.push(type + escape(fieldname) + '=' + escape(fieldvalue));
		}

		if (text == '' && emptyname) {
			text = emptyname.toUpperCase();
		}

		value = format.join('&');
		return new Array(text, value);
	}
	else {
		alert('Invalid list of fields!');
		return false;
	}
}

function itemClear (formname, hiddenname, boxname, skipfieldcheck) {
	var fieldlist = eval('document.'+formname+'.'+hiddenname+'.value');

	if (fieldlist) {
		var fields = fieldlist.split('&');
		for (var i=0; i<fields.length; i++) {
			var parts = fields[i].split('|');
			var type = parts[0].substr(0,3);
			var reset = parts.length > 3 ? true : false;
			var fieldname = unescape(parts[0].substr(3));
			var field = eval('document.'+formname+'.'+fieldname);
			if (field) {
				switch (type) {
					case '[T]':
						field.value = reset ? parts[3] : '';
						break;
					case '[R]':
						for (var j=0; j<field.length; j++) {
							field[j].checked = false;
						}
						break;
					case '[C]':
						field.checked = reset ? parts[3] : false;
						break;
					case '[S]':
						if (reset) {
							for (var j=0; j<field.length; j++) {
								if (field.options[j].value == parts[3]) {
									field.selectedIndex = j;
								}
							}
						}
						else {
							field.selectedIndex = 0;
						}
						break;
					case '[M]':
						field.length = 0;
						field.selectedIndex = -1;
						break;
					case '[P]':
						for (var j=0; j<field.length; j++) {
							field.options[j].selected = false;
						}
						break;
				}
			}
		}
		if (boxname) {
			var box = eval('document.'+formname+'.'+boxname);
			box.selectedIndex = -1;
		}
	}

	if (!skipfieldcheck) { fieldCheckAll(formname); }
}

function itemValue (formname, fieldname, type) {
	var field = eval('document.'+formname+'.'+fieldname);
	
	if (field) {
		switch (type) {
			case '[T]':
				return field.value;
				break;
			case '[R]':
				for (var i=0; i<field.length; i++) {
					if (field[i].checked) {
						return field[i].value;
					}
				}
				break;
			case '[C]':
				return field.checked ? '1' : '0';
				break;
			case '[S]':
				return (field.selectedIndex >= 0) ? field.options[field.selectedIndex].value : '';
				break;
			case '[M]':
				var format = new Array();
				for (var i=0; i<field.length; i++) {
					format.push(escape(field.options[i].text) + '=' + escape(field.options[i].value));
				}
				return format.join('&');
				break;
			case '[P]':
				var format = new Array();
				for (var i=0; i<field.length; i++) {
					if (field.options[i].selected) {
						format.push(escape(field.options[i].value));
					}
				}
				return format.join('&');
				break;
		}
	}
}

function itemMoveUp (formname, boxname, itemname, nxtfunc) {
	var box = eval('document.'+formname+'.'+boxname);
	var boxsel = box.selectedIndex;
	var newsel = boxsel - 1;
	var errormsg = 'Please select a';
	
	if (boxsel == -1) {
		if (firstVowel(itemname)) {
			errormsg = errormsg + 'n';
		}
		errormsg = errormsg + ' ' + itemname + ' first!';
		windowAlert(errormsg);
		return;
	}
	else if (boxsel == 0) {
		return;
	}

	var temptext = box.options[boxsel].text;
	var tempvalue = box.options[boxsel].value;
	box.options[boxsel].text = box.options[newsel].text;
	box.options[boxsel].value = box.options[newsel].value;
	box.options[newsel].text = temptext;
	box.options[newsel].value = tempvalue;

	box.selectedIndex = newsel;

	if (nxtfunc) {
		eval(nxtfunc);
	}
}

function itemMoveDown (formname, boxname, itemname, nxtfunc) {
	var box = eval('document.'+formname+'.'+boxname);
	var boxsel = box.selectedIndex;
	var newsel = boxsel + 1;
	var errormsg = 'Please select a';
	
	if (boxsel == -1) {
		if (firstVowel(itemname)) {
			errormsg = errormsg + 'n';
		}
		errormsg = errormsg + ' ' + itemname + ' first!';
		windowAlert(errormsg);
		return;
	}
	else if (boxsel == box.length - 1) {
		return;
	}

	var temptext = box.options[boxsel].text;
	var tempvalue = box.options[boxsel].value;
	box.options[boxsel].text = box.options[newsel].text;
	box.options[boxsel].value = box.options[newsel].value;
	box.options[newsel].text = temptext;
	box.options[newsel].value = tempvalue;
	
	box.selectedIndex = newsel;

	if (nxtfunc) { eval(nxtfunc); }
}

function itemMoveSelect (formname, frombox, tobox, itemname, nxtfunc) {
	var frombox = eval('document.'+formname+'.'+frombox);
	var tobox = eval('document.'+formname+'.'+tobox);
	var movedcount = 0;

	while (frombox.selectedIndex != -1) {
		var option = frombox.options[frombox.selectedIndex];
		var index = 0;
		if (tobox.options) { index = tobox.options.length; }

		tobox.options[index] = new Option(option.text, option.value, false, false);
		frombox.options[frombox.selectedIndex] = null;

		movedcount += 1;
	}

	if (!movedcount) {
		var errormsg = 'Please select a';
		if (firstVowel(itemname)) {
			errormsg = errormsg + 'n';
		}
		errormsg = errormsg + ' ' + itemname + ' first!';
		windowAlert(errormsg);
		return;
	}

	if (nxtfunc) { eval(nxtfunc); }
}

function itemSelect (formname, boxname, nxtfunc) {
	var box = eval('document.'+formname+'.'+boxname);
	var cindex = box.selectedIndex;
	
	if (cindex >= 0 && cindex < box.options.length) {
		var cvalue = box.options[cindex].value;
		itemPopulate(formname, cvalue);
	}

	if (nxtfunc) { eval(nxtfunc); }
}

function itemPopulate (formname, cvalue) {
	var fields = cvalue.split('&');
	for (var i=0; i<fields.length; i++) {
		var pair = fields[i].split('=');
		var pairkey = chomp(pair[0]);
		if (pairkey.length > 3) {
			var fieldkey = pairkey;
			var ftype = fieldkey.substr(0,3);
			var fieldname = fieldkey.substr(3);
			var fieldvalue = unescape(chomp(pair[1]));
			var formfield = eval('document.'+formname+'.'+fieldname);
			if (formfield) {
				switch (ftype) {
					case '[T]':
						formfield.value = fieldvalue;
						break;
					case '[R]':
						if (formfield.options) {
							for (var i=0; i<formfield.options.length; i++) {
								formfield[i].checked = (formfield[i].value == fieldvalue) ? true : false;
							}
						}
						break;
					case '[C]':
						if (fieldvalue == '1') {
							formfield.checked = true;
						}
						else {
							formfield.checked = false;
						}
						break;
					case '[S]':
						if (formfield.options) {
							for (var j=0; j<formfield.options.length; j++) {
								if (formfield.options[j].value == fieldvalue) {
									formfield.selectedIndex = j;
								}
							}
						}
						break;
					case '[M]':
						var subfields = fieldvalue.split('&');
						// clearing multi-select field
						formfield.length = 0;
						for (var j=0; j<subfields.length; j++) {
							var subpair = subfields[j].split('=');
							if (subpair[0] == '') { subpair[0] = '[BLANK ANSWER TEXT]'; }
							if (subpair[1] && subpair[1].length > 0) {
								formfield.length++;
								formfield.options[j].text = unescape(subpair[0]);
								formfield.options[j].value = unescape(subpair[1]);
							}
						}
						break;
					case '[P]':
						var subfields = fieldvalue.split('&');
						// clearing multi-select field
						for (var j=0; j<formfield.length; j++) {
							formfield.options[j].selected = false;
							for (var k=0; k<subfields.length; k++) {
								if (formfield.options[j].value == unescape(subfields[k])) {
									formfield.options[j].selected = true;
								}
							}
						}
						break;
				}
			}
		}
	}
}

function itemDelete (formname, boxname, hiddenname, itemname, nxtfunc, confirm_info) {
	var box = eval('document.'+formname+'.'+boxname);
	var boxsel = box.selectedIndex;
	var errormsg = 'Please select a';
	var success = false;
	var discard = (typeof(confirm_info) == 'undefined') ? true : confirm_info;

	if (boxsel == -1) {
		if (firstVowel(itemname)) {
			errormsg = errormsg + 'n';
		}
		errormsg = errormsg + ' ' + itemname + ' first!';
		windowAlert(errormsg);
		return false;
	}

	if (typeof(confirm_info) == 'undefined') {
		windowConfirm(sprintf('Do you wish to delete "%s"?', box.options[boxsel].text),
			sprintf("itemDelete('%s','%s','%s','%s','%s',%s);", formname, boxname, hiddenname, itemname, nxtfunc ? nxtfunc : ''));
		return false;
	}
	if (confirm_info) {
		for (var i=boxsel; i<box.options.length-1; i++) {
			box.options[i].text = box.options[i+1].text;
			box.options[i].value = box.options[i+1].value;
		}
		box.options.length--;
		try { sortBoxItemDelete(boxname); } catch (err) {}
	}
	else {
		return false;
	}

	if (nxtfunc) {
		eval(nxtfunc);
	}

	return true;
}

function itemSubmit (formname, boxname, hiddenname, send, nxtfunc) {
	var box = eval('document.'+formname+'.'+boxname);
	var hfield = eval('document.'+formname+'.'+hiddenname);
	var boxvalues = new Array();
	
	for (var i=0; i<box.options.length; i++) {
		boxvalues.push(escape(box.options[i].value));
	}
	
	hfield.value = boxvalues.join('|');

	if (nxtfunc) {
		eval(nxtfunc);
	}

	if (send) {
		eval('document.'+formname+'.submit();');
	}
}

function hashCreate (value) {
	var hash = {};
	var items = value.split('&');
	for (var i=0; i<items.length; i++) {
		var pairs = items[i].split('=');
		if (pairs.length < 2 || typeof(pairs[1]) == 'undefined') { pairs[1] = ''; } //continue; }
		if (pairs[0].indexOf('[M]') == 0 || /^\[(T|R|C|S|M)\]/.test(unescape(pairs[1]))) {
			hash[pairs[0]] = hashCreate(unescape(pairs[1]));
		}
		else {
			hash[pairs[0]] = pairs[1];
		}
	}
	return hash;
}

function hashPrint (hash, level) {
	if (typeof(hash) != 'object') { return ''; }

	var output = '';
	var spacer = '';
	level = level ? level : 0;

	for (var i=0; i<level; i++) { spacer += '   '; }
	for (var key in hash) {
		if (typeof(hash[key]) == 'object') {
			output += sprintf("%s%s => {\n%s%s}\n", spacer, key, hashPrint(hash[key], level+1), spacer);
		}
		else {
			output += sprintf("%s%s => %s\n", spacer, key, hash[key]);
		}
	}
	if (level) { return output; }
	else { alert(output); }
}

function hashCompare (hash1, hash2, ordercheck) {
	if (!hash1 || !hash2) { return false; }
	if (ordercheck) {
		var keyarr1 = [];
		var keyarr2 = [];
		for (var key in hash1) { keyarr1.push(key); }
		for (var key in hash2) { keyarr2.push(key); }
		if (keyarr1.length != keyarr2.length) { return false; }
		else {
			for (var i=0; i<keyarr1.length; i++) {
				if (keyarr1[i] != keyarr2[i]) { return false; }
			}
		}
	}
	for (var key in hash1) {
		var order = (key.indexOf('[M]') == 0) ? true : false;
		if (typeof(hash1[key]) == 'object') {
			if (!hashCompare(hash1[key], hash2[key], order)) { return false; }
		}
		else if (typeof(hash1[key]) != 'undefined' && hash1[key] != '' && hash1[key] != hash2[key]) { return false; }
	}
	for (var key in hash2) {
		var order = (key.indexOf('[M]') == 0) ? true : false;
		if (typeof(hash2[key]) == 'object') {
			if (!hashCompare(hash1[key], hash2[key], order)) { return false; }
		}
		else if (typeof(hash2[key]) != 'undefined' && hash2[key] != '' && hash1[key] != hash2[key]) { return false; }
	}
	return true;
}

var submitted = false;

function submitOnce (formname) {
	var form = eval('document.'+formname);
	if (form && !submitted) {
		submitted = true;
		form.submit();
	}
}

function toggleDisplay (windowid, defvalue) {
	var obj = document.getElementById(windowid);

	if (obj && obj.style) {
		if (obj.style.display == 'none') {
			elementDisplay(obj, true);
			if (defvalue == 1) setWinCookie(windowid, 0);
			else setWinCookie(windowid, 1);
		}
		else {
			elementDisplay(obj, false);
			if (defvalue == 2) setWinCookie(windowid, 0);
			else setWinCookie(windowid, 2);
		}
	}

	fixContentWindow();
}

function firstVowel (text) {
	if (text) {
		var chr = text.charAt(0);
		if (chr == 'a' || chr == 'e' || chr == 'i' || chr == 'o' || chr == 'u' ||
				chr == 'A' || chr == 'E' || chr == 'I' || chr == 'O' || chr == 'U') {
			return true;
		}
	}
	return false;
}

function getFieldValue (stringvalue, name) {
	var fields = stringvalue.split('&');

	for (var i=0; i<fields.length; i++) {
		var parts = fields[i].split('=');
		var type = parts[0].substr(0,3);
		var fieldname = unescape(parts[0].substr(3));
		var fieldvalue = unescape(parts[1]);
		
		if (fieldname == name) {
			return fieldvalue;
		}
	}

	return false;
}

function setFieldValue (stringvalue, name, value) {
	var fields = stringvalue.split('&');
	var format = new Array();

	for (var i=0; i<fields.length; i++) {
		var parts = fields[i].split('=');
		var type = parts[0].substr(0,3);
		var fieldname = unescape(parts[0].substr(3));
		var fieldvalue = unescape(parts[1]);

		if (fieldname == name) {
			fieldvalue = value;
		}
		
		format.push(type + escape(fieldname) + '=' + escape(fieldvalue));
	}

	return format.join('&');
}

function getArgs (arglist, prefix, doc) {
	var args = new Array();
	var docname = doc ? doc : 'document';
	var forminfo = eval(docname+'.forminfo');

	if (!forminfo) { return; }

	for (var i=0; i<arglist.length; i++) {
		// Attempts to pull from prefix + arglist[i], but if it fails, it pulls from arglist[i]
		var argname = prefix ? prefix + arglist[i] : arglist[i];
		var argitem = eval(docname+'.forminfo.'+argname);
		if (!argitem) { argitem = eval(docname+'.forminfo.'+arglist[i]); }
		if (argitem) { args[arglist[i]] = argitem.value; }
	}

	return args;
}

function validid (string) {
	return /^\s*[a-zA-Z][a-zA-Z_]*\s*$/.test(string);
}

function alphanumeric (string) {
	return /^\s*[a-zA-Z][a-zA-Z0-9]*\s*$/.test(string);
}

function alphaonly (string) {
	return /^[a-zA-Z]*$/.test(string);
}

function langcode (string) {
	return /^[a-zA-Z\-,; ]+$/.test(string);
}

function numeric (string, negative, zero, decimal) {
	if (!zero && string == '0') { return false; }
	
	var regexpstr = '';
	regexpstr = decimal ? '(\\d*\\.?\\d+|\\d+\\.?\\d*)' : '\\d+';
	regexpstr = negative ? '\\-?' + regexpstr : regexpstr;
	// Allow extra spaces at front/end (they will be removed by perl)
	regexpstr = '^\\s*' + regexpstr + '\\s*$';
	var regexpobj = new RegExp(regexpstr);
	
	return regexpobj.test(string);
}

function padnumber (numstring, digits, padstr) {
	var dcount = numstring.length;
	var output = '';
	var pad = padstr ? padstr : '0';
	while (digits > dcount && dcount > 0 && digits - dcount > 0) {
		output = output + pad;
		dcount--;
	}
	return output + numstring;
}

function toggleDisabled (formname, fieldname) {
	var disabled = eval('document.'+formname+'.'+fieldname+'.checked') ? 0 : 1;
	for (var i=2; i<toggleDisabled.arguments.length; i++) {
		eval('document.'+formname+'.'+toggleDisabled.arguments[i]+'.disabled='+disabled);
	}
}

function toggleBox (formname, fieldname, ischecked) {
	var box = eval('document.'+formname+'.'+fieldname);
	box.checked = ischecked;
}

function getMousePosX (e) {
	var event = e ? e : window.event;
	if (event.pageX) { return event.pageX; }
	else if (event.clientX + document.body.scrollLeft) { return event.clientX + document.body.scrollLeft; }
	return 0;
}

function getMousePosY (e) {
	var event = e ? e : window.event;
	if (event.pageY) { return event.pageY; }
	else if (event.clientY + document.body.scrollTop) { return event.clientY + document.body.scrollTop; }
	return 0;
}

function findPosX (obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY (obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function childResizeIframe (id, min, max) {
	var marker = document.getElementById('marker');
	
	if (!marker) { return; }

	// mw 06/27/07
	// size was originally findPosY() - 1, but I found it was cutting off a pixel in Firefox
	var size = findPosY(marker);

	if (min && size < min) { size = min; }
	if (max && size > max) { size = max; }
	if (parent) { parent.parentResizeIframe(id, size); }
}

function parentResizeIframe (id, size) {
	var iframe = document.getElementById(id);
	if (iframe && iframe.height != size) {
		iframe.height = size;
		fixContentWindow();
	}
}

function parentToChildResizeIframe (id, min, max) {
	if (!loaded) { return; }
	var iframe = this.frames[id];
	if (iframe) {
		iframe.childResizeIframe(id, min, max);
	}
}

function previewResizeIframe (id, min, max) {
	var iframe = document.getElementById(id);
	var frame = this.frames[id];
	var ibody = frame ? frame.document.body : null;

	if (!ibody) { return; }
	// This attempts to calculate the height of the frame content.  By default,
	// it will take the larger of the scrollHeight and offsetHeight. This means,
	// however, that the size can never decrease. To account for this, we compare
	// both variables to clientHeight. If clientHeight matches on and not the
	// other, then we use the non-matching height (as clientHeight usually --
	// we hope always -- returns the height of the iframe window)
	var size = ibody.scrollHeight > ibody.offsetHeight ? ibody.scrollHeight : ibody.offsetHeight;
	if (ibody.clientHeight == ibody.scrollHeight &&
	    ibody.clientHeight != ibody.offsetHeight) {
		size = ibody.offsetHeight;
	}
	else if (ibody.clientHeight != ibody.scrollHeight &&
	         ibody.clientHeight == ibody.offsetHeight) {
		size = ibody.scrollHeight;
	}
	
	if (min && size < min) { size = min; }
	if (max && size > max) { size = max; }
	iframe.height = size;

	fixContentWindow();
}

function exampleResizeIframe (id, size) {
	if (typeof(global['example_sizes']) == 'undefined') { global['example_sizes'] = []; }

	var example_id = id.replace(/[^a-zA-Z0-9]/g, 'x');
	var iframe = document.getElementById(id);

	// Pull the size from cache first, if not there, calculate it
	if (global['example_sizes'][example_id]) {
		size = global['example_sizes'][example_id];
	}
	else {
		var frame = this.frames[id];
		var ibody = frame && frame.document ? frame.document.body : null;

		if (ibody) {
			// This attempts to calculate the height of the frame content.  By default,
			// it will take the larger of the scrollHeight and offsetHeight. This means,
			// however, that the size can never decrease. To account for this, we compare
			// both variables to clientHeight. If clientHeight matches on and not the
			// other, then we use the non-matching height (as clientHeight usually --
			// we hope always -- returns the height of the iframe window)
			size = ibody.scrollHeight > ibody.offsetHeight ? ibody.scrollHeight : ibody.offsetHeight;
			if (ibody.clientHeight == ibody.scrollHeight &&
			    ibody.clientHeight != ibody.offsetHeight) {
				size = ibody.offsetHeight;
			}
			else if (ibody.clientHeight != ibody.scrollHeight &&
			         ibody.clientHeight == ibody.offsetHeight) {
				size = ibody.scrollHeight;
			}

			this.frames[id] = null;
		}

		// Cache iframe height size
		global['example_sizes'][example_id] = size;
	}

	// Set the iframe size
	iframe.height = size;

	// Call again to re-adjust the left and right boundary heights
	helpDialogueShow();
}

var blankpage = '/blank.html';

function toggleIframeWindow (iframeid, url, arrowid, rowarrowid) {
	var iframe = document.getElementById(iframeid);
	var arrow = document.getElementById(arrowid);
	var rowarrow = document.getElementById(rowarrowid);

	if (iframe && arrow && arrow.src == subbararrowup.src && iframe.src.indexOf(blankpage) >= 0) {
		if (!rowarrow || rowarrow.src == displayup.src) {
			iframe.src = url;
		}
	}
	
	fixContentWindow();
}

function num2hex (num) {
	num = parseInt(num);
	if (num >= 0 && num <= 9) {
		return num;
	}
	else {
		switch (num) {
			case 10: return 'A';
			case 11: return 'B';
			case 12: return 'C';
			case 13: return 'D';
			case 14: return 'E';
			case 15: return 'F';
		}
	}
	return 0;
}

function hex2num (hex) {
	if (hex >= 0 && hex <= 9) {
		return parseInt(hex);
	}
	else {
		switch (hex.toUpperCase()) {
			case 'A': return 10;
			case 'B': return 11;
			case 'C': return 12;
			case 'D': return 13;
			case 'E': return 14;
			case 'F': return 15;
		}
	}
	return 0;
}

function rgb2hex (rgb) {
	var hex = '#';
	for (var i=0; i<rgb.length; i++) {
		if (rgb[i] < 0) { rgb[i] = 0; }
		if (rgb[i] > 255) { rgb[i] = 255; }
		var hex1 = num2hex(Math.floor(rgb[i]/16));
		var hex2 = num2hex(rgb[i]%16);
		hex = hex + hex1 + hex2;
	}

	return hex;
}

function hex2rgb (hex) {
	if (!hex.match(/^\#[0-9A-Fa-f]{6}$/)) { return; }
	hex = hex.substring(1);
	
	var rgb = new Array(hex.substring(0,2), hex.substring(2,4), hex.substring(4,6));
	
	for (var i=0; i<rgb.length; i++) {
		var digit1 = rgb[i].substring(0,1);
		var digit2 = rgb[i].substring(1,2);
		rgb[i] = hex2num(digit1) * 16 + hex2num(digit2);
	}

	return rgb;
}

function rad2deg (rad) {
	return (rad / Math.PI) * 180;
}

function deg2rad (deg) {
	return (deg / 180) * Math.PI; 
}

function refreshCountdown () {
	var refresh = document.getElementById('refresh_countdown');
	if (refresh) {
		refsecs = parseInt(refresh.innerHTML) - 1;

		if (refsecs > 0) {
			refresh.innerHTML = refsecs;
			setTimeout('refreshCountdown()', 1000);
		}
	}
}

// This method can be used to simply set any select box to a specific value.
// Useful for updating things onload when a browser remembered incorrect value
function selectOption (formname, boxname, value) {
	var box = eval('document.'+formname+'.'+boxname);
	for (var i = 0; i < box.options.length; i++) {
		if (box.options[i].value == value) {
			box.selectedIndex = i;
			break;
		}
	}
}

function loadURL (url) {
	this.location = url;
}

function clearChildNodes (node) {
	while (node.childNodes.length) {
		if (node.firstChild.childNodes.length) {
			clearChildNodes(node.firstChild);
		}
		node.removeChild(node.firstChild);
	}
}

function stripWhiteSpace (node) {
	if (!node) { return; }
	for (var i=0; i<node.childNodes.length; i++) {
		// Stripping the white spaces and repeat for each sub node (unless it's a leaf node)
		if (node.childNodes[i].nodeName == '#text' && node.childNodes[i].nodeValue.match(/^\s*$/) &&
				node.childNodes.length > 1) {
			node.removeChild(node.childNodes[i]);
		}
		stripWhiteSpace(node.childNodes[i]);
	}
}

function getTags (tagname, obj) {
	if (!obj) { return []; }
	
	var list = [];
	for (var i=0; i<obj.childNodes.length; i++) {
		if (obj.childNodes[i].nodeName.toLowerCase() == tagname.toLowerCase()) {
			list.push(obj.childNodes[i]);
		}
		if (obj.childNodes[i].childNodes.length) {
			var tlist = getTags(tagname, obj.childNodes[i]);
			for (var j=0; j<tlist.length; j++) {
				list.push(tlist[j]);
			}
		}
	}
	return list;
}

function surveyConditionChange(qeditorsortbox) {
	document.editor.editconditions.value = 1;

	if (qeditorsortbox) {
		var args = getArgs(['prefixes']);
		var prefixes = args['prefixes'] ? args['prefixes'].split('|') : new Array(null);

		for (var i=0; i<prefixes.length; i++) {
			var sargs = getArgs(['boxname','savename'], prefixes[i]);

			// Some questions don't have a boxname, like content types or textfield
			if (sargs['boxname'] != undefined) {
				answerSubmit('document', 'editor', sargs['boxname'], sargs['savename'], true);
			}
		}
	}

	document.editor.submit();
}

function surveyLoopChange() {
	var sbox = document.editor.loop_trigger_qid;
	var selectedopt = sbox.options[sbox.selectedIndex];

	if (!(' ' + selectedopt.className + ' ').match(' invalidopt ')) {
		document.editor.editloop.value = 1;
		document.editor.submit();
	}
}

function logicToggleArrow(arrowid, rowid) {
	var arrow = document.getElementById(arrowid);
	var tablerow = document.getElementById(rowid);

	var status = arrow.src.match(/(white|black)arrow(right|down)/);
	if (status) {
		if (status[1] == 'white') {
			if (status[2] == 'right') {
				var newarrow = new Image();
				newarrow.src = "/images/whitearrowdown.png";
				arrow.src = newarrow.src;
			}
			else {
				var newarrow = new Image();
				newarrow.src = "/images/whitearrowright.png";
				arrow.src = newarrow.src;
			}
		}
		else {
			if (status[2] == 'right') {
				var newarrow = new Image();
				newarrow.src = "/images/blackarrowdown.png";
				arrow.src = newarrow.src;
			}
			else {
				var newarrow = new Image();
				newarrow.src = "/images/blackarrowright.png";
				arrow.src = newarrow.src;
			}
		}
	}
}

function loadTemporaryWindowStatus() {
	for (var i=0; i<arguments.length; i+=2) {
		setWinCookie(arguments[i], arguments[i+1]);
	}
}

function showTTError(idname, linktype) {
	var elemlink = document.getElementById(idname + '_ttlink');

	if (!linktype) { linktype = 'Error'; }

	var elem = document.getElementById(idname + '_tt');
	if (elem.style.display != '') {
		elem.style.display = '';
		elemlink.innerHTML = 'Hide ' + linktype;
	}
	else {
		elem.style.display = 'none;';
		elemlink.innerHTML = 'Show ' + linktype;
	}
}

// BASIC Functions

function chomp (str) {
	str = str.replace(/^\s+/, '');
	str = str.replace(/\s+$/, '');
	return str;
}

function sprintf () {
	var format = arguments[0];
	var pattern = /%(s|d)/;
	var match = format.search(pattern);
	var count = 1;
	while (match >= 0 && typeof(arguments[count]) != 'undefined') {
		var key = format.substr(match, 2);
		var value = arguments[count];
		if (key == '%d') { value = parseInt(value); }
		else if (key == '%s') { value = typeof(value) == 'undefined' ? '' : value.toString(); }
		format = format.substr(0, match) + value + format.substr(match+2);
		match = format.search(pattern);
		count++;
	}
	return format;
}

function debugAlert () {
	if (missingfields.length) {
		var debug_message = "Missing Field Check IDs:\n";
		for (var i=0; i<missingfields.length; i++) {
			debug_message = debug_message + missingfields[i] + "\n";
		}
		windowAlert(debug_message);
	}
}

function dump (obj) {
	var output = '';
	for (key in obj) {
		output = output + sprintf("%s => %s\n", key, obj[key]);
	}
	return output;
}

function screenWidth () {
	return parseInt(ie ? document.body.clientWidth : window.innerWidth);
}

function screenHeight () {
	return parseInt(ie ? document.body.clientHeight : window.innerHeight);
}

function mouseMoveEvents (e) {
	try { sortBoxMouseMove(e); } catch (err) {}
}

function mouseUpEvents (e) {
	try { sortBoxMouseUp(e); } catch (err) {}
	try { cpMouseUp(e); } catch (err) {}
	try { bigButtonMouseUp(e); } catch (err) {}
	try { questionButtonMouseUp(e); } catch (err) {}
}

function addEventSimple (obj, evt, fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt, fn, false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt, fn);
}

function removeEventSimple (obj, evt, fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt, fn, false);
	else if (obj.detachEvent)
		obj.detachEvent('on'+evt, fn);
}

// XML HTTP REQUEST Functions

function getXHRObject () {
	// fetch the XML Http Request object
	if (window.ActiveXObject) { return new ActiveXObject('Microsoft.XMLHTTP'); }
	else if (window.XMLHttpRequest) { return new XMLHttpRequest(); }
	return;
}

function loadXHRObject (index) {
	if (typeof(global['xhr']) == 'undefined') { global['xhr'] = {}; }
	if (typeof(global['xhr'][index]) == 'undefined') { global['xhr'][index] = getXHRObject(); }
}
