// The includes utils 
	var curSelection = null;
	var currRow = -1;
	var selRow = -1;
	var HColor="cyan";
	var	SColor = "#FFFFCC";
	var CheckListItem = '<input id="ItemId" type=checkbox name="ItemName" /><label for="ItemId">ItemValue</label>'
	var arrAddr = new Array();
	QueryString.keys = new Array();
	QueryString.values = new Array();
	var strStatus = '';
	var OnePath = '../';
	var PRFloor = 2000;
	var PRDelta = 900;
	var bIsis = false;
	var bSchemes = false;
	var chkMonday = null;
	var txtDescription;
	var docWindow = null;
	
	function CountOfSelectedItems(lstListBoxName)
	{
		var d=document.all;
		var Count = 0;
		for(i=0;i<d.item(lstListBoxName).rows.length;i++)
		{			
			if (d.item(lstListBoxName + "_" + i).checked==true)
			{
				Count = Count + 1;
			}
		}

		return Count;		
	}
	function CheckMaxLength(txtBox,intLength)
	{
		if (txtBox.value.length==intLength)
		{
			return false;
		}else
		{
			return true;
		}
	}
	
	function CalculateAge(DOB,CurrentDate)
	{            
		CurrentDate = new Date(CurrentDate);
		DOB = new Date(DOB);
		timeold = (CurrentDate.getTime()-DOB.getTime());
		msPerDay = 24 * 60 * 60 * 1000;
		e_daysold = timeold / msPerDay;
		daysold = Math.floor(e_daysold);
		Age=daysold/365.25;
		return Math.floor(Age);
	}
	
	function SetGridFromId(grdName,intId,ColName)
	{
		var table = document.all.item(grdName);		
		var intIdLocal=0;
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{
				intIdLocal=GetGridValueInRow(table, i, ColName);
				if (intIdLocal==intId)
				{
					table.rows(i).click();
					return;
				}
			}
		}
	}
	function GetGridRowCount(gridName)
	{
		var grid=document.all.item(gridName);
		if(null != grid)
		{			
			return grid.rows.length;
		}
		return 0;
	}
	function CheckAllBoxes(grdName)
	{
		var table = document.all.item(grdName);		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	
				table.rows[i].cells[0].childNodes[0].childNodes[0].checked=true;				
			}
		}
	}
	
	function EnableAllBoxes(grdName,Column)
	{	var table = document.all.item(grdName);		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	table.rows[i].cells[Column].childNodes[0].childNodes[0].disabled=false;				
			}
		}
	}
	
	function DisableAllBoxes(grdName,Column)
	{	var table = document.all.item(grdName);	
		
		if(null != table && table.rows.length >1)
		{	
			for(var i=1; i<table.rows.length; i++)
			{	if (null != table.rows[i].cells[Column].childNodes[0].childNodes[0])
				{	table.rows[i].cells[Column].childNodes[0].childNodes[0].disabled=true;
				}
			}
		}
	}

	function UnCheckAllBoxes(grdName)
	{
		var table = document.all.item(grdName);		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	
				table.rows[i].cells[0].childNodes[0].childNodes[0].checked=false;				
			}
		}
	}
	
	function UnCheckAllBoxesByColumn(grdName,Column)
	{
		var table = document.all.item(grdName);		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	
				table.rows[i].cells[Column].childNodes[0].childNodes[0].checked=false;				
			}
		}
	}
	
	function GetGridCheckedIds(grdName,colName)
	{
		iCount=0;
		var strIds = '';
		var table = document.all.item(grdName);
		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	
				if(table.rows[i].cells[0].childNodes[0].childNodes[0].checked==true)
				{
					iCount=iCount+1;
					if (strIds=="")
					{
						strIds=GetGridValueInRow(table, i, colName)
					}else
					{
						strIds +=',' + GetGridValueInRow(table, i, colName)
					}
				}
			}
		}
		return strIds;
	}
	
	function GetGridUnCheckedIds(grdName,colName)
	{
		iCount=0;
		var strIds = '';
		var table = document.all.item(grdName);
		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	
				if(table.rows[i].cells[0].childNodes[0].childNodes[0].checked==false)
				{
					iCount=iCount+1;
					if (strIds=="")
					{
						strIds=GetGridValueInRow(table, i, colName)
					}else
					{
						strIds +=',' + GetGridValueInRow(table, i, colName)
					}
				}
			}
		}
		return strIds;
	}
		
	function GetGridCheckedIdsCheckColumn(grdName,colName, CheckColumn)
	{
		iCount=0;
		var strIds = '';
		var table = document.all.item(grdName);
		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	
				if(table.rows[i].cells[CheckColumn].childNodes[0].childNodes[0].checked==true)
				{
					iCount=iCount+1;
					if (strIds=="")
					{
						strIds=GetGridValueInRow(table, i, colName)
					}
					else
					{
						strIds +=',' + GetGridValueInRow(table, i, colName)
					}
				}
			}
		}
		return strIds;
	}
	
	function GetGridCheckedIdAndValues(grdName,idColumn,checkColumn)
	{
		var strIdAndValues = '';
		var table = document.all.item(grdName);
		
		if(null != table && table.rows.length >1)
		{
			for(var i=1; i<table.rows.length; i++)
			{	
				var id = table.rows[i].cells[idColumn].innerHTML;
				var isChecked = table.rows[i].cells[checkColumn].childNodes[0].childNodes[0].checked;
				
				if (strIdAndValues=='')
				{
					strIdAndValues = id + ',' + isChecked;
				}
				else
				{
					strIdAndValues +=';' + id + ',' + isChecked;
				}
			}
		}
		return strIdAndValues;
	}
	function ShowExcel(level)
	{
		var p = GetPathOffset(level);
		var parent = window;
		try
		{
			if(dialogArguments != undefined) 
			{
				parent = dialogArguments;
			}
			//Check to ensure that the dialogArguments are a valid window object - i.e. have a Document object
			if(parent.document == undefined) 
			{
				parent = window;
			}
			//Used for modals
			window.showModalDialog(p + "../Common/ExcelColumnSelect.aspx" + rVal(),parent.dialogArguments,"dialogheight:310px;dialogwidth:585px;help:no;status:no");
		}
		catch(e)
		{
			//Used for ordinary windows
			parent = window;
			parent.showModalDialog(p + "../Common/ExcelColumnSelect.aspx" + rVal(),parent,"dialogheight:310px;dialogwidth:585px;help:no;status:no");
		}		
		return false;
	}
	
	function CheckTime()//Call this function onKeyPress
	{				
		if(event.keyCode<48 || event.keyCode>58)
		{
			return false;
		}	
		return true;			
	}
	
	function CheckNumberRange(intRageFrom,intRangeTo,txtBox)
	{
		if (txtBox.value=="") return true;
		if (isNaN(txtBox.value)==false)
		{
			if (txtBox.value<intRageFrom || txtBox.value>intRangeTo)
			{
				alert("Invalid number entered. Range allowed from " + intRageFrom + " to " + intRangeTo + ".");
				txtBox.select();
				txtBox.focus();
				return false;
			}else
			{
				return true
			}
		}else
		{
			alert("Invalid number entered. Range allowed from " + intRageFrom + " to " + intRangeTo + ".");
			txtBox.select();
			txtBox.focus();
			return false;
		}
		return true
	}
	
	function ShowLetters(CaseType)
	{		
		strURL="../Common/LettersTab.aspx" + rVal() + "&c=" + CaseType + "&CallForm=ModalWindow"
		OpenModalDialogCenterScreen(strURL, window, 630,420,null)
	}
	
	function PageOnLoadStuff(){
		SetBanner();
		SetButtons();
		document.attachEvent('onkeydown', KillCR);
		window.status = GetStatusValue();
		//document.oncontextmenu = function () { return false; }		
		if(null==window.opener && (!bIsis))history.go(1);
		return true;
	}

	function CheckWidth()
	{
		var nScreeWidth;
		nScreeWidth=screen.width;
		if (nScreeWidth==800)
		{
		}
		else			 
		{
			objDiv=document.getElementById("grdContainer");
			objDiv.style.posWidth=nScreeWidth-160;
			objDiv=document.getElementById("lblCaption");
			objDiv.style.posWidth=nScreeWidth-160;
		}		 
	}

	function ValidateDate(objName) 
	{
		var datefield = objName;
		if (chkdate(objName) == false) 
		{
			datefield.select();
			alert("That date is invalid. Please enter again.");
			datefield.focus();
			var today = Date();
			var month = today.substring(4, 7);
			var day = today.substring(8, 10);
			var year = today.substring(20, 25);
			objName.value = day + " " + month + " " + year;
			return false;
		}
		else 
		{
			return true;
		}
	}
	function ValidateEmail(tb)
	{
		/**if (tb.value != "")
		{
			var emailRegxp = /^([\w]+)(.[\w]+)*@([\w]+)\.([\w]{2,3}){1,2}$/;
			if(emailRegxp.test(tb.value) != true)
			{
				alert('Invalid Email address.');
				tb.focus();
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{**/	return true;
		//}
	}
	
	function ValidateFilenameOnly(tb)
	{	if (tb.value != "")
		{
			var filenameRegxp = /^([\w]+)\.([\w]{2,30})$/;
														
			if(filenameRegxp.test(tb.value) != true)
			{
				alert('Invalid File Name, do not include path information, invalid characters or spaces.');
				tb.focus();
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{	return true;
		}
	}
	
	function CheckFileFormat(tb, desiredFormat, desiredFormatName)
	{	var filename = tb.value;
		var fileFormat;
		
		if (filename != "")
		{	fileFormat = filename.substr(filename.lastIndexOf(".") + 1);
			
			if (fileFormat.toLowerCase() != desiredFormat.toLowerCase())
			{	var msg = "The selected file format does not match the expected format, it is recommended that " + desiredFormatName + ", " + desiredFormat.toLowerCase() + ", be used.\nUsing a different format may affect the way the file is displayed.\nDo you wish to continue?";
				
				if (confirm(msg))
				{	return ValidateFilenameOnly(tb);
				}
				else
				{	tb.focus();
					return false;
				}
			}
			else
			{	return ValidateFilenameOnly(tb);
			}
		}
		else
		{	return ValidateFilenameOnly(tb);
		}
	}
		
	function ValidateFilePathOnly(tb)
	{	if (tb.value != "")
		{
			var filenameRegxp = /\s/;
														
			if(filenameRegxp.test(tb.value) == true)
			{
				alert('Invalid File Path, do not include spaces.');
				tb.focus();
				return false;
			}
			else
			{	return true;
			}
		}
		else
		{	return true;
		}
	}
	
	function ValidateTime(tb)
	{
		var bValid = true;
		var h = "00";
		var m = "00"
		var r = ':';
		
		if((null != tb) && (tb.value.length>0))
		{
			var hours = 0;
			var mins = 0;
			var val = tb.value;
			var pos = val.indexOf(r);
			if(pos <0)
			{
				pos = val.indexOf('.');
			}
			if(pos <0)
			{
				pos = val.indexOf(';');
			}
			if (pos < 0)
			{
				if(val.length >2)
				{
					val='0' + val.substr(0, val.length-2)+r+val.substr(val.length-2);
					val=val.substr(val.length-5);
				}
				else
				{
					val=m+r+(val+'0').substr(0,2);
				}
				pos = val.indexOf(r);
			}
			try
			{
				hours = parseInt(val.substr(0,pos),10);
				mins = parseInt(val.substr(pos +1),10);
				//hours = val.substr(pos-1).parseInt();
				//mins = val.substr(pos +1).parseInt();
			}
			catch(e)
			{
				tb.value = h + r + m;
				return;
			}
			if(hours >=0 && hours <24)
			{
				h += hours.toString();
				h = h.substr(h.length -2);
			}
			else
			{
				bValid = false;
				alert('Invalid number of hours');
				tb.focus();
			}
			if(bValid)
			{
				if (mins >=0 && mins <60)
				{
					m += mins.toString();
					m = m.substr(m.length -2);
				}
				else
				{
					bValid = false;
					alert('Invalid number of minutes.');
					tb.focus();
				}
			}
			
		}	
		if (bValid)
		{
			tb.value = h + r + m;
		}		
	}
	
	function chkdate(objName) 
	{
		//var strDatestyle = "US"; //United States date style
		var strDatestyle = "EU";  //European date style
		var strDate;
		var strDateArray;
		var strDay;
		var strMonth;
		var strYear;
		var intday;
		var intMonth;
		var intYear;
		var booFound = false;
		var datefield = objName;
		var strSeparatorArray = new Array("-"," ","/",".");
		var intElementNr;
		var err = 0;
		var strMonthArray = new Array(12);
		strMonthArray[0] = "Jan";
		strMonthArray[1] = "Feb";
		strMonthArray[2] = "Mar";
		strMonthArray[3] = "Apr";
		strMonthArray[4] = "May";
		strMonthArray[5] = "Jun";
		strMonthArray[6] = "Jul";
		strMonthArray[7] = "Aug";
		strMonthArray[8] = "Sep";
		strMonthArray[9] = "Oct";
		strMonthArray[10] = "Nov";
		strMonthArray[11] = "Dec";
		strDate = datefield.value;
		if (strDate.length < 1) 
		{
			return true;
		}
		if (strDate.length < 6) 
		{
			return false;
		}
		for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) 
		{
			if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) 
			{
				strDateArray = strDate.split(strSeparatorArray[intElementNr]);
				if (strDateArray.length != 3) 
				{
					err = 1;
					return false;
				}
				else 
				{
					strDay = strDateArray[0];
					strMonth = strDateArray[1];
					strYear = strDateArray[2];
				}
				booFound = true;
			}
		}
		if (booFound == false) 
		{
			if (strDate.length>5) 
			{
				strDay = strDate.substr(0, 2);
				strMonth = strDate.substr(2, 2);
				strYear = strDate.substr(4);
			}
		}
		if (strYear.length == 2) 
		{
			strYear = SetEpoch(strYear);
		}
		else if (strYear.length>4)
		{
			return false;
		}


		// US style
		if (strDatestyle == "US") 
		{
			strTemp = strDay;
			strDay = strMonth;
			strMonth = strTemp;
		}
		intday = parseInt(strDay, 10);
		if (isNaN(intday)) 
		{
			err = 2;
			return false;
		}
		intMonth = parseInt(strMonth, 10);
		if (isNaN(intMonth)) 
		{
			for (i = 0;i<12;i++) 
			{
				if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) 
				{
					intMonth = i+1;
					strMonth = strMonthArray[i];
					i = 12;
				}
			}
			if (isNaN(intMonth)) 
			{
				err = 3;
				return false;
			}
		}
		intYear = parseInt(strYear, 10);
		if (isNaN(intYear)) 
		{
			err = 4;
			return false;
		}
		if (intMonth>12 || intMonth<1) 
		{
			err = 5;
			return false;
		}
		if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) 
		{
			err = 6;
			return false;
		}
		if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) 
		{
			err = 7;
			return false;
		}
		if (intMonth == 2) 
		{
			if (intday < 1) 
			{
				err = 8;
				return false;
			}
			if (LeapYear(intYear) == true) 
			{
				if (intday > 29) 
				{
					err = 9;
					return false;
				}
			}
			else 
			{
				if (intday > 28) 
				{
					err = 10;
					return false;
				}
			}
		}
		if (strDatestyle == "US") 
		{
			datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
		}
		else 
		{
			datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
		}
			return true;
	}
		
	function LeapYear(intYear) 
	{
		if (intYear % 100 == 0) 
		{
			if (intYear % 400 == 0) { return true; }
		}
		else 
		{
			if ((intYear % 4) == 0) { return true; }
		}
		return false;
	}

	function doDateCheck(from, to) 
	{
		if (Date.parse(from.value) <= Date.parse(to.value)) 
		{
			alert("The dates are valid.");
		}
		else 
		{
			if (from.value == "" || to.value == "") 
				alert("Both dates must be entered.");
			else 
				alert("To date must occur after the from date.");
		}
	}

	function OffsetDateByMonths(dtDate, nMonths)
	{
		var m = dtDate.getMonth() + nMonths;
		var d = (nMonths <0)?-12:12;		
		var yFactor = Math.floor(m /d);
		var mFactor = (yFactor >0)?m - (d *yFactor):m;
	
		return new Date(dtDate.getFullYear() + yFactor, mFactor, dtDate.getDate());
	}

	function SetEpoch(strYear)
	{
		//using 1930 as epoch
		if(parseInt(strYear) >30)
			return '19' + strYear;
		else
			return '20' + strYear;
	}

		
	function SetAddressValues(values)
	{
		if(null != values)
		{			
			document.all.txtAddress1.value = values[0];
			document.all.txtAddress2.value = values[1];
			document.all.txtAddress3.value = values[2];
			document.all.txtAddress4.value = values[3];
			document.all.txtAddress5.value = values[4];
			document.all.txtPostCode.value = values[5];							
			document.all.txtCounty.value = values[6];
			document.all.txtUPRN.value = values[7];
		}
	}
	
	function CheckAscDecimal(txtBox)
	{
		if ((event.keyCode<48||event.keyCode>57) && event.keyCode!=46)
		{
			return false;
		}
		
		if (event.keyCode==46 && txtBox.value.indexOf(".")!=-1)
		{
			return false;
		}	
	}
	
	function CheckAsc()
	{
		if (event.keyCode<48||event.keyCode>57)
			return false;
	}
	
	function CheckDecimalPlaces(intDecimalPlaces,txtBox)
	{		
		if ((event.keyCode<48||event.keyCode>57) && event.keyCode!=46)
		{
			return false;
		}
		
		if (event.keyCode==46 && txtBox.value.indexOf(".")!=-1)
		{
			return false;
		}
		if (txtBox.value.indexOf(".")!=-1)
		{				
			if((txtBox.value.length-txtBox.value.indexOf("."))>parseInt(intDecimalPlaces))
			{
				return false;
			}
		}
	}
	
	function CheckMaxAge(objTextBox,intMaxAge)
	{
		if (parseInt(objTextBox.value)>intMaxAge)
		{
			alert("Age cannot be greater than " + intMaxAge + ".");
			objTextBox.value="";
			objTextBox.focus();
			return false; 
		}
		return true;
	}

	function MakeNumeric(ctl)
	{
		if(!CheckValidNumeric(ctl.value))
		{
			ctl.value='';
		}
	}

	function GetNumeric(ctl)
	{
		if(null==ctl)return 0;
		var val=parseInt(ctl.value);
		return(isNaN(val))?0:val;	
	}
	
	function ConvertUpper(objTextBox)
	{
		var strVal;
		strVal=objTextBox.value;	
		objTextBox.value=strVal.toUpperCase();
		
	}

	String.prototype.trim = function() 
	{
		return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");
	}
	String.prototype.asId = function()
	{
		return (isNaN(this))?'0':this;
	}

	
	// Seting/Getting combo data
	function SetComboValue(cb, strValue)
	{
		var bSet = false;
		if(null == cb)return;
		cb.selectedIndex =0;
		for(var i=0; i<cb.length; i++)
		{
			if(cb.options[i].value==strValue && bSet == false)
			{
				cb.selectedIndex =i;
				cb.options[i].selected = true;
				bSet = true;				
			}	
			else
			{
				cb.options[i].selected = false;
			}
		}
	}
	function SetComboText(cb, strText)
	{
		if(null == cb)return;
		strText = strText.toUpperCase();
		for(var i=0; i <cb.length; i++)
		{
			if(cb.options[i].innerText.toUpperCase()==strText)
			{
				cb.selectedIndex=i;
				break;
			}	
		}
	}
	
	function GetComboText(cb)
	{
		var sel = '';
		if(null != cb)
		{
			if(null != cb.selectedIndex)
			{
				var i = cb.selectedIndex;
				if(i > -1)
					sel = cb.options[i].innerText;
			}
		}
			
		return sel.trim();
	}

	function GetComboValue(cb)
	{
		var sel = 0;
		if(null != cb)
		{
			if(null != cb.selectedIndex)
			{
				var i = cb.selectedIndex;
				if(i > -1)
					sel = cb.options[i].value;
			}	
		}
		return sel;
	}
	
	function IsValueInCombo(cb, value)
	{
		var ret = false;
		if(null != cb)
			if(null != cb.options)
				for(var i=0; i<cb.options.length; i++)
					if(cb.options[i].value==value)
					{
						i=cb.options.length;
						ret=true;
					}
		return ret;
	}
	
	
	function IsTextInCombo(cb, value)
	{
		var ret = false;
		if(null != cb)
			if(null != cb.options)
				for(var i=0; i<cb.options.length; i++)
					if(cb.options[i].innerText==value)
					{
						i=cb.options.length;
						ret=true;
					}
		return ret;
	}
	
