// SpectrumLibrary.js

function numberOfRowsDisplayed(table) 
{
	if (table.tagName != 'TABLE')
		return (-1);
	var j = 0;
	for (var i = 0; i < table.rows.length; i++) {
		if (table.rows[i].style.display != 'none')
			j++;
	}
	return (j);
}

var oIFramePopup = window.createPopup();

globalMouseRestrictions(false);

function globalMouseRestrictions(boolFlag) {
	if (boolFlag == true) {
		document.oncontextmenu = oncontextmenuDocument;
		document.onmousedown = onmousedownDocument;
		document.ondragstart = ondragstartDocument;
		document.onselectstart = onselectstartDocument;
	}
}

function oncontextmenuDocument() {
	window.event.returnValue = false;
	//"return false"&gt;
	alert('This feature is not available on this site.');
}

function onmousedownDocument() {
	if (window.event.button == 2) {
	window.event.returnValue = false;
	//oncontextmenu="alert('This feature ... blah');return false;"&gt;
		alert('This feature is not available on this site.');
	}
}

function ondragstartDocument() {
	with (window.event) {
		if (srcElement.type) {
			with (window.event.srcElement) {
				if (type == 'text' || type == 'textarea') {
					returnValue = true;
					return;
				}
			}
		}
		returnValue = false;
	}
}

function onselectstartDocument() {
	with (window.event) {
		if (srcElement.type) {
			with (window.event.srcElement) {
				if (type == 'text' || type == 'textarea') {
					returnValue = true;
					return;
				}
			}
		}
		returnValue = false;
	}
}

// style expressions
var themeDense = '#CC0066'; // expression(themeDense)
var themeMidLight = '#FFA4BB'; //expression(themeMidLight)
var themeLight = '#EEDDFF'; // expression(themeLight)

function setInformationSummary(theElement, theText, boolAppendOrReplace) {
	/*
	var tmpTxt = '';
	var ist = top.informationSummaryText + '';
	if (boolAppendOrReplace == REPLACE) {
		tmpTxt = ist.substring(0, allIfNotFound(ist.lastIndexOf('~'), ist));
		top.informationSummaryText = theText;
	} else if (boolAppendOrReplace == ADD) {
		tmpTxt = ist.substring(0, allIfNotFound(ist.lastIndexOf('~'), ist));
		top.informationSummaryText += tmpTxt + '~' + theText;
	} else if (boolAppendOrReplace == APPENDIX) {
		tmpTxt = ist.substring(0, allIfNotFound(ist.lastIndexOf('~'), ist));
		top.informationSummaryText += tmpTxt + '^' + theText;
	} else if (boolAppendOrReplace == REMOVE_APPENDIX) {
		top.informationSummaryText += ist.substring(0, allIfNotFound(ist.indexOf('^'), ist));
	}
	var text = theElement.id + ' = ' + getElementVal(theElement) +':\n';
	alert(text + '\n' + top.informationSummaryText);
	function allIfNotFound(idx, ist) {
		return (idx == -1) ? ist.length : idx;
	}
	*/
}

function showCallee(thecaller) {
	if (event.type != "load") {
		//alert('caller= ' + showCallee.caller.caller);
		//alert((showCallee.caller.arguments.callee == null) ? '' : showCallee.caller.arguments.callee);
	}
}

function show() {
	//alert('window.event.type = ' + window.event.type + ', window.event.returnValue = ' + window.event.returnValue);
	window.event.srcElement.fireEvent("onmouseout");
	window.event.returnValue = false;
}

function getPersonID() {
	if (! top.document.form1.PersonID) {
		return 0;
	}
	return (top.document.form1.PersonID.value > 0) ? top.document.form1.PersonID.value : 0;
}

function onclickPopup(id, h) {
    var oPopupBody = oIFramePopup.document.body;
	oPopupBody.style.backgroundColor = "lightyellow";
	oPopupBody.style.border = "solid black 1px";    
    oPopupBody.innerHTML = "Display some <B>HTML</B> here.";
	oPopupBody.innerHTML = document.getElementById(id).innerHTML;
    oIFramePopup.show(-200, -h, 200, h, event.srcElement);
}

