var form = document.mainForm;
var cgiLoc="http://maximus.ravecore.com/cgi-bin/view.cgi";

function getIndex(elem) {
	if (elem.selectedIndex > -1) return elem.selectedIndex;
	else return elem.length - 1;
}

function addOption(obj, txt, val) {
	with(form) {
		if(!obj.begin) {
			obj[0] = null;
			obj.begin = true;
		}
		var len = obj.length;
		var ndx = getIndex(obj);
		for (var i = len - 1; i > ndx; i--)
			if (obj[i])
				obj[i+1] = new Option(obj[i].text, obj[i].value);
		obj[ndx+1] = new Option(txt, val);
		obj.selectedIndex = ndx+1;
	}
}

function repOption(obj, txt, val) {
	with(form) {
		if(!obj.begin) {
			obj.begin = true;
		}
		var ndx = getIndex(obj);
		if (ndx > -1) obj[ndx] = new Option(txt, val);
		obj.selectedIndex = ndx;
	}
}

function edtOption(obj, txt, val) {
	// obj = source element
	// txt = [string_manipulation, delimiter, target_element1 [, ... target_elementN]]
	// val = [string_manipulation, delimiter, target_element1 [, ... target_elementN]]
	with(form) {
		var ndx = getIndex(obj);
		if (obj.begin&&obj.length>0) {
			for(var j = 0; j < 2; j++) {
				var arr = !j?txt:val;
				if(arr) {
					var theArr = eval('obj[ndx].'+txt[0]+'.split(arr[1])');
					for(var i = 2; i < arr.length; i++) {
						if(elements[arr[i]].type == "text") elements[arr[i]].value = theArr[i-2]?theArr[i-2]:'';
						else if(elements[arr[i]].options) {
							if(!theArr[i-2]) theArr[i-2] = 0;
							if(!isNaN(theArr[i-2]))elements[arr[i]].selectedIndex = theArr[i-2];
							else {
								for(var j = 0; j < elements[arr[i]].length; j++)
									if(elements[arr[i]][j].text==theArr[i-2])elements[arr[i]].selectedIndex = j;
							}
						}
					}
				}
			}
		}
	}
}

function delOption(obj) {
	with(form) {
		var ndx = getIndex(obj);
		if (obj.length > 1) {
			for(var i = ndx; i < obj.length-1; i++)
				obj[i] = new Option(obj[i+1].text, obj[i+1].value);
			obj[obj.length-1] = null;
		}
		else if (ndx > -1)
			obj[ndx] = null;
		obj.selectedIndex = (ndx > obj.length-1)? ndx-1 : ndx
	}
}

function movOption(obj, n) {
	with(form) {
		var ndx = getIndex(obj);
		if (ndx+n > -1 && obj[ndx+n]) {
			var theTxt = obj[ndx].text;
			var theVal = obj[ndx].value;
			obj[ndx] = new Option(obj[ndx+n].text, obj[ndx+n].value);
			obj[ndx+n] = new Option(theTxt, theVal);
			obj.selectedIndex = ndx+n;
		}
	}
}

function handleKeys(obj, e) {
	with(form) {
		var key = e.keyCode
		if (key == 104 || key == 98) movOption(obj, ((key == 104)?-1:1))
		if (key == 110) delOption(obj)
		if (key == 107) {keyAdd(obj)}
		if (key == 96) {keyRep(obj)}
	}
}