//Grid Support functions
	function HoverOver() 
	{	
		try 
		{
			srcElem = window.event.srcElement;
			//crawl up to find the row
			while (srcElem.tagName != "TR" && srcElem.tagName != "TABLE")
				srcElem = srcElem.parentElement;

			if(srcElem.tagName != "TR") return;

			if (srcElem.rowIndex >= 1)
				hilite(srcElem);
			else
				hilite(-1);
		}
		catch (error) {}
	}

	function EndHover() 
	{
		try
		{
			hilite(-1);
		}
		catch(error) 
		{}
	}
	
	function HoverOverWithTasksListTip()
	{
		try 
		{
			srcElem = window.event.srcElement;
			//crawl up to find the row
			while (srcElem.tagName != "TR" && srcElem.tagName != "TABLE")
				srcElem = srcElem.parentElement;

			if(srcElem.tagName != "TR") return;
			
			hilite(srcElem);
			srcElem.title = 'Referral ' + srcElem.cells(1).innerText + ' for '  + srcElem.cells(2).innerText + ' ' + srcElem.cells(0).innerText + ' On: ' + srcElem.cells(3).innerText;
		}
		catch (error) {}
	}

	function EndHoverTasksList()
	{
		//will customize for TasksLists
		EndHover();
	}
	
	function hilite(newRow) 
	{
		try 
		{
			if (HColor != null ) 
			{
				if (currRow != -1 && currRow!=selRow) 
					currRow.runtimeStyle.backgroundColor = '';

				if (newRow != -1 && newRow!=selRow) 
					newRow.runtimeStyle.backgroundColor = HColor;
			}
			currRow = newRow;
		}
		catch (error) 
		{}
	}

	function GetTableName(o)
	{
		var tableName='';
		srcElem = o;
		while (srcElem.tagName != "TABLE") 
			srcElem = srcElem.parentElement;
			
		if(srcElem.tagName == "TABLE")
			tableName = srcElem.id;
			
		return tableName;
	}
	
	// Gareth Maguire 12/10/2004
	// When a datagrid is rendered, it renders a string for the boolean values.
	// This function checks the string value and returns a boolean
	function GetBooleanGridValue(strColumn)
	{
		var retval = GetGridValue(strColumn);
		if (retval.toUpperCase() == "TRUE")
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	
	
	function GetGridValue(strColumn, PreserveHTML)
	{
		var strValue='';
		PreserveHTML=(null==PreserveHTML)?false:PreserveHTML;
		srcElem = window.event.srcElement;
		while (null != srcElem && srcElem.tagName != "TR" && srcElem.tagName != "TABLE" && srcElem.tagName != "TH") 
			srcElem = srcElem.parentElement;
		if(null != srcElem)
		{
			if(srcElem.tagName == "TR")
			{	
				if(srcElem != srcElem.parentNode.rows[0])
				{
					var strCol = strColumn.toUpperCase();
					//var Ids = srcElem.parentNode.children[0];
					var Ids = GetIdRow(srcElem.parentNode);
					if(null != Ids)
					{
						for (var i=0; i<Ids.childNodes.length; i++)
						{
							if (Ids.childNodes[i].innerText.trim().toUpperCase() == strCol)
							{
								strValue=(PreserveHTML)?srcElem.childNodes[i].innerHTML:srcElem.childNodes[i].innerText.trim();
								break;
							}	
						}
					}
				}
			}
		}
		return strValue.trim();	
	}
	
	function GetGridCheckedValue(strColumn)
	{
		var strCheckedValue='';
		srcElem = window.event.srcElement;
		while (null != srcElem && srcElem.tagName != "TR" && srcElem.tagName != "TABLE" && srcElem.tagName != "TH") 
			srcElem = srcElem.parentElement;
		if(null != srcElem)
		{
			if(srcElem.tagName == "TR")
			{	
				if(srcElem != srcElem.parentNode.rows[0])
				{
					var strCol = strColumn.toUpperCase();
					
					var Ids = GetIdRow(srcElem.parentNode);
					if(null != Ids)
					{
						for (var i=0; i<Ids.childNodes.length; i++)
						{
							if (Ids.childNodes[i].innerText.trim().toUpperCase() == strCol)
							{	strCheckedValue = (srcElem.childNodes[i].childNodes[0].childNodes[0].checked==true);
							}	
						}
					}
				}
			}
		}
		return strCheckedValue;
	}
	
	function GetGridValueInRow(grid, iRowIndex, strCol)
	{
		var strUCol = strCol.toUpperCase();
		for(var p =0; p <grid.rows[0].childNodes.length; p++)
		{	
			if(grid.rows[0].childNodes[p].innerText.trim().toUpperCase() == strUCol)
			{				
				return grid.rows[iRowIndex].childNodes[p].innerText;
			}
		}
	}

	function GetGridValueByGrid(grid, column, UseHTML)
	{
		var row = null;
		var strValue = '';
		var strCol = column.toUpperCase();
		if(null != grid)
		{
			row = SetGridSelectedById(grid);
			if(null != row)
			{
				var Ids = GetIdRow(grid);
				if(null != Ids)
				{
					for (var i=0; i<Ids.childNodes.length; i++)
					{
						if (Ids.childNodes[i].innerText.trim().toUpperCase() == strCol)
						{
							strValue=(null != UseHTML && UseHTML)?row.childNodes[i].innerHTML:row.childNodes[i].innerText.trim();
							break;
						}	
					}
				}
			}
		}
		return strValue;
	}
	
	function GetGridValueByIndex(index, PreserveHTML)
	{
		var strValue='';
		PreserveHTML=(null==PreserveHTML)?false:PreserveHTML;
		srcElem = window.event.srcElement;
		while (null != srcElem && srcElem.tagName != "TR" && srcElem.tagName != "TABLE" && srcElem.tagName != "TH") 
			srcElem = srcElem.parentElement;
		if(null != srcElem)
		{
			if(srcElem.tagName == "TR")
			{	
				if(srcElem != srcElem.parentNode.rows[0])
				{
					var Ids = GetIdRow(srcElem.parentNode);
					if(null != Ids)
					{
						if(index<Ids.childNodes.length+1)
						{
							strValue=(PreserveHTML)?srcElem.childNodes[index-1].innerHTML:srcElem.childNodes[index-1].innerText;
						}
					}
				}
			}
		}
		return strValue.trim();	
	}

	function SetGridSelectedItemIdEx(Id, IdHolder)
	{		
		if(null != IdHolder)
		{
			IdHolder.value = Id.asId();
			return true;
		}
		else
		{
			return false
		}
		return false;
	}
	
	function SetGridSelectedItemId(Id, doc)
	{
		var Document = (null==doc)?document:doc;
		var IdHolder = Document.all.GridSelection;
		if(null != IdHolder)
		{
			IdHolder.value = Id.asId();
			return true;
		}
		else
		{
			return false
		}
		return false;
	}	
	
	function GetGridSelectedItemId()
	{
		var strId = '';
		var IdHolder = document.all.GridSelection;
		if(null != IdHolder)
			strId = IdHolder.value;
		
		return strId;
	}
	
	function SetGridSelected()
	{
		srcElem = window.event.srcElement;
		if(null == srcElem)
		{
			SetGridSelectedById();
			return;
		}
		while (srcElem.tagName != "TR" && srcElem.tagName != "TABLE" && srcElem.tagName != "TH") 
			srcElem = srcElem.parentElement;
		
		if(srcElem.tagName != "TR") return false;
		if(srcElem.rowIndex <= 0 ) return false;
		if (selRow != -1)
		{
			selRow.runtimeStyle.backgroundColor = '';
			selRow.runtimeStyle.color = '#000000';
		}
		srcElem.runtimeStyle.backgroundColor = '#0000FF';
		srcElem.runtimeStyle.color = '#FFFFFF';
		selRow = srcElem;
		return true;
	}
	
	function SetGridSelectedById(theGrid)
	{
		selRow =-1;
		var Document=(null==theGrid)?document:theGrid.document;
		var gs = Document.all.GridSelection;
		var elem = null;
		if(null != gs && gs.value > 0)
		{
			var grid = GetGrid(theGrid);
			if(null != grid)
			{
				for(var p =0; p <grid.rows[0].childNodes.length; p++)
				{
					if(grid.rows[0].childNodes[p].innerText.trim().toUpperCase() == 'ID')
					{				
						for(var i=1; i<grid.rows.length; i++)
						{
							if(grid.rows[i].childNodes[p].innerText.trim() == gs.value)
							{
								elem = grid.rows[i];
								break;	
							}
						}
					}
				}
			}
		}
		if(null != elem)
		{
			if (selRow != -1)
			{
				selRow.runtimeStyle.backgroundColor = '';
				selRow.runtimeStyle.color = '#000000';
			}
			elem.runtimeStyle.backgroundColor = '#0000FF';
			elem.runtimeStyle.color = '#FFFFFF';
			selRow = elem;		
		}
		return elem;
	}	

	function ClearGridSelection(grid)
	{
		if(null != grid)return ResetGrid(grid);
		var gs = document.all.GridSelection;
		if(null != gs)gs.value = '0';
		if(selRow != -1)
		{
			selRow.runtimeStyle.backgroundColor = '';
			selRow.runtimeStyle.color = '#000000';
		}
	}
	
	function ResetGrid(grid)
	{
		if(null != grid && grid.tagName == 'TABLE')
		{
			for(var i =0; i <grid.rows.length; i++)
			{
				grid.rows[i].runtimeStyle.backgroundColor = '';
				grid.rows[i].runtimeStyle.color = '#000000';
			}				
		}
	}
	function GetRowById(table, id)
	{
		var row = null;
		if(null != table && table.rows.length >1)
		{
			for(var i=0; i<table.rows.length; i++)
			{
				if(IsValueInRow(table.rows[i], 'Id', id))
				{
					row = table.rows[i];
					break;
				}
			}
		}
		return row;
	}
	
	function IsValueInRow(row, item, value)
	{
		if(null != row)
		{
			var bReturn = false;
			var col = item.toUpperCase();
			var val = value.toUpperCase();
			var hdr = row.parentNode.children[0];
			var thisCol = -1;
			for(var p =0; p < hdr.childNodes.length; p++)
			{
				if(hdr.childNodes[p].innerText.trim().toUpperCase() == col)
				{
					bReturn = row.childNodes[p].innerText.trim().toUpperCase() == val
					break;
				}
			}
		}
		return bReturn;
	}
	
	//now returns the column index if value is found
	function IsValueInColumn(item, value, theGrid)
	{
		var col = item.toUpperCase();
		var val = value.toUpperCase();
		var foundRow = 0;
		var thisCol = -1;
		var grid = GetGrid(theGrid);
		if(null != grid)
		{
			var hdr = grid.rows[0];
			if(null != hdr)
			{
				for(var p =0; p <hdr.childNodes.length; p++)
				{
					if(hdr.childNodes[p].innerText.trim().toUpperCase() == col)
					{
						for(var i=1; i<grid.rows.length; i++)
						{
							if(grid.rows[i].childNodes[p].innerText.toUpperCase() == val)
							{
								bReturn = true;
								foundRow = i;
								break;
							}
						}
						break;
					}
				}
			}
		}		
		return foundRow;
	}
	
	function HideGridEntries(grid)
	{
		if(null != grid)
		{
			for(var i=1; i<grid.rows.length; i++)
				grid.rows[i].runtimeStyle.visibility='hidden';
		}
	}
	

	function ShowGridEntriesById(grid, Id)
	{
		if(null != grid && null != Id)
		{
			for(var i=1; i<grid.rows.length; i++)
				if(IsValueInRow(grid.rows[i], 'Id', Id))
					grid.rows[i].runtimeStyle.visibility='visible';
		}
	}

	function DeleteGridEntries(grid, bLeaveHeader)
	{
		if(null != grid)
		{
			var scope = (bLeaveHeader)?1:0;
			while(grid.rows.length >scope)
				grid.deleteRow(scope);
		}
	}
	
	function GetGrid(grid)
	{
		var theGrid=null;
		if(null != grid && IsValidDataGrid(grid))
		{
			theGrid = grid;
		}
		else if(null !=grid && (grid.tagName=='TR' || grid.tagName=='TD'))
		{
			while (grid.tagName != "TR" && grid.tagName != "TH") 
				grid = grid.parentElement;
			if(grid.tagName =='TR')
				theGrid = grid.parentElement;
			if(theGrid.tagName == 'TBODY')
				theGrid = theGrid.parentElement;
		}
		else
		{
			var aGrid = document.getElementsByTagName('TABLE');
			if(IsValidDataGrid(aGrid))
				theGrid = aGrid[0];
		}
		return theGrid;
	}
	
	function IsValidDataGrid(grid)
	{
		if(null == grid)return false;
		return (null != grid && null != grid[0] && grid[0].className=='DataTable') || (grid.className=='DataTable');
	}

	function GetIdRow(grid)
	{
		var row = null;
		if(grid.tagName == 'TABLE')
			if(grid.childNodes[0].tagName == 'TBODY')
				row = grid.childNodes[0].childNodes[0];
			else
				row = grid.childNodes[0];
		else if(grid.tagName=='TBODY')
			row = grid.childNodes[0]
		
		return row;
	}
	
	function SetLBSelected()
	{
		var lb = document.getElementsByTagName('SELECT');
		if(null != lb)
		{
			var id = document.all.LBSelection.value;
			if(id > '0')
				SetLBSelectedById(lb, id);
		}
	}

	function SetLBSelectedById(lb, id)
	{
		if(null != lb && null != id && id > '0')
		{
			for(var o in lb.options)
			{
				if(o.value == id)
				{
					o.setAttribute('selected', true);
					return true;
				}
			}
		} 
	}
	
	function GetLBSelectedID()
	{
		var id = '0';
		var lb = window.event.srcElement;
		while (srcElem.tagName != "SELECT") 
			srcElem = srcElem.parentElement;
		
		if(srcElem.tagName != "SELECT") return;
		if(srcElem.selectedIndex <= 0 ) return;
		{
			id = srcElem.value;
		}
		return id;
	}
	
	function GetLBSelectedItem()
	{
		var item = window.event.srcElement;
		if(null != item)
		{
			if(item.tagName == 'OPTION')
				return item;
			else if(item.tagName == 'SELECT')
				return item.options[item.selectedIndex];
		}
	}
	
	function ClearLBSelection()
	{
		var lb=document.getElementsByTagName('SELECT');
		if(null != lb && lb.length >0)
			lb[0].selectedIndex=-1;
	}
	
	function IsItemInLB(lb, item)
	{
		if(null != lb && null != item)
		{
			for(var i =0; i <lb.options.length; i ++)
			{
				if(lb.options[i].value == item)
					return true;
			}
		}
	}
 
	function GetAge(birthdate, ctl)		//MQ 20/4/04 unfinished need to incorporate Date of Death
	{
    	var strReturn = '';
    	 var arr = new Array("9");
	var elm = ServerRequest(arr, '../common/DocumentRequest.aspx', false);
			if(null!=elm)
			       {
		 //bInUse=elm.text;
			var today = new Date(elm.text);
				   }
			   else
				  {
    		var today = new Date();
    				}
    	var bday = new Date(birthdate);
    	try
    	{
    		bday.setUTCDate(bday.getDate() -1);
    		var difference = Date.UTC(today.getYear(), today.getMonth(), today.getDate(),0,0,0)
      					   - Date.UTC(bday.getYear(), bday.getMonth(), bday.getDate(),0,0,0);
	      				   
    		var val = Math.floor(difference /1000/60/60/24/365.25);
    		if(val > 0)strReturn = val.toString();
    	}
    	catch(e){}
    	if(null != ctl)
    		ctl.value = strReturn;
    		
    	return strReturn;
	}
	
	function GetSessionClientNo()
	{
		var iClientNo = 0;
		var bRet = false;
		var arr = new Array("10", "0", "0");
		var elm = ServerRequest(arr, '../common/DocumentRequest.aspx', false);
		if(null!=elm)
			if(null!=elm.childNodes[0])iClientNo=elm.text;
		
		return iClientNo;
	}
	
	function GetSessionRefEnabled()
	{
		var bRefEnabled = false;
		var bRet = false;
		var arr = new Array("12", "0", "0");
		var elm = ServerRequest(arr, '../common/DocumentRequest.aspx', false);
		if(null!=elm)
			if(null!=elm.childNodes[0])bRefEnabled=(elm.text=='true');
		
		return bRefEnabled;
	}
	
	//created by MQ 16/4/04 cause above func(GetAge) takes todays date from Client computer.
	// GetAge gets called from clientdetails.aspx(twice), clientrelatinoships.aspx and adoption.js	
	// if the client isnt dead then the webserver current date is return using serverrequest
	//if they both are null then the current date from the client is returned
	function GetAgeNew(birthDate, deathDate, ctl)
	{
		var strReturn = '';
		if ( birthDate.length>0)
		{
			var elm = "";
			if (null!=deathDate && deathDate.length > 0)
			{
				elm = new Date(deathDate);
			}
			else//not dead
			{
				var arr = new Array("9");//get the webservers current date
				var req = ServerRequest(arr, '../common/DocumentRequest.aspx', false);
				if(null!=req)
				{
					elm = new Date(req.text);
				}
			}
			if (elm == null)
			{
				elm = new Date();
			} 
    		var bday = new Date(birthDate);
    		try
    		{
				var difference = Date.UTC(elm.getYear(), elm.getMonth(), elm.getDate(),0,0,0)
      							- Date.UTC(bday.getYear(), bday.getMonth(), bday.getDate(),0,0,0);
				var val = Math.floor(difference /1000/60/60/24/365.25);
				if(val >= 0)strReturn = val.toString();
    		}    		 
    		catch(e){}
    	}
    	if(null != ctl)
    	ctl.value = strReturn;
		return strReturn;    			
	}
	
	function CompareDates(strLoDate, strHiDate, strLoName,  strHiName)
	{
		var bReturn = true; //assumption valid 
		try
		{
			var d1 = new Date(strLoDate);
			var d2 = new Date(strHiDate);
		}
		catch(e){}
		if(null != d1 && null != d2 &&(d1 > d2))
		{
			bReturn= false;
			if(null != strLoName && null != strHiName && strLoName != '' && strHiName != '')
				alert(strLoName + ' cannot be greater than ' + strHiName);
		}
		
		return bReturn;
	}
	
	function CompareDateofBirth(tb)
	{
		try
		{
		var td = new Date();
		var db = new Date(tb.value);
		}
		catch(e){ }
		if (null != td && null != db &&(db>td))
		{
			tb.value='';
			alert('Entered Date Can not be Greater than Todays Date');
			tb.value='';
			tb.focus();
		}
	}

	function CheckValidDate(ctl)
	{
		try
		{
			var ad = new Date(ctl.value);
			if(null == ad || 'NaN' == ad)
			{
				return false;
			}
		}
		catch(e)
		{
			return false;
		}
		return true;
	}
	
	function CheckValidNumeric(strNumbers) 
	{
		var Parsed = parseInt(strNumbers).toString();
		
		if (isNaN(Parsed)) 
			return false;
		
		if (Parsed.length != strNumbers.length)
		{
			return false;
		}
		return true;
	}
	
	function CheckValidInt32(strNumbers) 
	{
		if ((CheckValidNumeric(strNumbers)) && ( strNumbers <= 2147483647)) 
			return true;
		return false;
	}
	
	function FlipCheckBoxes(b1, b2, b3, b4, b5)
	{
		var b = window.event.srcElement;
		var bChecked = false;
		if(null != b && (b.tagName == 'INPUT' && b.getAttribute('type')=='checkbox'))
		{
			if(null != b1 && b != b1)b1.checked = bChecked;
			if(null != b2 && b != b2)b2.checked = bChecked;
			if(null != b3 && b != b3)b3.checked = bChecked;
			if(null != b4 && b != b4)b4.checked = bChecked;
			if(null != b5 && b != b5)b5.checked = bChecked;
		}
	}
	
	function GetCheckBoxList(ctl)
	{
		var strArr = '';
		if (ctl.currentStyle.layoutFlow == 'horizontal')
		{
			for(var i =0; i <ctl.cells.length; i ++)
			{
				var item = ctl.cells[i];
				if(null != item && IsCheckListItemChecked(item, 'horizontal'))
					strArr += ',' + GetCheckListBoxItemValue(item, 'horizontal');
			}
		}
		else
		{
			for(var i =0; i <ctl.rows.length; i++)
			{
				var item = ctl.rows[i];
				if(null != item && IsCheckListItemChecked(item))
					strArr += ',' + GetCheckListBoxItemValue(item);	
			}
		}
		return strArr.substring(1);
	}
		
	function GetLeft(o)
	{
		var l = 0;
		var p=o;
		for(;p!=null;p=p.offsetParent)
		{
			l+=p.offsetLeft;	
		}
		return l;	
	}
	function GetTop(o)
	{
		var t = o.offsetHeight;
		var p = o;
		for(;p!=null;p=p.offsetParent)
		{
			t+=p.offsetTop +1;	
		}
		return t;	
	}

	function ShowMsgYN()
	{
		if(null != document.all.DlgMsgYN && document.all.DlgMsgYN.value != '')
		{
			var s = document.all.DlgMsgYN.value;
			if(s.substring(0, 6) == '*CODE*' && s.length > 10)
			{
					var fcode = s.substring(7);
					var funcs = fcode.split('|');
					if(funcs.length)
					{
						for(var i =0; i <funcs.length; i++)
						{
							window.execScript(funcs[i]);
						}
					}
			}
			else
			{	
				var bConfirm = window.confirm(s);
				document.all.DlgMsgYNResponse.value=bConfirm;
				
				document.all.DlgMsgYN.value = '';
				
				if(bConfirm==true)__doPostBack('','');
			}			
				
		}
		
		document.all.DlgMsgYN.value = '';
		PageOnLoadStuff();
	}

	function ShowMsg()
	{
		if(null != document.all.DlgMsg && document.all.DlgMsg.value != '')
		{
			var s = document.all.DlgMsg.value;
			if(s.substring(0, 6) == '*CODE*' && s.length > 10)
			{
				var re = /\*CODE\*/gi;
				var fcode = s.replace(re, '');
				while(fcode.indexOf('*CODE*')>-1)
					fcode = fcode.replace(re, '');
				var funcs = fcode.split('|');
				if(funcs.length)
				{
					for(var i =0; i <funcs.length; i++)
					{
						try 
							{window.execScript(funcs[i]);}
						catch (ex) 
							{alert(ex.message + ' ' + funcs[i]);}
					}
				}
			}			
			else
			{
				var strMessage="";
				var strVal=s.split("/n")
				for (i=0;i<strVal.length;i++)
				{	
					if (i==0)
					{					
						strMessage=strVal[i];
					}else
					{
						strMessage=strMessage+ "\n" + strVal[i];
					}
				}
				if (strMessage!="")
				{
					alert(strMessage);
				}else
				{
					alert(s);
				}
			}
			document.all.DlgMsg.value = '';					
		}
		PageOnLoadStuff();
	}
	
	function ConfirmDelete(item)
	{
		var thisItem = 'this item';
		if(null != item && item.length >0)thisItem=item;
		return window.confirm('Are you sure you want to Delete ' + thisItem + '?');
	}

	function ConfirmCancel(item)
	{
		var thisItem = 'this item';
		if(null != item && item.length >0)thisItem=item;
		return window.confirm('Are you sure you want to Cancel ' + thisItem + '?');
	}

	function ConfirmSave(item)
	{
		var thisItem = 'this item';
		if(null != item && item.length >0)thisItem=item;
		return window.confirm('Are you sure you want to Save ' + thisItem + '?');
	}


	function ConfirmInsert(item)
	{
		var thisItem = '';
		if(null != item && item.length >0)thisItem=item;
		return window.confirm('Are you sure you want to create a new ' + thisItem + ' record?');
	}

	function ConfirmQuit()
	{
		return window.confirm('Are you sure you want to Exit?');
	}

	function ConfirmUpdate(item)
	{
		var thisItem = 'this item';
		if(null != item && item.length >0)thisItem=item;
		return window.confirm('Are you sure you want to Update ' + thisItem + '?');
	}
	
	function NotAvailable()
	{
		alert('Not available in this release.');
		return false;
	}

	function ShowCalendar(ctl)
	{
		if(window.top.iCal!=null)
			window.top.iCal.ShowCalendar(ctl, true);
		else if(iCal!=null)
			iCal.ShowCalendar(ctl,true);
	}	
	
	function ShowCalendar(ctl, l, t)
	{
		var vErr;
		if(window.top.iCal!=null)
			window.top.iCal.ShowCalendar(ctl, l, t);
		else
			try
			    {
			    if(iCal!=null)
			        {
			        iCal.ShowCalendar(ctl, l, t);
			        }
			    }
			catch(vErr)
			    {
			    }
		
	}	

	function ShowCalendar(ctl, l, t, SetDirty, fnCallBack)
	{
		var vErr;
		if(window.top.iCal!=null)
			window.top.iCal.ShowCalendar(ctl, l, t, SetDirty, fnCallBack);
		else
			try
			    {
			    if(iCal!=null)
			        {
			        iCal.ShowCalendar(ctl, l, t, SetDirty, fnCallBack);
			        }
			    }
			catch(vErr)
			    {
			    }
		
	}	
	
	function MainPage(depth)
	{
		window.location.href = GetPathOffset(depth) + '../SupplierGlobalUprate/SupGlobalUpratePage.aspx';
	}
	
	function GetListFromXml(nodeName, startRoot, cb, killCB, cbOverride, bAllOption, cbFourth, bNonUniqueIds, iOverrideValue, bBlankRow)
	{
		var list = document.all.item(nodeName);
		var src = window.event.srcElement;	
		if(null != cbOverride)src = cbOverride;
		if(null != iOverrideValue) src = iOverrideValue;
		if(null == bNonUniqueIds)bNonUniqueIds = false;
		if(null == bBlankRow) bBlankRow = true;
		if(null == cb) return;
		if(cb.tagName == 'TABLE' && (src.tagName == 'INPUT' || src.tagName == 'TABLE'))
		{
			GetCheckListFromXml(src, cb, nodeName, startRoot);
			return;
		}
		cb.innerHTML = '<OPTION></OPTION>';
		if(null != killCB)killCB.innerHTML = '<OPTION>' + (bAllOption)?'All':'' + '</OPTION>';
		if(null != src && (null !=iOverrideValue || (null == iOverrideValue && src.tagName == 'SELECT')) && null != list && null != list.XMLDocument)
		{
			var strXP = '';
			var iCat = (null==iOverrideValue)?GetComboValue(src):iOverrideValue;
			if(iCat =='0' && bAllOption)
			{
				var strXP = (startRoot =='A')?'/*/*/*':'/*/*/*/*';
			}
			else
			{
				if((startRoot.length <5) || bNonUniqueIds )
				{
					strXP = startRoot + '[@i="' + iCat + '"]/*';
				}
				else
				{
					var p4 = (null!=cbFourth)?'[@i="' + GetComboValue(cbFourth) + '"]':'';
					strXP = 'A/B' + p4 + '/C[@i="' + iCat + '"]/*'; 
				}
			}
			var XmlNodes = list.XMLDocument.documentElement.selectNodes(strXP);
			if(null!=XmlNodes)
				FillDropdownFromXmlNodeList(cb, XmlNodes, bAllOption, bBlankRow);	
		}
	}

		function GetListFromXmlWithDupes(nodeName, cbA, cbB, cbC, killCB, bAllOption)
	{
		var list = document.all.item(nodeName);	
		var i=0;
		var j=0;
		var k=0;
		var l=0;	
		cbC.innerHTML = '<OPTION></OPTION>';
		var opt = document.createElement("OPTION");
		cbC.options.add(opt);
		opt.value =0 
		if (bAllOption==true)
		{
			opt.innerText ="All"
		}else
		{
			opt.innerText =""
		}
		if(null != killCB)killCB.innerHTML = '<OPTION>' + (bAllOption)?'All':'' + '</OPTION>';
		if(null != cbA && cbA.tagName == 'SELECT' && null != cbB && null != list.XMLDocument)
		{
			var strXP = '';					
			var iComboA=GetComboValue(cbA);
			var iComboB=GetComboValue(cbB);
			var iXmlAValue="";
			var iXmlBValue="";
			
			if(iComboB =='0')
			{						
			}
			else
			{
				for (i=0;i<list.XMLDocument.childNodes.length;i++)
				{
					for (j=0;j<list.XMLDocument.childNodes[i].childNodes.length;j++)
					{
						iXmlAValue=list.XMLDocument.childNodes[i].childNodes[j].getAttribute('i');
						if (iComboA==iXmlAValue)
						{
							for (k=0;k<list.XMLDocument.childNodes[i].childNodes[j].childNodes.length;k++)
							{
								iXmlBValue=list.XMLDocument.childNodes[i].childNodes[j].childNodes[k].getAttribute('i');
								if (iComboB==iXmlBValue)
								{
									for (l=0;l<list.XMLDocument.childNodes[i].childNodes[j].childNodes[k].childNodes.length;l++)
									{
										var opt = document.createElement("OPTION");
										cbC.options.add(opt);
										opt.value = list.XMLDocument.childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('i');
										opt.innerText = list.XMLDocument.childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('d');												
									}
								}
							}
						}
					}
				}
			}					
		}
	}

	function FillDropdownFromXmlNodeListForUsers(cb, XmlNodes, bAllOption)
	{
		if(null==cb)return;
		if(null != XmlNodes)
		{
			var bAll=(null!=bAllOption)?bAllOption:false;
			//var opt0 = document.createElement("OPTION");
			//cb.options.add(opt0);
			//if(bAll)cb.options[0].innerText='';
			//cb.options[0].value='0';
			
			RefreshDropDown(cb, true);
			
			for(var i=0; i<XmlNodes.childNodes.length; i++)
			{
				var opt = document.createElement("OPTION");
				var dist = XmlNodes.childNodes[i].childNodes[0];
				var dist1 = XmlNodes.childNodes[i].childNodes[1];
				if(dist.text != "0")
				{
					if(null!=dist1 && null!=dist)
					{
						cb.options.add(opt);
						opt.innerText = dist1.text;
						opt.value = dist.text;
					}
					//}
				}
			}
		}
	}
	
	
	function FillDropdownFromXmlNodeList(cb, XmlNodes, bAllOption, bBlankRow)
	{
		
		if(null==cb)return;
		if(null != XmlNodes)
		{
			var bAll=(null!=bAllOption)?bAllOption:false;
			var bBlank = (null != bBlankRow)? bBlankRow : true;
			
			var iIndex = 0;
			if (bBlank)
			{
				var opt = document.createElement("OPTION");
				cb.options.add(opt);
				cb.options[iIndex].value= iIndex;
				iIndex++;
			}			
			
			if (bAll)
			{
				var opt = document.createElement("OPTION");
				cb.options.add(opt);
				cb.options[iIndex].innerText = 'All';
				cb.options[iIndex].value = iIndex;
			}
				
			for(var i=0; i<XmlNodes.length; i++)
			{
				var opt = document.createElement("OPTION");
				var dist = XmlNodes[i].getAttribute('i');
				if(!IsValueInCombo(cb, dist))
				{
					cb.options.add(opt);
					opt.innerText = XmlNodes[i].getAttribute('d');
					opt.value = dist;
				}
			}
		}
	}
	
	function RefreshDropDown(cb, blankOpt)
	{
	
	
		while(cb.options.length > 0)
		{
			cb.options.remove(0);
		}
	
		if(blankOpt)
		{
			var opt = document.createElement("OPTION");
			cb.options.add(opt);
			cb.options[0].innerText='';
			cb.options[0].value='0';
		}
	
	}
	
	
	
	//To Get the Attribute Value for Xml with two level of nesting A, A/B
	//nodeName - name of the XML ; StartRoot - to Indicate Level A or A/B, idAttribute - the unique attribute name
	//nodeId - the value of the attribute, attribute - attribute name for which to return the value
	function GetAttributeFromXml(nodeName,startRoot,idAttribute,nodeId,attribute)
	{
		var list = document.all.item(nodeName);
		var attr = '';
		if (null != list)
		{
			var strXP = (startRoot =='A')?'/*/'+ startRoot:'/*/' + startRoot;
			strXP = strXP + '[@'+ idAttribute + '="'+ nodeId + '"]';
			
			var XmlNodes = list.XMLDocument.documentElement.selectNodes(strXP);
			if (null != XmlNodes)
			{
				if (XmlNodes.length > 0) attr = XmlNodes[0].getAttribute(attribute);
			}	
		}		
		return attr;
	}
	
	//To Get the Attribute Value for Xml with two level of nesting A, A/B
	//nodeName - name of the XML ; StartRoot - to Indicate Level A or A/B, idAttribute - the unique attribute name
	//nodeId - the value of the attribute, attribute - attribute name for which to return the value
	function GetNodesListFromXml(nodeName,startRoot,idAttribute,nodeId)
	{
		var list = document.all.item(nodeName);
		var XmlNodes = '';
		if (null != list)
		{
			var strXP = (startRoot =='A')?'/*/' + startRoot:'/*/' + startRoot;
			strXP = strXP + '[@'+ idAttribute + '="'+ nodeId + '"]/*';
			
			XmlNodes = list.XMLDocument.documentElement.selectNodes(strXP);				
		}		
		return XmlNodes;
	}
	
	
	function GetCheckListFromXml(src, cb, nodeName, startRoot)
	{
		DeleteGridEntries(cb, false);
		var IsList = (src.tagName == 'TABLE')?true:false;
		var iCat = '0';
		if(!IsList && !src.checked)return;
		var list = document.all.item(nodeName);
		if(null != src && (src.tagName == 'INPUT' || src.tagName == 'TABLE') && null != cb && null != list && null != list.XMLDocument)
		{
			iCat = (IsList)?GetCheckListSelectedItemText(src):src.offsetParent.children[1].innerText;
			var strXP = startRoot + '[@d="' + iCat + '"]/*';
			var nodCat = list.XMLDocument.documentElement.selectNodes(strXP);
			if(null != nodCat)
			{
				for(var i=0; i<nodCat.length; i++)
				{
					AddCheckListItem(cb, nodCat[i].getAttribute('d'), nodCat[i].getAttribute('i'));
				}
			}
		}
	}
	
	function GetItemsFromXml(nodeName, startRoot, tb1, tb2)
	{
		var list = document.all.item(nodeName);
		var src = window.event.srcElement;	
		if(null != src && src.tagName == 'SELECT' && null != list && null != list.XMLDocument)
		{
			var iCoord = GetComboValue(src);
			var strXP = '/*/*[@i="' + iCoord + '"]/*';
			var nodCoord = list.XMLDocument.documentElement.selectNodes(strXP);
			if(null != nodCoord)
			{
				if(null != tb1 && nodCoord.length)
				{	
					var val = nodCoord[0].childNodes[0];
					tb1.value = (null==val)?'':val.text;
				}
				if(null != tb2 && nodCoord.length)
				{	
					var val = nodCoord[1].childNodes[0];
					tb2.value = (null==val)?'':val.text;
				}
			}
		}	
	}
	function GetCheckListSelectedItemText(src)
	{
		var strRet = null;
		if(null != src && src.tagName == 'TABLE')
		{
			for(var i =0; i <src.rows.length; i ++)
			{
				if(src.rows[i].cells[0].childNodes[0].checked)
				{
					strRet = src.rows[i].cells[0].childNodes[1].innerText;
					break;
				}
			}
		}
		return strRet;
	}
	
	function GetCheckListSelectedItemValue(src)
	{
		var strRet = null;
		if(null != src && src.tagName == 'TABLE')
		{
			for(var i =0; i <src.rows.length; i ++)
			{
				if(src.rows[i].cells[0].childNodes[0].checked)
				{
					//strRet = src.rows[i].cells[0].childNodes[0].id;
					//strRet = strRet.substring(strRet.indexOf(src.id) + src.id.length +1);
					strRet = GetCheckListItemValue(src.rows[i].cells[0].childNodes[0]);
					break;
				}
			}
		}
		return strRet;
	}

	function SetCheckListSelectedItemText(value, ctl)
	{
		if(null != ctl && ctl.tagName == 'TABLE')
		{
			for(var i =0; i <ctl.rows.length; i ++)
			{
				if(ctl.rows[i].cells[0].childNodes[1].innerText == value)
				{
					src.rows[i].cells[0].childNodes[0].checked = true;
					break;
				}
			}
		}
	}
	
	function SetCheckListSelectedItemValue(value, ctl, strHorizontal)
	{
		if(null == ctl)return;
		value = ctl.id + '_' + (parseInt(value) -1).toString();
		
		if(null != ctl && ctl.tagName == 'TABLE')
		{
			
			if( strHorizontal == null )
			{
				for(var i =0; i <ctl.rows.length; i ++)
				{
					if(ctl.rows[i].cells[0].childNodes[0].id == value)
		
					{
						ctl.rows[i].cells[0].childNodes[0].checked = true;
						break;
					}
				}
			}
			else
			{
				for(var i =0; i <ctl.cells.length; i ++)
				{
					if(ctl.cells[i].childNodes[0].childNodes[0].id == value)
					{
						ctl.cells[i].childNodes[0].childNodes[0].checked = true;
						break;
					}
				}
		
			}
		}
	}
	
	function SetRadioListSelectedItemValue(value, ctl, strHorizontal)
	{
		if(null == ctl)return;

		value = ctl.id + '_' + (parseInt(value) -1).toString();
		
		if(null != ctl && ctl.tagName == 'TABLE')
		{
			
			if( strHorizontal == null )
			{
				for(var i =0; i <ctl.rows.length; i ++)
				{
					if((null != ctl.rows[i].cells[0].childNodes[0].id) && (ctl.rows[i].cells[0].childNodes[0].id == value))
					{
						ctl.rows[i].cells[0].childNodes[0].checked = true;
						break;
					}
				}
			}
			else
			{
				for(var i =0; i <ctl.cells.length; i ++)
				{
					if((null != ctl.cells[i].childNodes[0].id) && (ctl.cells[i].childNodes[0].id == value))
					{
						ctl.cells[i].childNodes[0].checked = true;
						break;
					}
				}
		
			}
		}
}
	
	function IsCheckListItemChecked(item, strHorizontal)
	{
		var thing;
		if (strHorizontal != null)
			thing = item.childNodes[0];
		else
			thing = item.cells[0].childNodes[0];
		
		if(thing.tagName=='SPAN')
			return thing.childNodes[0].checked;
		else
			return thing.checked;
	}
	
	function GetCheckListBoxItemValue(item, strHorizontal)
	{	
		var thing;
		if (strHorizontal != null)
			thing = item.childNodes[0];
		else
			thing = item.cells[0].childNodes[0];
			
		var chkbx = null;
		if(null != thing)
		{
			if(thing.tagName=='SPAN' && thing.childNodes.length)
				chkbx = thing.childNodes[0];
			else
				chkbx = thing;				
		}		
		return GetCheckListItemValue(chkbx);
	}
	
	function GetCheckListItemValue(item)
	{	if(null == item)return '';
		var value = item.getAttribute('value');
		if(null != value)return value;
		var strRet = item.id;		
		while (item.tagName != 'TABLE') 
			item = item.parentElement;
						
		if(item.tagName == 'TABLE')
			strRet = strRet.replace(item.id + '_', '');
			
		try
		{
			strRet = (parseInt(strRet) +1);
		}
		catch(e)
		{
			strRet = '0';
		}
			
		return strRet;
	}
	
	function GetCheckListItemText(item)
	{
		return item.nextSibling.innerText;
	}
	
	function AddCheckListItem(list, item, value)
	{
		if(null != list && list.tagName == 'TABLE')
		{
			var id = list.id;
			var num = list.rows.length;
			var row = list.insertRow(-1);
			var cell = row.insertCell();
			cell.innerHTML = CheckListItem.replace(/ItemId/, id + '_' + num ).replace(/ItemName/, id + ':' + num).replace(/ItemValue/, item);
		}
	}
	
	function ClearCheckListChecks(list)
	{
		if(null != list && list.tagName == 'TABLE')
			if (list.currentStyle.layoutFlow == 'horizontal')
			{
				for(var i =0; i <list.cells.length; i ++)
					list.cells[i].childNodes[0].checked = false;
			}
			else
			{
				for(var i =0; i <list.rows.length; i ++)
					list.rows[i].cells[0].childNodes[0].checked = false;
			}
	}
	
	function SetBanner(s)
	{
		//return;
		var f = window.parent.document;
		if(null != f)
		{
			var hr=window.parent.location.href;
			if(hr.indexOf('OrganizationsPage.aspx')>-1 || hr.indexOf('ClientPage.aspx')>-1 )
			{
				if(null ==s && null !=document.all.hidBanner)s = document.all.hidBanner.value
				if(null !=f.all.lblClientCaption && null != s)f.all.lblClientCaption.innerText = s;
				if(null != f.all.TabStrip1)
				{
					
				}
			}
			/*
			else
			{
				f.all.lblCaption.innerText = s;
			}
			*/
		}
	}
	
	function FlipUpdateDeleteButtons(bOn)
	{
		var d = document.all;
		var s = d.asb;
		if(null != s)
		{
			var canUpdate = (s.value.indexOf('True|')>-1);
			var canDelete = (s.value.indexOf('|True')>-1);
			if(null != d.btnDelete)
				EnableButton(d.btnDelete, (canDelete)?bOn:false);
			if(null != d.btnUpdate)
			{
				d.btnUpdate.className = (!bOn)?'btnInsert':'btnUpdate';
				EnableButton(d.btnUpdate, canUpdate);
				d.btnUpdate.value = '';
				if(!bOn){ClearGridSelection();} //ClearLBSelection();}
				if(null != d.frmAction)d.frmAction.value = d.btnUpdate.className.replace('btn','');
			}
		}
	}
	
	function FlipUpdateDeleteButtons2(bOn)
	{
		var d = document.all;
		var s = d.asb;
		if(null != s)
		{
			var canUpdate = (s.value.indexOf('True|')>-1);
			var canDelete = (s.value.indexOf('|True')>-1);
			if(null != d.btnDelete2)
				EnableButton(d.btnDelete2, (canDelete)?bOn:false);
			if(null != d.btnUpdate2)
			{
				d.btnUpdate2.className = (!bOn)?'btnInsert':'btnUpdate';
				EnableButton(d.btnUpdate2, canUpdate);
				d.btnUpdate2.value = '';
				if(!bOn){ClearGridSelection();} //ClearLBSelection();}
				if(null != d.frmAction)d.frmAction.value = d.btnUpdate2.className.replace('btn','');
			}
		}
	}
	
	function SetButtons()
	{
		
		var d = document.all;
		if(null != d.asb)
		{
			var s = '';
			var b = null;
			var canUpdate = false;
			var canDelete = false;
			s = d.asb.value;
			if('Truetrue'.indexOf(s)>=0)b = true;
			else if(s == 'False')b = false;				
			canUpdate = (null==b)?(s.indexOf('True|')>-1):b;
			canDelete = (null==b)?(s.indexOf('|True')>-1):b;
			if(null != d.btnUpdate)EnableButton(d.btnUpdate, (!d.btnUpdate.disabled)?canUpdate:false);
			if(null != d.btnInsert)EnableButton(d.btnInsert, (!d.btnInsert.disabled)?canUpdate:false);
			if(null != d.btnNew)EnableButton(d.btnNew, (!d.btnNew.disabled)?canUpdate:false);
			if(null != d.btnDelete)EnableButton(d.btnDelete, (!d.btnDelete.disabled)?canDelete:false);
		}
		else
		{
			var butts = document.getElementsByTagName('INPUT');
			for(var i=0; i< butts.length; i++)
			{
				if('.submit.button'.indexOf(butts[i].type)>0)
					EnableButton(butts[i], !butts[i].disabled);
			}
		}
		if(null != d.frmAction)
			d.frmAction.value = (null != d.btnUpdate)?d.btnUpdate.className.substring(3):'';
	}

	function ZoomText(tb, disabled, depth,intMaxLength)
	{	//disabled is the status of the parents updateBtn enabled - when disabled we dont want the user to be able to add new Zoom text // MQ	 7/5/04
		//var res = window.showModalDialog(GetPathOffset(depth) + '../common/TextZoom.htm' + rVal() + '?isDisabled=' + disabled,tb,'dialogheight:350px;dialogwidth:435px;dialogtop:200;dialogleft:100;resizable:no;help:no;status:no');
		var res = window.showModalDialog(GetPathOffset(depth) + '../common/ZoomText.aspx' + rVal() + '&isDisabled=' + disabled + '&MaxLength=' + intMaxLength ,tb,'dialogheight:350px;dialogwidth:435px;dialogtop:200;dialogleft:100;resizable:no;help:no;status:no');
		//var res = window.showModalDialog(GetPathOffset(depth) + '../common/TextZoom.htm' + rVal() ,tb,'dialogheight:350px;dialogwidth:435px;dialogtop:200;dialogleft:100;resizable:yes;help:no;status:no');
		if(null!=res)tb.value=res;
	}
	function GetPathOffset(depth)
	{
		var p = '';
		if(null !=depth)
		{
			var d = parseInt(depth);
			for(var i =0; i <depth; i ++)
				p += OnePath;
		}
		return p;
	}

//Utility stuff
	function rVal()
	{
		
		var d = new Date();		
		return '?rv=' + d.getTime();
		
	}

	function SelectItem(item)
	{
		try 
		{			
			srcElem = window.event.srcElement;
			//crawl up to find the row
			while (srcElem.tagName != "TR" && srcElem.tagName != "TABLE")
				srcElem = srcElem.parentElement;

			if(srcElem.tagName != "TR") return;
			
			if(srcElem.cells.length > 3 && srcElem.cells(0).innerText == 'Referral')
			{
				var RefNo = srcElem.cells(2).innerText;
				var varClientNumber = srcElem.cells(6).innerText;
				SetCurrentClientRefInfo(varClientNumber, RefNo, 0, "",0);
				if (!GetSessionRefEnabled())
				{
					window.alert("This referral is not assigned to you, so you cannot open it's details.");
				}
				else
				{
					window.top.frames['Main'].location.href = '../referrals/ReferralPage.aspx';
				}
			}
			
			if(srcElem.cells.length > 3 && srcElem.cells(0).innerText == 'Appointment')
			{
				var varClientNumber = srcElem.cells(6).innerText;
				var varReferralNumber = srcElem.cells(7).innerText;
				var varCaseNumber = srcElem.cells(8).innerText;
				window.showModalDialog('../referrals/CaseRecording.aspx' + rVal() + '&ClientNo=' + varClientNumber + '&ReferralNo=' + varReferralNumber + '&CaseNo=' + varCaseNumber,'null','dialogheight:450px;dialogwidth:660px;dialogtop:200;dialogleft:100;help:no;status:no');				
			}
			if(srcElem.cells.length > 3 && srcElem.cells(0).innerText == 'Task' && srcElem.cells(10).innerText == 'Assessments')
			{
				var varClientNumber = srcElem.cells(11).innerText;
				var varReferralNumber = srcElem.cells(3).innerText;
				var varCaseNumber = srcElem.cells(5).innerText;
				var varClientName = srcElem.cells(1).innerText;
				window.top.frames['Main'].location.href = '../assessments/assessments.aspx?ClientNo=' + varClientNumber + '&ReferralNo=' + varReferralNumber + '&CaseNo=' + varCaseNumber + '&ClientName=' + varClientName;
			}
			

			if(srcElem.cells.length > 3 && srcElem.cells(0).innerText == 'Task' && srcElem.cells(10).innerText == 'Service Placements Starting')
			{
				var varClientNumber = srcElem.cells(11).innerText;
				var varReferralNumber = srcElem.cells(3).innerText;
				var varCaseNumber = srcElem.cells(5).innerText;
				var varClientName = srcElem.cells(1).innerText;
				//window.top.frames['Main'].location.href = '../services/servicedetail.aspx?ClientNo=' + varClientNumber + '&ReferralNo=' + varReferralNumber + '&CaseNo=' + varCaseNumber + '&ClientName=' + varClientName;
				window.showModalDialog('../services/ServiceDetail.aspx' + rVal() + '&RecId=' + varCaseNumber,'null','dialogheight:505px;dialogwidth:625px;dialogtop:40;dialogleft:40;help:no;status:no');
			}
			if(srcElem.cells.length > 3 && srcElem.cells(0).innerText == 'Task' && srcElem.cells(10).innerText == 'Service Placements Ending')
			{
				var varClientNumber = srcElem.cells(11).innerText;
				var varReferralNumber = srcElem.cells(3).innerText;
				var varCaseNumber = srcElem.cells(5).innerText;
				var varClientName = srcElem.cells(1).innerText;
				window.showModalDialog('../services/ServiceDetail.aspx' + rVal() + '&RecId=' + varCaseNumber,'null','dialogheight:505px;dialogwidth:625px;dialogtop:40;dialogleft:40;help:no;status:no');
				//window.top.frames['Main'].location.href = '../services/servicedetail.aspx?ClientNo=' + varClientNumber + '&ReferralNo=' + varReferralNumber + '&CaseNo=' + varCaseNumber + '&ClientName=' + varClientName;
			}
		}
		catch (error) {}

	}
	
	function KillCR()
	{
        if(null == event)return;
		if(event.keyCode == 13)
		{
			if(event.srcElement.tagName=='TEXTAREA')return;
			event.returnValue=false;
			event.cancel = true;
		}
	}

	//iNewClient = 0 is false. > 0 is true
	function LaunchDocument(Number, Type, SubType, StartDate, Id, iNewClient, NewDoc, Ext1, Ext2, Ext3, Ext4, Ext5)
	{
		var NewClient = (null!=iNewClient)?'&NewClient=' + iNewClient.toString():'';
		var theId = (null!=Id)?'&Id=' + Id:'';
		var theDate = (null!=StartDate)?'&StartDate=' + StartDate:'';
		var Ext = GetExtraParams(Ext1, Ext2, Ext3, Ext4, Ext5);
		docWindow = window.open('../common/DocumentOpener.aspx?case_number=' + Number + '&case_type=' + Type + '&case_sub_type=' + SubType + theDate + theId + NewClient + Ext,'','status=no,toolbar=no,resizable=yes,scrollbars=' + ((null==NewDoc)?'yes':'no'));
	}
	
	function EnableControl(ctl, bEnable)
	{
		if(null==ctl)return;
		if(ctl.type == 'checkbox')
		{
			EnableCheckBox(ctl, bEnable);
			return;
		}
		
		if(ctl.type == 'button' || ctl.type == 'submit')
		{
			EnableButton(ctl, bEnable);
			return;
		}
		
		if('TEXTAREA;INPUT;SELECT'.indexOf(ctl.tagName)!=-1)ctl.runtimeStyle.backgroundColor = (bEnable)?'White':'LemonChiffon';
		ctl.disabled = !bEnable;
	}
	
	function setAssociatedControlReadOnly(textbox, bEnable)
	{	//This is intended for use primarily with a checkbox and related textbox
		//So when the checkbox IS ticked the textbox is NOT readonly
		//As such it needs to negate the incoming boolean
		textbox.readOnly = !bEnable;
		textbox.value = "";
	}
	
	function EnableCheckBox(checkbox, bEnable)
	{
		// fiona - only disables/enables the actual checkbox. Not the text associated with it. 
		// if you want the text disabled as well, use EnableControl
		if(null==checkbox)return;
		// Depends whether text is to the right or left of the checkbox whether
		// we need to disable childNode[0] or [1]
		if (checkbox.parentElement.childNodes[1].tagName == 'INPUT')
			checkbox.parentElement.childNodes[1].disabled = !bEnable;
		else
			checkbox.parentElement.childNodes[0].disabled = !bEnable;
	}

	function EnableButton(button, bEnable)
	{
		if(null==button || 'submit.button'.indexOf(button.type)<0)return;
		var b = (null != bEnable)?bEnable:true;
		button.disabled = !b;
		if (button.className.indexOf('btn')==0)
		{
			var s = 'Disabled';
			var cls = button.className.replace(s,'');
			if(cls!="") button.className = (b)?cls:cls +s;
		}
	}
	
	function GetGridFromServer(arrItems, strUrl, strGridId)
	{
		var ret = '<table></table>';
		var strHTML = ServerRequest(arrItems, strUrl, true);
		if(null != strHTML)
		{
			var html = ExtractNodeStringByTagName(strHTML, 'HTML') //Is valid html?
			var grid = ExtractNodeStringByTagName(html, 'TABLE')
			if(null != grid && grid != '')ret = grid;
		}
		return ret;
	}
	
	function ExtractNodeStringByTagName(strHTML, strTag)
	{	var ret = '';
		if(null !=strHTML && null !=strTag)
		{
			var tag = strTag.toUpperCase();
			var i = strHTML.toUpperCase().indexOf('</' + tag + '>');
			i=(i >0)?i +8:0;
			ret = strHTML.substring(strHTML.toUpperCase().indexOf('<' + tag), i);
		}
		return ret;
	}

	function QueryString(key)
	{
		var value = null;
		for (var i=0;i<QueryString.keys.length;i++)
		{
			if (QueryString.keys[i]==key)
			{
				value = QueryString.values[i];
				break;
			}
		}
		return value;
	}

	function QueryString_Parse()
	{
		var query = window.location.search.substring(1);
		var pairs = query.split("&");
		
		for (var i=0;i<pairs.length;i++)
		{
			var pos = pairs[i].indexOf('=');
			if (pos >= 0)
			{
				var argname = pairs[i].substring(0,pos);
				var value = pairs[i].substring(pos+1);
				QueryString.keys[QueryString.keys.length] = argname;
				QueryString.values[QueryString.values.length] = value;		
			}
		}
	}

	function SetStatusValue(val)
	{
		if (null != window.top){
			if (null != window.top.frames[0]){
				if (null != window.top.frames[0].document){
					var s = window.top.frames[0].document.all.statusValue;
					if(null !=s)s.value = val;
				}
			}
		}	
	}

	function GetStatusValue()
	{
		if (null != window.top)
			if (null != window.top.frames[0])
				if (null != window.top.frames[0].document)
				{
					var s = window.top.frames[0].document.all.statusValue;		
					return(null !=s)?s.value:'';
				}
	}
  
	function ValidateMoney(objName)
	{
			var moneyfield = objName;
			var amount = objName.value;
			if (isNaN(amount) == true) 
			{
				if (amount.trim()!="")
				{			
					alert("That amount is invalid.  Please enter again.");			
					objName.focus();
					return false;
				}
				else
				{
					return true;
				}		
			}else 
			{
				return true;
			} 
		}
	
	function ResetCheckBoxList(lstListBoxName, bSet)
	{
		var d=document.all;
		if(null == d.item(lstListBoxName).cells)
		{
			for(i=0;i<d.item(lstListBoxName).rows.length;i++)
			{			
				d.item(lstListBoxName + "_" + i).checked=bSet;
			}
		}
		else
		{
			for(i=0;i<d.item(lstListBoxName).cells.length;i++)
			{			
				d.item(lstListBoxName + "_" + i).checked=bSet;
			}
		}
	}
	
	function CheckIfListItemSelected(lstListBoxName)
	{
		var d=document.all;
		for(i=0;i<d.item(lstListBoxName).rows.length;i++)
		{			
			if (d.item(lstListBoxName + "_" + i).checked==true)
			{
				return true;
			}
		}
		return false;
	}
	
	function SetCheckBoxListItem(lstListBoxName,strValue,arrRefArray)
	{
		var d=document.all;
		for(i=0;i<arrRefArray.length;i++)
		{			
			if (arrRefArray[i]==strValue)
			{
				d.item(lstListBoxName + "_" + i).checked=true;
			}
		}		
	}
	
	function OpenDialogCenterScreen(strURL, strName, intWindowWidth, intWindowHeight, strExtraFeatures, intLeftOffset, intTopOffset) {
	    var screenWidth=screen.width
	    var screenHeight=screen.height
	    
	    if(null==intLeftOffset)intLeftOffset=0;
	    if(null==intTopOffset)intTopOffset=0;
	    	    		
		if(strName=='')strName='_blank';
		if(intWindowWidth==0)intWindowWidth=1;
		if(intWindowHeight==0)intWindowHeight=1;
		
	    var leftPos=Math.round((screenWidth/2)-(intWindowWidth/2))
	    var topPos=Math.round((screenHeight/2)-(intWindowHeight/2))
	    
	    if (intLeftOffset!=0)leftPos+=intLeftOffset;
	    if (intTopOffset!=0)topPos+=intTopOffset;

	    return window.open(strURL, strName, "left=" + leftPos + ",top=" + topPos + ",width=" + intWindowWidth + ",height=" + intWindowHeight + strExtraFeatures);
	}

	function OpenModalDialogCenterScreen(strURL, varDialogArgument, intWindowWidth, intWindowHeight, strExtraFeatures) {
	    var screenWidth=screen.width
	    var screenHeight=screen.height

		if(intWindowWidth==0)intWindowWidth=1;
		if(intWindowHeight==0)intWindowHeight=1;
		
        if (strExtraFeatures==null || strExtraFeatures==''){
			strExtraFeatures=';help:no;status:no';
	    }

	    var leftPos=Math.round((screenWidth/2)-(intWindowWidth/2))
	    var topPos=Math.round((screenHeight/2)-(intWindowHeight/2))
		
	    return window.showModalDialog(strURL, varDialogArgument, 'dialogheight:' + intWindowHeight + 'px;dialogwidth:' + intWindowWidth  + 'px;dialogtop:' + topPos + 'px;dialogleft:' + leftPos + 'px' + strExtraFeatures);
	}

	function ServerRequest(arrItems, strUrl, bReturnEntireResponse)
	{
		//*** Generic wrapper for calls to XMLHTTP 
		//*** arrItems: An array of strings to send to server. Will be converted to xml nodelist before sending - in the form "<Params><Param>item1</Param><Param>item2</Param></Params>"
		//*** strUrl: The aspx page to call.
		//*** bReturnEntireResponse: When true, returns the entire HTML response as a string.  
		//***						 When false, will attempt to return an xml element from the response.
		//*** If an error occurs, it can be returned in the xml element and raised here at the end.
		
		var bAll = (null !=bReturnEntireResponse)?bReturnEntireResponse:false;
		var ret = null;
		if(null != arrItems && arrItems.length && null != strUrl && strUrl.length)
		{
			var ohttp = new ActiveXObject('Microsoft.XMLHTTP');
			var strParams = '';
			for(var i =0; i < arrItems.length; i++)
			{
				strParams += '<Param>data</Param>'.replace(/data/, arrItems[i]); 	
			}
			var strXml = '<Params>data</Params>'.replace(/data/, strParams);
			ohttp.open('POST', strUrl, false);
			ohttp.send(strXml);
			var response = ohttp.responseText;
			if(bAll)
			{
				ret = response.substring(response.toUpperCase().indexOf('<HTML'));
			}
			else
			{
				var xd = new ActiveXObject('Microsoft.XMLDOM');
				response = response.substring(0, response.indexOf('\r\n'));
				try
				{
					xd.loadXML(response);
					var elm = xd.documentElement;
				}
				catch(e){}
				if(null != elm && null != elm.childNodes[0])ret = elm;
			}
		}
		if(null != ret)
		{
			if(null !=elm)
			{
				var elmError = elm.childNodes[0].selectSingleNode('ErrorResult');
				if(null!=elmError)
				{
					alert(elmError.text);
					ret = null;
				}
			}
		}
		return ret;
	}
	
	function ValidateControl(Cntrl,obj,ErrMsg)
	{
		if(document.all.item(Cntrl).checked)
		{
			if(obj.value=="")
			{
				alert(ErrMsg);
			}
		}
	}
	
	function SetCurrentClientRefInfo(ClientNo, RefNo, RefClass, Client,SPId)
	{
		var ohttp = new ActiveXObject('Microsoft.XMLHTTP');
		var strXml = '<params><ClientNo>' + ClientNo + '</ClientNo><RefNo>' + RefNo + '</RefNo><RefClass>' + RefClass + '</RefClass><Client>' + Client + '</Client><SPId>' + SPId + '</SPId></params>';
		ohttp.open('POST', '../Common/SetClient.aspx', false);
		ohttp.send(strXml);
		
		return ohttp.responseText.substring(0, ohttp.responseText.indexOf('\r\n'));;
		ohttp = null;
	}
	
	function ShowPersonalDetails(level)
	{
		var p = GetPathOffset(level);
		window.top.frames[1].document.location.href = p + '../Clients/ClientPage.aspx';
		return false;
	}

	function ShowServicePlacements(CaseType, level)
	{
		var ct=(null!=CaseType)?CaseType:'0';
		var p = GetPathOffset(level);
		window.top.frames[1].document.location.href = p + '../Services/ServicePlacementListingPage.aspx?From=' + ct;
		return false;
	}

	//Related File Details
	function ShowRelatedFileDetails(level)
	{
		var p = GetPathOffset(level);
		var em = window.showModalDialog(p + '../Common/RelatedFiles.aspx' + rVal(),'null','dialogheight:325px;dialogwidth:487px;dialogtop:200;dialogleft:100;help:no;status:no');
		return false;
	}
	
//Printing
function PrintList(strTitle, level)
{
	var p = GetPathOffset(level);
	window.open(p + '../common/excelclientwindow.aspx?Title=' + strTitle, 'PrintWindow', 'status=yes,menubar=yes,scrollbars=yes,location=no');
}

// Complaints
function ShowComplaints(CaseType)
{
	window.showModalDialog('../ChildProtect/Complaints.aspx' + rVal() + '&CaseType=' + CaseType,window,'dialogheight:430px;dialogwidth:636px;dialogtop:200;dialogleft:100;help:no;status:no');
}
	
//Attached Documents
	function ShowAttachedDocs(level)
	{
		var p = GetPathOffset(level);
		var em = window.showModalDialog(p + '../Common/AttachedDocs.aspx' + rVal(),window,'dialogheight:485px;dialogwidth:720px;dialogtop:200;dialogleft:100;help:no;status:no');
		//var em = window.showModalDialog(p + '../Common/AttachedDocs.aspx' + rVal(),'null','dialogheight:355px;dialogwidth:520px;dialogtop:200;dialogleft:100;help:no;status:no');
		return false;
	}	
	
//Case Items
	function ShowCaseItems(CaseType, level,CaseItemId)
	{
		var p = GetPathOffset(level);
		var ct=(null!=CaseType)?CaseType:'0';
		var CaseId = (null !=CaseItemId)?CaseItemId:'0';
		//var em = window.showModalDialog(p + '../referrals/Caserecording.aspx' + rVal() + '&CaseType=' + ct,'null','dialogheight:450px;dialogwidth:660px;dialogtop:200;dialogleft:100;help:no;status:no');
		var em = window.showModalDialog(p + '../referrals/CaseNotesPage.aspx' + rVal() + '&CaseType=' + ct + '&CaseNotesId=' + CaseId,window,'dialogheight:540px;dialogwidth:665px;dialogtop:200;dialogleft:100;help:no;status:no');
		//window.open(p + '../referrals/Caserecording.aspx' + rVal() + '&CaseType=' + ct);
		return false;
	}
		
	
	function WarnUser()
	{
		alert('Populating this Date field will close the document for editing.')
	}
	
	function GetGridRowNumById(table, id)
	{
		var row = null;
		if(null != table && table.rows.length >1)
		{
			for(var i=0; i<table.rows.length; i++)
			{
				if(IsValueInRow(table.rows[i], 'Id', id))
				{
					row = i;
					break;
				}
			}
		}
		return row;
	}
	
	function TruncDec(val)
	{
		var rVal = 0;
		rVal = Math.round(val);
		
		if(rVal>val)
		{
			if(rVal>0)
				rVal=rVal-1;
			else
				rVal=rVal+1;
		}
		
		return rVal;	
	}
	
	function CompareFourDates(strDBStartDate,StartDate,strDBEndDate,EndDate)
	{
		var blnReturn=false;	
		if (strDBStartDate!="")strDBStartDate=new Date(strDBStartDate);
		if (StartDate!="")StartDate=new Date(StartDate);
		if (strDBEndDate!="")strDBEndDate=new Date(strDBEndDate);
		if (EndDate!="")EndDate=new Date(EndDate);
		
		if (strDBStartDate!="" && StartDate!="" && strDBEndDate !="" && EndDate!="")
		{
			if ((strDBStartDate>=StartDate && strDBEndDate<=EndDate) || (strDBStartDate<=EndDate && strDBEndDate>=EndDate) || (strDBStartDate<=StartDate && strDBEndDate>=StartDate))
			{
				blnReturn=true;
			}
		}else
		{
			if ((strDBStartDate<=StartDate && (strDBEndDate>=StartDate || strDBEndDate=="")) || (strDBStartDate>=StartDate))
			{
				if (EndDate!="" && strDBEndDate!="")
				{
					if (EndDate<=strDBEndDate)
					{
						blnReturn=true;
					}	
				}else if (EndDate!="")
				{
					if (strDBStartDate<=EndDate)
					{
						blnReturn=true;
					}	
				}else
				{
					blnReturn=true;
				}			
			}		
		}
		return blnReturn;
	}

	function GetPassWord()
	{	
		var nod = document.createElement('<input type="checkbox">');
		var p= window.showModalDialog('../common/PWBox.aspx' + rVal(),nod,'dialogheight:155px;dialogwidth:288px;help:no;status:no');
		return nod.checked;
	}	

	// Address Functionality
	function HasLinkedPrimaryAddresses(dude)
	{
		var ohttp = new ActiveXObject('Microsoft.XMLHTTP');
		var strXml = '<params><type>' + dude + '</type></params>';
		ohttp.open('POST', '../Common/LinkedAddressCheck.aspx', false);
		ohttp.send(strXml);
		var response = ohttp.responseText;
		var xd = new ActiveXObject('Microsoft.XMLDOM');
		response = response.substring(0, response.indexOf('\r\n'));
		xd.loadXML(response);
		var elm = xd.documentElement;
		var bRes = false;
		if(null != elm)bRes = elm.getAttribute('Value');			
		if(bRes.toUpperCase()!='TRUE')
			return false;
		else
			return true;		
	}

	function ShowLinkedAddressTypes()
	{
		return window.showModalDialog('../Common/AddressLinks.aspx' + rVal(),window,'dialogheight:360px;dialogwidth:350px;dialogtop:200;dialogleft:100;help:no;status:no')
	}

	function SelectAllLinkedAddressTypes()
	{
		var d = document.all;
		if (d.cb.parentElement.childNodes[1].innerText == "Select All")
		{
			d.cb.checked = false;
			d.cb.parentElement.childNodes[1].innerText = "Clear All";
			ResetCheckBoxList("cblLinked", true);
		}
		else
		{
			d.cb.checked = false;
			d.cb.parentElement.childNodes[1].innerText = "Select All";
			ResetCheckBoxList("cblLinked", false);
		}
	}
	
	function PCase(str)
	{		
		//fiona - needs to do same as Foundation/StringUtils.ProperCase
		return str;
	}
	
	//disables a control if the selected index value of a dropdown list is zero (or less than zero)
	//enables the control if the selected index value of a dropdown list is NOT zero
	function SetControlForComboIndex(ctl, cbo)
	{
		if (cbo.selectedIndex <= 0)
		{
			EnableControl(ctl,false);
		}
		else
		{
			EnableControl(ctl,true);
		}
	}
	
	function UnPackLeftInt(PackedInt)
	{
		return parseInt(parseInt(PackedInt)/100000);
	}
	
	function UnPackRightInt(PackedInt)
	{
		return parseInt(parseInt(PackedInt)%100000);
	}
	
	function PackInt(LeftInt, RightInt)
	{
		var RetVal = 0;
		
		RetVal = ParseInt(LeftInt) * 100000;
		RetVal = RetVal + parseInt(RightInt);
		
		return RetVal;
	}
	
	// Consents
	function ShowConsent(CaseType)
	{
		var ClientNo = document.all.hidClientNo.value;
		var parms = '?ClientNo=' + ClientNo.toString();
		var ct=(null!=CaseType)?CaseType:'9'; // default to Client Consent
		window.showModalDialog('../common/Consent.aspx' + rVal() + parms + '&CaseType=' + ct,window,'dialogheight:403px;dialogwidth:676px;dialogtop:200;dialogleft:100;help:no;status:no');
	}
	
	//To Set the Checkbox List based on Comma Separated Ids, Style Vertical - Senthil
	function SetCheckBoxList(chkBox,CommaSeparatedIdList)
	{
		
		if (null == chkBox) return;
	
		var IdList = CommaSeparatedIdList.split(",");								
		
		for(i=0;i< chkBox.cells.length;i++)
		{			
			for(j=0; j <IdList.length; j++)
			{
			    if(chkBox.cells[i].childNodes[0].getAttribute('value') == IdList[j])
				{					
					chkBox.cells[i].childNodes[0].checked = true;
					break;
				}
			}			
		}		
	}
	//To Reset Checkbox List, Style Vertical - Senthil
	function ReSetCheckBoxList(chkBox)
	{		
		if (null == chkBox) return;	
				
		for(i=0;i< chkBox.cells.length;i++)
		{						
			chkBox.cells[i].childNodes[0].checked = false;									
		}		
	}
	
	
	//To Make Controls Visible and Invisible - Senthil
	function VisibleAndHideControls(ctl,bVisible)
	{
		if (null == ctl) return;
		
		if (bVisible == true)
			ctl.style.display='';		
		else
			ctl.style.display='None';		
	}
	
	//Function to get the name of the Grid with selected row (current row) - Senthil
	//This is required for pages with two grids
	function GetCurRowGridName()
	{
		var GridName = '';
		if (null == selRow) return GridName;
		if (-1 == selRow) return GridName;
					
		if (null != selRow.parentNode.parentNode)
			GridName = selRow.parentNode.parentNode.id;
		return GridName;
	}
	
	function GetExtraParams(a, b, c, d, e)
	{
		var Params = '';
		Params =  (null!=a)?'&ExtParam1=' + FormatParam(a):'';
		Params += (null!=b)?'&ExtParam2=' + FormatParam(b):'';
		Params += (null!=c)?'&ExtParam3=' + FormatParam(c):'';
		Params += (null!=d)?'&ExtParam4=' + FormatParam(d):'';
		Params += (null!=e)?'&ExtParam5=' + FormatParam(e):'';
		return Params;	
	}
	
	function FormatParam(p)
	{
		var pre = '';
		switch(typeof(p))
		{
			case 'number':
			{
				pre += '2|';
				break;
			}
			case 'string':
			{
				pre += '1|';
				break;
			}
			case 'boolean':
			{
				pre += '4|';
				break;
			}
			default:
			{
				pre += '1|';
				break;
			}
		}
		return pre + p.toString();
	}
		
/*function GetNextDay(SDate,Day)
{
	var nextDay = new Date(SDate);
	var thisDay = SDate.getDay();
	
	if(thisDay==0)thisDay=7
	
	// getDay returns the day of the week, with 0=Sunday
	with (nextDay) {
			setDate(getDate() - (15+Day-(thisDay))%7);
		}

	return nextDay;
}*/

	//For a given start date and day (1=monday 7=sunday) this function will return the date
	//that falls on that day in the current week of the SDate.  ie.  if you provide a date
	//that falls on a friday and Day=1 it will return the previous monday.  However, if
	//you parse in a date that falls on a monday and Day=5 it will turn the next friday.
	function GetThisWeekDay(SDate, Day) 
	{
		// Get day of week
		var dayOfWeek = SDate.getDay();
		// If day is sunday, change 0 into 7
		if (dayOfWeek == 0) {
			dayOfWeek = 7;
			}
		// Modify date by Day argument
		SDate.setDate(SDate.getDate() + Day - dayOfWeek);
		return SDate;
	}

	//For a given date and day of week (1=mon 7=sun) this function finds the next date
	//falling on that day
	function GetNextDay(aDate, theDay)
	{
		var thisDay = aDate.getDay();
		if(thisDay==0) thisDay=7;
		if(thisDay==theDay) return aDate;
		
		var dayOff = theDay - aDate.getDay();
		if(dayOff<0) dayOff += 7;
		return new Date(aDate.setDate(aDate.getDate()+dayOff));
	}
	
	//For a given date and day of week (1=mon 7=sun) this function finds the previous date
	//falling on that day
	function GetPrevDay(aDate, theDay)
	{
		var thisDay = aDate.getDay();
		if(thisDay==0) thisDay=7;
		if(thisDay==theDay) return aDate;
		
		var aDate = GetNextDay(aDate,theDay);
		
		return new Date(aDate.setDate(aDate.getDate()-7));
	}
	
	//Restrict input in textarea to cols and rows length
	function RestrictInput(ths)
	{
		var txt = ths.value;
		var maxLength = ths.getAttribute('maxLength');
		if(null!=maxLength)
		{
			ths.value='';
			while(txt.length > maxLength)
				txt=txt.substr(0, maxLength);
			ths.value=txt;
			ths.scrollTop=0;
		}	
	}


	function ValidateMonth(ctl)
	{
		var msg = '';
		if (null != ctl)
		{
			if (ctl.value == '') return;
			if (ctl.value > 12 || ctl.value < 0)
			{
				ctl.value = '';
				alert("Invalid Month. Please Input Proper Month (0-12)");				
			}			
		}			
	}
	
	function MakePositive(ctl)
	{
		if(!CheckValidNumeric(ctl.value))
		{
			ctl.value='';
		}
		else if (ctl.value < 0)
		{
			ctl.value = '';
		}	
	}
	
function GetJanusGridValue(grdName,strColumn)
{	
	var blnColumnPresent=false;
	var strValue="";
	var srcElem = window.event.srcElement;			
	var grdGrid=document.getElementById(grdName); 			
	if (null!=grdGrid.children(1))
	{	
		var grdHedderRow=grdGrid.children(1).children(0).children(0).rows(0);
	}else
	{
		var grdHedderRow=grdGrid.children(0).children(0).children(0).rows(0);
	}
	var grdItemRow=document.getElementById(grdName + "1_items")			
	while (null != srcElem && srcElem.tagName != "TR" && srcElem.tagName != "TABLE" && srcElem.tagName != "TH") 
	srcElem = srcElem.parentElement;
	if(null != srcElem)
	{
		if(srcElem.tagName == "TR")
		{	
			for (var i=0; i<grdHedderRow.childNodes.length; i++)
			{
				if (grdHedderRow.childNodes[i].innerText.toUpperCase() == strColumn.toUpperCase())
				{							
					strValue=srcElem.cells(i).innerText;
					blnColumnPresent=true;
					break;
				}	
			}		
		}
	}
	if (blnColumnPresent==false)
	{
		alert(strColumn + " Column not present.");
	}
	return strValue;
}

function IsJanusSelectedRowTheHeaderRow(grdName)
{
	var bSameRow = false;
	var srcElem = window.event.srcElement;			
	var grdGrid=document.getElementById(grdName); 			
	if (null!=grdGrid.children(1))
	{	
		var grdHedderRow=grdGrid.children(1).children(0).children(0).rows(0);
	}else
	{
		var grdHedderRow=grdGrid.children(0).children(0).children(0).rows(0);
	}
	while (null != srcElem && srcElem.tagName != "TR" && srcElem.tagName != "TABLE" && srcElem.tagName != "TH") 
	srcElem = srcElem.parentElement;
	bSameRow = srcElem.sourceIndex == grdHedderRow.sourceIndex
	return bSameRow;
}
	
//Functions to Add - Yr, Week, Day to the Date
function isDate(p_Expression)
{
	return !isNaN(new Date(p_Expression));
}


// REQUIRES: isDate()
function dateAdd(p_Interval, p_Number, p_Date){
	if(!isDate(p_Date)){return "invalid date: '" + p_Date + "'";}
	if(isNaN(p_Number)){return "invalid number: '" + p_Number + "'";}	

	p_Number = new Number(p_Number);
	var dt = new Date(p_Date);
	switch(p_Interval.toLowerCase()){
		case "yyyy": {// year
			dt.setFullYear(dt.getFullYear() + p_Number);
			break;
		}
		case "q": {		// quarter
			dt.setMonth(dt.getMonth() + (p_Number*3));
			break;
		}
		case "m": {		// month
			dt.setMonth(dt.getMonth() + p_Number);
			break;
		}
		case "y":		// day of year
		case "d":		// day
		case "w": {		// weekday
			dt.setDate(dt.getDate() + p_Number);
			break;
		}
		case "ww": {	// week of year
			dt.setDate(dt.getDate() + (p_Number*7));
			break;
		}
		case "h": {		// hour
			dt.setHours(dt.getHours() + p_Number);
			break;
		}
		case "n": {		// minute
			dt.setMinutes(dt.getMinutes() + p_Number);
			break;
		}
		case "s": {		// second
			dt.setSeconds(dt.getSeconds() + p_Number);
			break;
		}
		case "ms": {		// second
			dt.setMilliseconds(dt.getMilliseconds() + p_Number);
			break;
		}
		default: {
			return "invalid interval: '" + p_Interval + "'";
		}
	}
	return dt;
}
//Gareth Maguire 07/04/2005
// Function to format a string to display number of decimal places passed in - 2 by default
function FormatMoneyValue(value, numplaces)
{
	var i;
	var retval;
	value = value + "";
	if (null == numplaces) numplaces = 2;

	if (value.lastIndexOf(".") != -1)
	{
		var places =  value.length - value.lastIndexOf(".");
		switch(places)
		{
			case 1 :
				value += "0";
			case 2 :
				value += "00";
			case 3 :
				value += "000";
				break;
			
			default :
				break;
		}
		i = value.lastIndexOf(".") + (numplaces + 1);
		retval = value.substring(0,i);
	}
	else
	{
		retval = value + ".";
		for (var i = 0; i < numplaces; i++)
			retval += "0";
	}
			
	return retval;
}

// Ted: 27/05/2005
// Move an item (option) up one place in a listbox
function MoveItemUp(objList)
{

	try
	{
		if (objList.selectedIndex == -1) 
		{
			alert ('Please select the item to be moved.');
			return (false);
		}
		else
		{
			var selIndex = objList.selectedIndex;
			
			
			if (selIndex > 0)
			{
				var optCurrent = objList.options(selIndex)
				var optPrevious = objList.options(selIndex - 1)
				
				var selText = optCurrent.text;
				var selValue = optCurrent.value;

				optCurrent.text = optPrevious.text;
				optCurrent.value = optPrevious.value;

				optPrevious.text = selText;
				optPrevious.value = selValue;

				optPrevious.selected = true;
			}
		}
	}
	catch (ex)
	{
		alert ('Unable to move item.' + ex.message);
	}

	return (false);
}

// Ted: 27/05/2005
// Move an item (option) down one place in a listbox
function MoveItemDown(objList)
{
	
	try
	{
		if (objList.selectedIndex == -1) 
		{
			alert ('Please select the item to be moved.');
			return (false);
		}
		else
		{
			var selIndex = objList.selectedIndex;
			
			
			if (selIndex < (objList.length -1))
			{
				var optCurrent = objList.options(selIndex)
				var optNext = objList.options(selIndex + 1)
				
				var selText = optCurrent.text;
				var selValue = optCurrent.value;

				optCurrent.text = optNext.text;
				optCurrent.value = optNext.value;

				optNext.text = selText;
				optNext.value = selValue;

				optNext.selected = true;
			}
		}
	}
	catch (ex)
	{
		alert ('Unable to move item.' + ex.message);
	}

	return (false);
}

// Ted: 27/05/2005. Add the selected item from a combobox to a listbox
function AddComboItemToListbox (objCombo, objListbox)
{
	// Make sure that the combobox and listbox are valid objects
	if (null==objCombo) return (false);
	if (null==objListbox) return (false);

	// Make sure that an item has been selected in the combobox
	if (objCombo.selectedIndex == 0)
	{
		alert ('Please select the item to be added.');
		return (false);
	}

	// Make sure that the selected combobox item is not already in the listbox
	for (var i=0; i<objListbox.length; i++)
	{
		if (objListbox.options(i).value == objCombo(objCombo.selectedIndex).value)
		{
			alert ('The selected item already exists in the list.');
			return (false);
		}
	}

	// Crete a new list item and add it to the listbox
	var newItem = document.createElement('OPTION');
	objListbox.add (newItem);

	// Set the value and text properties of the new listitem
	newItem.value = objCombo(objCombo.selectedIndex).value;
	newItem.text = objCombo(objCombo.selectedIndex).text;

	return (false);
}

// Delete an item from a listbox or combobox
function DeleteListItem (objList)
{

	// Make sure that the list is a valid object
	if (null==objList) return (false);

	// Make sure that an item has been selected in the list
	if (objList.selectedIndex == -1)
	{
		alert ('Please select the item to be deleted.');
		return (false);
	}
	
	// Remove the selected item from the list
	objList.options.remove(objList.selectedIndex);

	return (false);
}



//To Set Hour Glass
function doHourglass()
{
  document.body.style.cursor = 'wait';
}

function FormatDate(strDate)
{
	var dt = '';
	var mn = '';
	var yr = '';

	dt=strDate.substring(8,10);
	mn=strDate.substring(4,7);
	yr=strDate.substring(strDate.length-4,strDate.length);
	
	return dt.trim() + ' ' + mn.trim() + ' ' + yr.trim();
}



	function GetFileSize(file)
	{
	  try
	  {
		var fso = new ActiveXObject("Scripting.FileSystemObject");
		var f = fso.getFile(file);
		return fso.getFile(file).size;	
	  }
	  catch (e)
	  {
		return -1;
	  }	   
	}
	
	function CheckFileSize(File,MaxSizeAllowed)
	{
		var d = document.all;
		try
		{
			var size = GetFileSize(File);
			 
			//User Might have disallowed ActiveX or Error Getting File Size
			if (size == -1) return true;
			
			if (size > MaxSizeAllowed)
			{
				return false;   
			} 
			else
			{
				return true;
			}
		}
		catch(e)
		{
			return true;
		}
	}


//Format [control] - round and set to [decimalplaces] decimal places
function FormatDecimalPlaces(control, decimalplaces)
{
	var value = control.value;
	var ddp = Math.pow(10, decimalplaces); 
	var retval = Math.round(value * ddp) / ddp;	
	control.value = FormatMoneyValue(retval, decimalplaces);
}
//Rate amount entered
function ValidateRate(RateControl)
{
	var bValid = true;
	var d = document.all;
	var RateValue = parseFloat(RateControl.value)

	if ((RateValue == null) || (String(RateValue) == "NaN"))
	{
		bValid = false;
		alert("Invalid Rate entered. Please enter a valid numeric Rate.");
		RateControl.value = "0.000";
		RateControl.focus();
	}
	else
	{
		RateControl.value = RateValue;
		FormatDecimalPlaces(RateControl, 3);
	}	
	return bValid;
}

function SetDataGridBookmarkRow(sDataGridId)	
{
	var dgDataGrid = document.getElementById(sDataGridId)
	
	if	(null != dgDataGrid)
	{
		var sCurrentRowIdentifier = GetGridValue('UniqueIdentifier');
		if (sCurrentRowIdentifier == null || sCurrentRowIdentifier == '')
			return;
			
		var sAction = "Add";
		
		var sXml = '<Params><DataGridId>' + sDataGridId + '</DataGridId><CurrentRowIdentifier>' + sCurrentRowIdentifier + '</CurrentRowIdentifier><Action>' + sAction + '</Action></Params>';
		
		var strExecutionPath = window.location.pathname;
		var strSiteName = strExecutionPath.split('/')[1];

		var ohttp = new ActiveXObject('Microsoft.XMLHTTP');
		
		ohttp.open('POST', '/' + strSiteName + '/Common/SetDataGridBookmarkRow.aspx' , false);
		ohttp.send(sXml);
	
		ohttp = null;
	
	}
} 

function RemoveDataGridBookmarkRow(sDataGridId)	
{
	var sCurrentRowIdentifier = ""
	var sAction = "Remove"
	
	var sXml = '<Params><DataGridId>' + sDataGridId + '</DataGridId><CurrentRowIdentifier>' + sCurrentRowIdentifier + '</CurrentRowIdentifier><Action>' + sAction + '</Action></Params>';
	
	var strExecutionPath = window.location.pathname;
	var strSiteName = strExecutionPath.split('/')[1];

	var ohttp = new ActiveXObject('Microsoft.XMLHTTP');
	
	ohttp.open('POST', '/' + strSiteName + '/Common/SetDataGridBookmarkRow.aspx' , false);
	ohttp.send(sXml);

	ohttp = null;
}

function RemoveAllDataGridBookmarkRows()	
{
	var sCurrentRowIdentifier = ""
	var sAction = "RemoveAll"
	
	var sXml = '<Params><DataGridId></DataGridId><CurrentRowIdentifier>' + sCurrentRowIdentifier + '</CurrentRowIdentifier><Action>' + sAction + '</Action></Params>';
	
	var strExecutionPath = window.location.pathname;
	var strSiteName = strExecutionPath.split('/')[1];

	var ohttp = new ActiveXObject('Microsoft.XMLHTTP');
	
	ohttp.open('POST', '/' + strSiteName + '/Common/SetDataGridBookmarkRow.aspx' , false);
	ohttp.send(sXml);

	ohttp = null;
}

function GetFormPath(controllerPath)
{		
	var j=0;
	var lnk = document.getElementsByTagName("LINK");
	if(null!=lnk)
	{
		if(lnk.length > 0)
		{
			var LinkUrl=lnk(0).href;
			if (LinkUrl.indexOf("../")==-1)
			{
				return controllerPath
			}else
			{
				var arrLinkUrl=LinkUrl.split('/');
				for (j=0;j<arrLinkUrl.length;j++)
				{
					if (arrLinkUrl[j]=="..")
					{
						controllerPath = '../' + controllerPath;
					}
				}
				return controllerPath;
			}
		}
	}else
	{
		return controllerPath;
	}
}