function withDrawnRegistrationConsentBehaviour(el) {
	displayServiceUserName();
	var defV = getElementDefaultVal(el);
	var newV = getElementVal(el);
	var yes = '3', no = '2', dk = '1';
	var msg = '';
	//alert('defV = ' + defV + ' newV = ' +newV)
	if (defV != newV) {
		setElementDefault(el, newV);
	// Yes to No
	// Yes to Not known
		// We will have to offer a confirmation and explanaton and ensure deletion if the change is confirmed.
		if ((defV == yes && newV == no) || (defV == yes && newV == dk)) {
			msg  = 'No information can be held without the consent of the Young Person. \n';
			msg += 'Any information in this section will be deleted. \n\n';
			alert(msg);
			setDisplay('none', ['ButtonsTable']);
			leaveForm();
		}
	// No to Not Known
	// Not known to No
		// We can just display a message that says no infromation can be added without consent
		else if ((defV == no && newV == dk) || (defV == dk && newV == no)) {
			alert('No information can be recorded without the consent of the Young Person.');
			setDisplay('none', ['ButtonsTable']);
		} else {
	// Not known to Yes
	// No to Yes
			setDisplay('', ['ButtonsTable']);
		}
	}
}

function withDrawnConsentBehaviour(el) {
	var defV = getElementDefaultVal(el);
	var newV = getElementVal(el);
	var yes = '3', no = '2', dk = '1';
	var msg = '';
	switch(newV) {
		case '1':
			setDisplay('none', ['ButtonsTable']);
			break;
		case '2':
			setDisplay('none', ['ButtonsTable']);
			break;
		case '3':
			setDisplay('', ['ButtonsTable']);
			break;
		default:
			setDisplay('none', ['ButtonsTable']);
			break;
	}
	if (defV != newV) {
		setElementDefault(el, newV);
	// Yes to No
	// Yes to Not known
		// We will have to offer a confirmation and explanaton and ensure deletion if the change is confirmed.
		if ((defV == yes && newV == no) || (defV == yes && newV == dk)) {
			msg  = 'No information can be held without the agreement of the Young Person. \n';
			msg += 'Any information in this section will be deleted. \n\n';
			msg += 'Click \'OK\' to allow the information to be deleted\n';
			msg += 'or\n';
			msg += 'Click \'Cancel\'.';
			if (confirm(msg)) {
				document.forms[0].WithdrawnConsentButton.click();
				//document.forms[0].SaveButton.click();
				//document.forms[0].submit();
			} else {
				window.location.reload();
			}
		}
	// No to Not Known
	// Not known to No
		// We can just display a message that says no information can be added without the Service User's consent
		else if ((defV == no && newV == dk) || (defV == dk && newV == no)) {
			alert('No information can be recorded without the agreement of the Young Person.');
			setDisplay('none', ['ButtonsTable']);
		} else {
	// Not known to Yes
	// No to Yes
			//setDisplay('', ['ButtonsTable']);
		}
	}
	return true;
}

function addEventHandler(control, id) {
	// Generic function for setting up profile forms
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
        var i;
        for (i = 0; i < control.length; i++) {
            var inner = control[i];
            if (typeof(inner.value) == "string") {
                addEventHandler(inner, id);
            } 
        }
        return;
    }
    else if (control.tagName != "INPUT" && control.tagName != "TEXTAREA" && control.tagName != "SELECT") {
        var i;
        for (i = 0; i < control.children.length; i++) {
            addEventHandler(control.children[i], id);
        }
        return;
    }
    else {
		var ev;
		if (control.type == "radio" || control.type == "checkbox") {
			ev = control.onclick;
		} else {
			ev = control.onchange;
		}
		if (typeof(ev) == "function" ) {
			ev = ev.toString();
			ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
		} else {
			ev = "";
		}
		//var func = new Function("ValidatorOnChange(); " + ev);
		if (control.type == "radio" || control.type == "checkbox") {
			var func = new Function("onclick" + id + "(); " + ev);
			control.onclick = func;
		} else {
			var func = new Function("onchange" + id + "(); " + ev);
			control.onchange = func;
		}
	}
}

function getEventRow(tbl) {
	for (var i=0; i<tbl.rows.length; i++) {
		if (tbl.rows(i).contains(event.srcElement))
			return tbl.rows(i);
	}
}

function getEventRowIndex(tbl) {
	for (var i=0; i<tbl.rows.length; i++) {
		if (tbl.rows(i).contains(event.srcElement))
			return i;
	}
}

function getEventCellIndex(tr) {
	for (var i=0; i<tr.cells.length; i++) {
		if (tr.cells(i).contains(event.srcElement))
			return i;
	}
}

function getEl(strElementId) {
	return (!isBlank(strElementId)) ? document.getElementById(strElementId) : null;
}

function populateList(targetListId, sourceListid) {
	var debug = 'Degug/n';
	debug += targetListId + ' ' + sourceListid + '\n';
	var targ = document.getElementById(targetListId);
	var sourc = document.getElementById(sourceListid);
	var selectedValue = getElementVal(targ);
	var i = 0;
	var newOp;
	debug += 'isBlank(targ) = ' + isBlank(targ) + ', isBlank(sourc) = ' + isBlank(sourc) + '\n\n';
	if (!isBlank(targ) && !isBlank(sourc)) {
		targ.options.length = 0;
		for (i = 0; i < sourc.options.length; i++) {
			newOp = document.createElement('<OPTION>');
			targ.options.add(newOp);
			newOp.value = sourc.options[i].value;
			newOp.text = sourc.options[i].text;
			debug += 'opt val =' + sourc.options[i].value + ' text = ' + sourc.options[i].text + '\n';
		}
	}
	var setToDefault = true;
	setElementDefault(targ, selectedValue, setToDefault);
	//alert(debug);
}

function doOptionFiltering(arrIds, arrVals, savedOptions) {
	var newOption;
	for (i=0; i<arrIds.length;i++) {
		if (document.getElementById(arrIds[i])) {
			with (document.getElementById(arrIds[i])) {
				options.length = 0;
				newOption = document.createElement('<OPTION>');
				options.add(newOption);
				newOption.value = "0";
				newOption.text = "Select...";
				newOption.setAttribute("optionfilter", "0");
				for (var j = 0; j < savedOptions.options.length; j++) {
					if (parseInt(savedOptions.options[j][2], 10) == parseInt(arrVals[i], 10)) {
						newOption = document.createElement('<OPTION>');
						options.add(newOption);
						newOption.value = savedOptions.options[j][0]; // value
						newOption.text = savedOptions.options[j][1]; // text;
						newOption.setAttribute("optionfilter", savedOptions.options[j][2]); // optionfilter
					}
				}
			}
		}
	}
}

/*
function growElementHeight
Created 12 November 2003 by Gareth Lloyd
parameters name: type (required or optional) - description.
el: object (required) - DOM reference of the HTML element to grow in height NOTE the element must have an id property
inc: integer (required) - the number of pixels to grow by
limit: integer (required) - the maximum number of pixels to grow to
onTermination: string or null (required) - script code to evaluate when limit is reached
fq: integer (required)

Example usage:
growElementHeight(document.all.MessageCentreDIV, 2, Math.floor(MessageCentre.clientHeight / 2), 'scrollMessageCentre()', 10)
Note use of Math.floor to ensure that third param is an integer
*/
function growElementHeight(el, inc, limit, onTermination, fq) {
	if (! (limit.constructor == Number)) {
		return;
	}
	var pxH = el.style.pixelHeight;
	if (pxH < limit) {
		if ((pxH + inc) < limit) {
			el.style.pixelHeight = pxH + inc;
			if (onTermination) {
				var tmo2 = setTimeout('growElementHeight(document.all.' + el.id + ', ' + inc + ', ' + limit + ', "' + onTermination + '", ' + fq + ')', fq);
			} else {
				var tmo2 = setTimeout('growElementHeight(document.all.' + el.id + ', ' + inc + ', ' + limit + ', null, ' + fq + ')', fq);
			}
		} else {
			el.style.pixelHeight = limit;
			eval(onTermination);
		}
	}
}
function shrinkElementHeight(el, inc, limit, onTermination, fq) {
	if (! (limit.constructor == Number)) {
		return;
	}
	var pxH = el.style.pixelHeight;
	if (pxH >= limit) {
		if ((pxH - inc) > limit) {
			el.style.pixelHeight = pxH - inc;
			if (onTermination) {
				var tmo2 = setTimeout('shrinkElementHeight(document.all.' + el.id + ', ' + inc + ', ' + limit + ', "' + onTermination + '", ' + fq + ')', fq);
			} else {
				var tmo2 = setTimeout('shrinkElementHeight(document.all.' + el.id + ', ' + inc + ', ' + limit + ', null, ' + fq + ')', fq);
			}
		} else {
			el.style.pixelHeight = limit;
			eval(onTermination);
		}
	}
}
function growElementWidth(el, inc, limit, onTermination, fq) {
	if (! (limit.constructor == Number)) {
		return;
	}
	var pxH = el.style.pixelWidth;
	if (pxH < limit) {
		if ((pxH + inc) < limit) {
			el.style.pixelWidth = pxH + inc;
			if (onTermination) {
				var tmo2 = setTimeout('growElementWidth(document.all.' + el.id + ', ' + inc + ', ' + limit + ', "' + onTermination + '", ' + fq + ')', fq);
			} else {
				var tmo2 = setTimeout('growElementWidth(document.all.' + el.id + ', ' + inc + ', ' + limit + ', null, ' + fq + ')', fq);
			}
		} else {
			el.style.pixelWidth = limit;
			eval(onTermination);
		}
	}
}

function findContact() {
	function contactWindowArgs() {
		this.permission = 1;
		return(this);
	}
	var modArgs = new contactWindowArgs();
	var cw = window.showModalDialog('ContactsList.aspx', modArgs, 'dialogHeight:300px;dialogWidth:620px;status:no');
	if (cw) {
		event.srcElement.form.MessageTo.value = cw.email;
	}
	event.srcElement.blur()
}

function showContactsPage() {
	function contactWindowArgs() {
		this.permission = 1;
		return(this);
	}
	var modArgs = new contactWindowArgs();
	var cw = window.showModalDialog('ContactsPage.aspx', modArgs, 'dialogHeight:300px;dialogWidth:620px;status:no');
	if (cw) {
		event.srcElement.form.MessageTo.value = cw.email;
	}
	event.srcElement.blur()
}

function MessageCentrePrefs(fq) {
	this.fq = 120; // chaeck every 120 seconds
	this.dsp = 2;
	return(this);
}

function getStyle(selectorName) {
	var i=0, j=0;
//	alert(document.styleSheets.length);
	for (i=0; i<document.styleSheets.length; i++) {
//	alert(document.styleSheets(i).rules.length);
		for (j=0; j<document.styleSheets(i).rules.length; j++) {
//alert(document.styleSheets(i).rules(j).selectorText);
			if (document.styleSheets(i).rules(j).selectorText == selectorName) {
				return(document.styleSheets(i).rules(j).style);
			}
		}
	}
}

function mouseoverTable(table, onmouseoverClassName, onmouseoutClassName) {
	this.onmouseoverFunc = onmouseoverItem;
	this.onmouseoutFunc = onmouseoutItem;
	this.className = onmouseoutClassName;
	this.onmouseoverClassName = onmouseoverClassName;
	this.onmouseoutClassName = onmouseoutClassName;
	this.initialiseMouseoverTable = initialiseMouseoverTable;
	this.initialiseCell = initialiseCell;
	this.initialiseMouseoverTable();
	function initialiseMouseoverTable() {
		var tr, td;
		for (var i = 0; i < table.rows.length; i++) {
			tr = table.rows[i];
			for (var j=0; j<tr.cells.length; j++) {
				td = tr.cells[j];
				if (isBlank(td.className)) {
					initialiseCell(td, this);
				}
			}
		}
	}
	function initialiseCell(td, thisf) {
		td.onmouseover = thisf.onmouseoverFunc;
		td.onmouseout = thisf.onmouseoutFunc;
		td.className = thisf.className;
		td.onmouseoverClassName = thisf.onmouseoverClassName;
		td.onmouseoutClassName = thisf.onmouseoutClassName;
	}
	function onmouseoverItem() {
		with(window.event.srcElement) {
			if (className != this.onclickClassName) {
				className = this.onmouseoverClassName;
			}
			self.status = innerText;
		}
	}
	function onmouseoutItem() {
		with(window.event.srcElement) {
			if (className == this.onmouseoverClassName) {
				className = this.onmouseoutClassName;
			}
			self.status = '';
		}
	}
}

function selectsToOnes() {
	var i, j;
	for (i=0;i<document.forms.length;i++) {
		for (j=0;j<document.forms[i].elements.length;j++) {
			selectToOne(document.forms[i].elements[j]);
		}
	}
}

function selectToOne(theSelect) {
	if (theSelect) {
		if (theSelect.type == 'select-one' || theSelect.type == 'select-multiple') {
			theSelect.size = null;
		}
	}
}

function selectsToMultiples() {
	var i, j;
	for (i=0;i<document.forms.length;i++) {
		for (j=0;j<document.forms[i].elements.length;j++) {
			if (document.forms[i].elements[j].type == 'select-one' || document.forms[i].elements[j].type == 'select-multiple') {
				if (document.forms[i].elements[j].name.indexOf('DateOf') == -1) {
					selectToMultiple(document.forms[i].elements[j]);
				}
			}
		}
	}
}

function selectToMultiple(theSelect) {
	if (theSelect) {
		if (theSelect.type == 'select-one' || theSelect.type == 'select-multiple') {
			theSelect.size = theSelect.options.length;
		}
	}
}

var counter = 0;
var iTimerID;
function selectTickedServiceUsers(theButton, theHidden) {
	var theForm = theButton.form;
	var tilde = '';
	theHidden.value = '';
//	if (theForm.SUtick[0]) {
//		for (i=0;i<theForm.SUtick.length;i++) {
//			if (theForm.SUtick[i].checked == true) {
//				theHidden.value += tilde + theForm.SUtick[i].value;
//				tilde = '~';
//				selectSUObjectParams(theForm.SUtick[i].value);
//			}
//		}		
//	}
	timedAdding(0);
	//selectServiceUser(top.document.form1.PersonID.value);
}
function timedAdding(i, onTermination) {
	var theForm = null;
	if (window.event == null) {
		theForm = mainiframe.document.forms[0];
	} else {
		theForm = window.event.srcElement.forms[0];
	}
	var redirect = false;
	if (!theForm.SUtick)
		return;
	if (i >= theForm.SUtick.length) {
		window.clearTimeout(tmo3);
		eval(onTermination);
		return;
	}
	if (theForm.SUtick[i].checked == true) {
		mainiframe.selectSUObjectParams(theForm.SUtick[i].value, redirect);
	}
	i++
	var tmo3 = window.setTimeout('timedAdding(' + i + ', \'selectServiceUser(top.document.form1.PersonID.value)\')', 300);
}

function selectServiceUser(id) {
	var currSel = top.document.form1.PersonID.value;
	top.mainiframe.document.location='Empty.aspx';
	//showCallee();
	top.document.form1.PersonID.value = id;
	var obj = getSUObjectFromarrSUs(id);
	showPermissionedFunctions(obj);
	top.setDisplay('', ['ServiceUserSelectionTABLE']);
	if (currSel == 0 && top.suSelected == false) {
		top.toggleFunctionButtons();
	}
	top.scrollTo(0, 0)
	top.hideMessageCentreIfDisplayed();
}

function selectServiceUserAndRemain(id) {
	var currSel = top.document.form1.PersonID.value;
	top.document.form1.PersonID.value = id;
	var obj = getSUObjectFromarrSUs(id);
	showPermissionedFunctions(obj);
	top.setDisplay('', ['ServiceUserSelectionTABLE']);
	if (currSel == 0 && top.suSelected == false) {
		top.toggleFunctionButtons();
	}
	top.scrollTo(0, 0)
	top.hideMessageCentreIfDisplayed();
}

function showPhoto(id) {
	var htm = event.srcElement.innerHTML;
	var tg = top.photoImgTag2(id);
	event.srcElement.innerHTML = top.photoImgTag2(id);
	event.srcElement.style.display = '';
}

function selectPhoto(id) {
	document.all.SelectedPhotoTD.innerHTML = top.photoImgTag(id);
	document.all.SelectedPhotoTD.style.display = '';
}

function photoPath(id) {
	return('Photos/' + id + '.jpg');
}

function photoImgTag(id) {
	return('<IMG src=' + top.photoPath(id) + ' width=96 height=127 border=2 unselectable="On">');
}

function photoImgTag2(id) {
	return('<IMG src="../' + top.photoPath(id) + '" width="96" height="127" border="2" unselectable="On">');
}

function editAddress(srcButton, numRows) {
	var addressSpan = srcButton.parentElement.firstChild;
	function addressArgs() {
		this.fullName = '';
		this.organisation = '';
		this.address1 = '';
		this.address2 = '';
		this.address3 = '';
		this.address4 = '';
		this.phone = '';
		this.addressID = 0;
		return(this);
	}
	var modArgs = new addressArgs();
	var h = (40 * numRows) + 40;
	var md = window.showModalDialog('Modal_Address.aspx', modArgs, 'dialogHeight:' + h + 'px;dialogWidth:494px;resizable:yes;status:no');
	if (md) {
		//alert(displayArray(md));
	}
}

// For Support needs (exept 'Informal')
function onchangeAgencyID(theEl) {
	var el = (isBlank(theEl)) ? event.srcElement : theEl;
	//var arrSupTypePrefixes = new Array('Mntl', 'Gnrl', 'Dntl', 'Sght', 'Bhvr', 'Dmst', 'Edct', 'Empy', 'Flng', 'Hrsm', 'Lrng', 'Mney', 'Trng');
	// Changed to accommodate UserControl IDs as defined in the pages
	var arrSupTypePrefixes = new Array('Only1_', 'Litcy_', 'Numcy_', 'Mentl_', 'Genrl_' ,'Dentl_', 'Sight_', 'Bhavr_', 'Domst_', 'Educt_', 'Emplm_', 'Fleng_', 'Harsm_', 'Lerng_', 'Money_', 'Train_');
	var idx = getIndexInArray(el.id.substring(0, 6), arrSupTypePrefixes);
	var prefix = (idx == null) ? '' : arrSupTypePrefixes[idx];
	switch(getElementVal(el)) {
		case '0':
			return;
		default:
			function reviewArgs(agencyID, agencyName, add) {
				this.agencyID = agencyID;
				this.agencyName = agencyName;
				this.add = add;
				return(this);
			}
			var modArgs = new reviewArgs(getElementVal(el), getSelectText(el), false);
			var md = window.showModalDialog('Agency_Support_Review.htm', modArgs, 'dialogHeight:500px;dialogWidth:680px;resizable:yes;status:no');
			if (! md) {
				md = modArgs;
			}
			
			var shortListTable = eval('document.all.' + prefix + 'InvolvedTABLE');
			if (md.add == true) {
				// Stuff for SupList hidden field
				var theHid = document.getElementById(prefix + 'SupList');
				var theLvlCncrn = getElementVal(document.getElementById(prefix + 'LvlCncrnTypID'));
				var theIsSupNd = getElementVal(document.getElementById(prefix + 'IsSupNdID'));
				var theSupTyp = getElementVal(document.getElementById(prefix + 'SupTypID'));
				//AgencyID~Organisation~LvlCncrnTypID~IsSupNdID~SupTypID
				var SupListText = theHid.value;
				var caret = '';
				if (SupListText.length == 0) {
					SupListText = "0~~" + theLvlCncrn + "~" + theIsSupNd + "~" + theSupTyp;
				}
				if (SupListText.substring(0, 1) == '0') { //First agency selected so clear the default 0 id agency.
					SupListText = '';
				} else {
					caret = '^';
				}
				SupListText += caret + md.agencyID + "~" + md.agencyName + "~" + theLvlCncrn + "~" + theIsSupNd + "~" + theSupTyp;
				theHid.value = SupListText;
				
				// Building and adding the table row
				var nRow = shortListTable.insertRow(1);
				var cell0 = nRow.insertCell();
				var cell1 = nRow.insertCell();
				var cell2 = nRow.insertCell();
			
				var c = cell0;
				c.className = 'formCellsTextNoVBdr';
				c.innerHTML = '<input class="buttonSmall" type="button" name="Submit" value="Review" onclick="reviewAgency(' + getElementVal(el) + ')">';
			
				var c = cell1;
				c.className = 'formCellsTextNoVBdr';
				c.innerText = md.agencyName;

				var c = cell2;
				c.className = 'formCellsTextNoVBdr';
				c.innerHTML = '<input type="button" name="Button" value="Remove" onclick="onclickRemoveAgency(\'' + prefix + 'SupList\', \'' + theHid.id + '\'); " class="buttonSmall">';
				
				displayIDs('', prefix + 'InvolvedTR');
				
			} else {
				//onclickSelectedApplicantDeselect()
				if (! shortListTable.rows.length > 1) {
					displayIDs('none', prefix + 'InvolvedTR');
				}
			}
			
			clearVals([el], true);
	}
}

function onclickRemoveAgency(theHidId, agencyId) {
	var agName = null;
	// find the clicked table row
	var tbl = getParentTag(event.srcElement, 'TABLE');
	var tr;
	var rowIdx = 0;
	for (var i = 0; i < tbl.rows.length; i++) {
		tr = tbl.rows(i);
		if (tr.contains(event.srcElement) == true) {
			rowIdx = i;
			// Get the Agency name from the rows.cells[1]
			agName = tbl.rows(i).cells(1).innerText;
			break;
		}
	}
	// find the match in the string in the hidden field and delete it
	var theHid = document.getElementById(theHidId);
	var theHidVal = getElementVal(theHid);
	if (theHidVal.length > 0) {
		var lines = theHidVal.split('^');
		var fields;
		for (var i = 0; i < lines.length; i++) {
			fields = lines[i].split('~');
			if (fields[0].toString() == agencyId.toString()) {
				lines.splice(i, 1);
				break;
			}
		}
		theHid.value = lines.join('^');
	}
	if (rowIdx > 0) {
		tbl.deleteRow(rowIdx);
	}
}

// For Support needs (exept 'Informal')
function buildInvolvedTABLE(theEl) {
	var el = (isBlank(theEl)) ? event.srcElement : theEl;
	var arrSupTypePrefixes = new Array('Only1_', 'Mentl_', 'Genrl_' ,'Dentl_', 'Sight_', 'Bhavr_', 'Domst_', 'Educt_', 'Emplm_', 'Fleng_', 'Harsm_', 'Lerng_', 'Money_', 'Train_');
	var idx = getIndexInArray(el.id.substring(0, 6), arrSupTypePrefixes);
	var prefix = (idx == null) ? '' : arrSupTypePrefixes[idx];
	var shortListTable = eval('document.all.' + prefix + 'InvolvedTABLE');
	var theHid = document.getElementById(prefix + 'SupList');
	SupListText = theHid.value;
	if (!SupListText.length > 0)
		return;;
	var arrAllInvolved = SupListText.split('^');
	var arrInvolved = null;
	for (i = 0; i < arrAllInvolved.length; i++) {
		arrInvolved = arrAllInvolved[i].split('~');
		// Building and adding the table row
		var nRow = shortListTable.insertRow(1);
		var cell0 = nRow.insertCell();
		var cell1 = nRow.insertCell();
		var cell2 = nRow.insertCell();
	
		var c = cell0;
		c.className = 'formCellsTextNoVBdr';
		c.innerHTML = '<input class="buttonSmall" type="button" name="Submit" value="Review" onclick="reviewAgency(' + arrInvolved[0] + ')">';
	
		var c = cell1;
		c.className = 'formCellsTextNoVBdr';
		c.innerText = arrInvolved[1];// md.agencyName;

		var c = cell2;
		c.className = 'formCellsTextNoVBdr';
		c.innerHTML = '<input type="button" name="Button" value="Remove" onclick="onclickRemoveAgency(\'' + prefix + 'SupList\', \'' + arrInvolved[0] + '\'); " class="buttonSmall">';
		
		displayIDs('', prefix + 'InvolvedTR');
	}
}


var ENTITY_MAP = new Array(
 "\x20", "&nbsp;",
 "\x22", "&quot;",   //Low-ASCII chars that should use entities
 "\x26", "&amp;",
 "\x3C", "&lt;",
 "\x3E", "&gt;",

 "\x80", "&euro;",   //Hi-ASCII chars
 "\xA1", "&iexcl;",
 "\xA2", "&cent;",
 "\xA3", "&pound;",
 "\xA4", "&curren;",
 "\xA5", "&yen;",
 "\xA6", "&brvbar;",
 "\xA7", "&sect;",
 "\xA8", "&uml;",
 "\xA9", "&copy;",
 "\xAA", "&ordf;",
 "\xAB", "&laquo;",
 "\xAC", "&not;",
 "\xAD", "&shy;",
 "\xAE", "&reg;",
 "\xAF", "&macr;",
 "\xB0", "&deg;",
 "\xB1", "&plusmn;",
 "\xB2", "&sup2;",
 "\xB3", "&sup3;",
 "\xB4", "&acute;",
 "\xB5", "&micro;",
 "\xB6", "&para;",
 "\xB7", "&middot;",
 "\xB8", "&cedil;",
 "\xB9", "&sup1;",
 "\xBA", "&ordm;",
 "\xBB", "&raquo;",
 "\xBC", "&frac14;",
 "\xBD", "&frac12;",
 "\xBE", "&frac34;",
 "\xBF", "&iquest;",
 "\xD7", "&times;",
 "\xF7", "&divide;",
 "\xC6", "&AElig;",
 "\xC1", "&Aacute;",
 "\xC2", "&Acirc;",
 "\xC0", "&Agrave;",
 "\xC5", "&Aring;",
 "\xC3", "&Atilde;",
 "\xC4", "&Auml;",
 "\xC7", "&Ccedil;",
 "\xD0", "&ETH;",
 "\xC9", "&Eacute;",
 "\xCA", "&Ecirc;",
 "\xC8", "&Egrave;",
 "\xCB", "&Euml;",
 "\xCD", "&Iacute;",
 "\xCE", "&Icirc;",
 "\xCC", "&Igrave;",
 "\xCF", "&Iuml;",
 "\xD1", "&Ntilde;",
 "\xD3", "&Oacute;",
 "\xD4", "&Ocirc;",
 "\xD2", "&Ograve;",
 "\xD8", "&Oslash;",
 "\xD5", "&Otilde;",
 "\xD6", "&Ouml;",
 "\xDE", "&THORN;",
 "\xDA", "&Uacute;",
 "\xDB", "&Ucirc;",
 "\xD9", "&Ugrave;",
 "\xDC", "&Uuml;",
 "\xDD", "&Yacute;",
 "\xE1", "&aacute;",
 "\xE2", "&acirc;",
 "\xE6", "&aelig;",
 "\xE0", "&agrave;",
 "\xE5", "&aring;",
 "\xE3", "&atilde;",
 "\xE4", "&auml;",
 "\xE7", "&ccedil;",
 "\xE9", "&eacute;",
 "\xEA", "&ecirc;",
 "\xE8", "&egrave;",
 "\xF0", "&eth;",
 "\xEB", "&euml;",
 "\xED", "&iacute;",
 "\xEE", "&icirc;",
 "\xEC", "&igrave;",
 "\xEF", "&iuml;",
 "\xF1", "&ntilde;",
 "\xF3", "&oacute;",
 "\xF4", "&ocirc;",
 "\xF2", "&ograve;",
 "\xF8", "&oslash;",
 "\xF5", "&otilde;",
 "\xF6", "&ouml;",
 "\xDF", "&szlig;",
 "\xFE", "&thorn;",
 "\xFA", "&uacute;",
 "\xFB", "&ucirc;",
 "\xF9", "&ugrave;",
 "\xFC", "&uuml;",
 "\xFD", "&yacute;",
 "\xFF", "&yuml;");


function highAsciiEntityEncode(origStr) {
 if (isBlank(origStr)) {
	return(origStr);
 }
 var i,j, retStr;
// var charSet = dw.getDocumentDOM().getCharSet();
//  if (charSet == "iso-8859-1")
//  {
//    retStr = dreamweaver.nativeToLatin1(origStr);
//  } else {
    retStr = origStr;  
//  }
  var charCode, hasEntity = false;

  for (i=0; i<retStr.length && !hasEntity; i++) {
    charCode = retStr.charCodeAt(i);
    // if  high-ASCII, ", &, <, or >
    hasEntity = (charCode > 127);
    //DEBUG: for Japanese, don't encode if high-ASCII. Need to modify the previous line for the J release.
  }

  if (hasEntity) {   // iff entity found, entity-encode string
    oldStr = retStr;                     //copy string
    retStr = "";                         //and build new one
    for (i=0; i<oldStr.length; i++) {
      charCode = oldStr.charCodeAt(i);
      theChar = oldStr.charAt(i);
      if (charCode > 127) { 
        for (j=0; j<ENTITY_MAP.length-1; j+=2) {  //search map
          if (ENTITY_MAP[j] == theChar) { //if found
            theChar = ENTITY_MAP[j+1];    //set theChar to matching entity
            break;
          }
        }
        if (j >= ENTITY_MAP.length) {     //if not found in map
          theChar = '&#' + parseInt(charCode) + ';';  //set to integer
        }
      }
      retStr += theChar;                  //append char to string
    }
  }

  return retStr;
}

//If a string has high-ASCII characters or low-ASCII that should be encoded, those characters
//are converted to entities. For example, and accented "e" will become &egrave;.
//Note that this does not affect low ascii chars that should be encoded like <>".
//Uses the entity map above (ENTITY_MAP). If a high-ASCII char is not found in
//the map, sets the char to &#nnn;, where nnn is the charCode.
//Returns the encoded string.

function entityNameEncode(origStr) {

 var i,j, retStr;
 var charSet = dw.getDocumentDOM().getCharSet();
  if (charSet == "iso-8859-1")
  {
    retStr = dreamweaver.nativeToLatin1(origStr);
  } else {
    retStr = origStr;  
  }
  var charCode, hasEntity = false;

  for (i=0; i<retStr.length && !hasEntity; i++) {
    charCode = retStr.charCodeAt(i);
    // if  high-ASCII, ", &, <, or >
    hasEntity = (charCode > 127 || charCode == "\x22" || charCode == "\x26" || charCode == "\x3C" || charCode == "\x3E");
    //DEBUG: for Japanese, don't encode if high-ASCII. Need to modify the previous line for the J release.
  }

  if (hasEntity) {   // iff entity found, entity-encode string
    oldStr = retStr;                     //copy string
    retStr = "";                         //and build new one
    for (i=0; i<oldStr.length; i++) {
      charCode = oldStr.charCodeAt(i);
      theChar = oldStr.charAt(i);
      if (charCode > 127 || charCode == "\x22" || charCode == "\x26" || charCode == "\x3C" || charCode == "\x3E") { 
        for (j=0; j<ENTITY_MAP.length-1; j+=2) {  //search map
          if (ENTITY_MAP[j] == theChar) { //if found
            theChar = ENTITY_MAP[j+1];    //set theChar to matching entity
            break;
          }
        }
        if (j >= ENTITY_MAP.length) {     //if not found in map
          theChar = '&#' + parseInt(charCode) + ';';  //set to integer
        }
      }
      retStr += theChar;                  //append char to string
    }
  }

  return retStr;
}



//If a string contains encoded strings like &quot; or &egrave;, they will be converted
//to their character equivalents for proper display. Returns the decoded string.

function entityNameDecode(origStr) {
  var i, theEntity, retStr = origStr;
  var entityPattern = /&\w+;/g;

  while ((theEntity = entityPattern.exec(origStr)) != null) { //with each entity found
    for (i=1; i<ENTITY_MAP.length; i+=2) {              //look up entity in map
      if (ENTITY_MAP[i] == theEntity) {                 //when found
        retStr = retStr.replace(RegExp(ENTITY_MAP[i]),(ENTITY_MAP[i-1])); //replace entity with value
        break;
      }
    }
  }
  var charSet = dw.getDocumentDOM().getCharSet();
   if (charSet == "iso-8859-1")
    {
   	return dreamweaver.latin1ToNative(retStr);
    }  else {
	return retStr;
     }
}

function trim(str) {
	if (window.RegExp) 
	{
		//str = str.replace(/^\s*(.*)/, "$1");
		//str = str.replace(/(.*?)\s*$/, "$1");
		// debug MM version - replace Sedgemoor if OK and add to any appropriate libraries
		str = str.replace(/^\s*/,""); //strip leading
		str = str.replace(/\s+$/,""); //strip trailing
		return str;
	}
}
function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}



