﻿// COPYRIGHT NOTICE
// ----------------
// Copyright (c) 2000-2004. All rights reserved.
//
// Any unauthorised copying, reproduction or publishing in any form
// or manner whatsoever, of either a part of or this entire script, 
// is strictly prohibited and will constitute an infringement of this
// copyright.

/*-------------------- INTERNATIONALIZATION - NUMERIC --------------------*/
var jSVClocid=1;
var jSVCnumformat;
var jSVCdtformat="dd/mm/yyyy";
var jSVCtmformat="HH:mm";
var jSVCloctmz;
var jSVCapptmz=8; // assume our DB server GMT+8!
var jSVClgid=0; // current language ID
function JSVCSetLocale(locid,numformat,dtformat,tmformat,loctmz)
{
	if(locid!=null)
		jSVClocid=locid;
	if(numformat!=null)
		jSVCnumformat=numformat;
	if(dtformat==null)
	{	if(locid==10)
			jSVCdtformat="mm/dd/yyyy";
	}	
	else
		jSVCdtformat=dtformat;
	if(tmformat!=null)
		jSVCtmformat=tmformat;
	if(loctmz!=null)
		jSVCloctmz=loctmz;
}
function JSVCGetNumFormat(locid)
{
	var arr;
	var RE;
	var strnodec; 
	var tmp, tmp2, strsep;
	
	if(jSVCnumformat!=null)
		return jSVCnumformat;
	if(locid==null)
		locid=jSVClocid;
	switch(locid)
	{
		case 4:return ("-|.|2|,|2,3".split("|"));break;	// Indian numeric format
//		default:return ("-|.|0|,|3".split("|"));	// Indonesian numeric format

		//case 7:return ("-|.|0|,|3".split("|"));break;	// Indonesian numeric format
		//default:return ("-|.|2|,|3".split("|"));	// Default numeric format
		default:

			if(request.CurrencyFormat != undefined) 
			{
				tmp = (request.CurrencyFormat).match(/\D/gi);
				RE = new RegExp('\\' + tmp[tmp.length - 1], "gi");
				tmp2 = (request.CurrencyFormat).search(RE);
				tmp = tmp.join('');
				if(tmp.match(/^(\D)\1*[^\1]$/gi).length > 0)
				{
					if(tmp.charAt(0) != tmp.charAt(tmp.length - 1))
						arr = "-|" + tmp.charAt(tmp.length - 1) + "|" + (request.CurrencyFormat.length - tmp2 - 1);
					else
						arr = "-|.|0";

					if(tmp.length > 0)
					{
						arr = arr + "|" + tmp.charAt(0);
						if(tmp2 > 0 && tmp.charAt(0) != tmp.charAt(tmp.length - 1))
							strnodec = (request.CurrencyFormat).substr(0, tmp2);
						else
							strnodec = request.CurrencyFormat;
						
						strsep = "";
						while (strnodec.length > 0) 
						{
							if (strnodec.substring(0, strnodec.indexOf(tmp.charAt(0))).length != strnodec.substring(strnodec.lastIndexOf(tmp.charAt(0)) + 1).length) 
							{
								strsep = "," + strnodec.substring(strnodec.lastIndexOf(tmp.charAt(0)) + 1).length.toString() + strsep;
								strnodec = strnodec.substr(0, strnodec.lastIndexOf(tmp.charAt(0)));
							}
							else
							{
								strsep = strnodec.substring(0, strnodec.indexOf(tmp.charAt(0))).length.toString() + strsep;
								strnodec = "";
							} 
						}
						arr = arr + "|" + strsep;
					}
					else
						arr = arr + "|0|0";

					arr = arr.split("|");
				}
				else
					arr = "-|.|2|,|3".split("|");

			}
			else
				arr = "-|.|2|,|3".split("|");	// Default numeric format

			return arr;
			break;
	}
	// Return array: Negative Symbol,Decimal Symbol,Default decimal-places for currency,Separator Symbol,Separator Pattern
}
function JSVCNumLOC(val,maxno,minno,decplace,decsymbol,separator,mode,currencyformat)
{	// Mode: 0/null: If exceed, delete, 1: If breach, take min/max
	var fl,obj,str;
	if(typeof(val)=="object"){obj=val;val=val.value;}
	if(minno==null)minno=0;
	if(maxno==null)maxno=9999999999; // max 10 digits
	if(maxno<minno){fl=minno;minno=maxno;maxno=fl;}
	if(val==null)val=""; 
	fl=JSVCNumLOCtoDB(val,decsymbol,separator,1);
	// Perform Rounding
	if(fl!=null&&val!=""&&mode==1)
		if(fl<minno)fl=minno
		else if(fl>maxno)fl=maxno;
	if(fl==null || fl<minno || fl>maxno)
		str=""
	else
		str=JSVCNumDBtoLOC(fl,decplace,decsymbol,separator,currencyformat);
	if(obj!=null){obj.value=str;DoReq(obj);}
	return str;
}
function JSVCNumYear(val,maxno,minno)
{
	var obj,val2;
	if(typeof(val)=="object")
	{	obj=val;
		val=val.value;
	}
	val=parseInt(val);
	if(val<40 && val>=0)
		val=val+2000
	else if(val>=40 && val<100)
		val=val+1900;
	if(val>0)
	{	if(minno==null)minno=1920;
		if(maxno==null)maxno=2100;
		if(maxno<minno){val2=minno;minno=maxno;maxno=val2;}
		if(val<minno || val>maxno)
			val=0;
	}
	if(val>0)
	{	if(obj!=null){obj.value=val.toString();DoReq(obj);}
		return val;
	} else
	{ if(obj!=null){obj.value="";DoReq(obj);}
		return null;
	}
}
function JSVCNum(fl,decplace,decsymbol,separator)
{
	return JSVCNumDBtoLOC(fl,decplace,decsymbol,separator);
}
//KY : Currency format for handling multiple currency in one page
function JSVCNumDBtoLOC(fl,decplace,decsymbol,separator,currencyformat)
{
	var neg,intstr,prefix,postfix,valstd,nformat,curspace,sepspace;
	neg="";
	if(fl==null)
			return ""
	else
	{
		if(typeof(fl)!="number")
			fl=parseFloat(fl);
		if(isNaN(fl))
			return "";
	}
	//replace the currency format with the passed in one
	if(currencyformat!=null){
		var currformat=request.CurrencyFormat;
		request.CurrencyFormat=currencyformat;
		jSVCnumformat=null;
	}
	nformat=JSVCGetNumFormat();
	if(decplace==null)
		decplace=nformat[2];
	// Handle decimals
	if(decplace>0)
	{
		fl=Math.round(fl*Math.pow(10,decplace))/Math.pow(10,decplace);
		if(fl<0)
		{
			fl=-fl;
			neg="-";
		}
		valstd=fl.toString().split(".");
		if(valstd.length==1)
			valstd[1]="";
		while((valstd[1].length)<decplace)
			valstd[1]=valstd[1]+"0";
		if(decsymbol==null)
			decsymbol=nformat[1];
		postfix=decsymbol+valstd[1];
		intstr=valstd[0];
	} else
	{
		fl=Math.round(fl);
		if(fl<0)
		{
			fl=-fl;
			neg="-";
		}
		intstr=fl.toString();
		postfix="";
	}
	// Add separators
	if(separator==null)
		separator=nformat[3];
	if (separator.length > 0 && nformat[4]!=null) {
		nformat[4]=nformat[4].toString();
		prefix = "";
		sepspace = nformat[4].split(",");
		curspace = sepspace.pop();
		while (intstr.length > 0) {
			if (intstr.length > curspace) {
				prefix = separator + intstr.slice(intstr.length - curspace) + prefix;
				intstr = intstr.substring(0, intstr.length - curspace);
				if (sepspace.length > 0) 
					curspace = sepspace.pop();
			}
			else {
				prefix = intstr + prefix;
				intstr = "";
			}
		}
	}
	else {
		prefix = intstr;
	}
	//repopulate the original currency format
	if(currencyformat!=null){
		request.CurrencyFormat=currformat;
		jSVCnumformat=null;
		JSVCGetNumFormat();
	}
	return neg+prefix+postfix;
}
function JSVCNumLOCtoDB(val,decsymbol,separator,returnblank)
{
	var nformat,fl;
	
	if(val==null || (val=="" && typeof val == 'string'))
		return ((returnblank>0)?null:new Number(0));
	nformat=JSVCGetNumFormat();
	if(separator==null)
		separator=nformat[3];
	val=val.toString();
	if(separator!="")
		while(val.indexOf(separator)>=0)
			val=val.replace(separator,"");
	if(decsymbol==null)
		decsymbol=nformat[1];
	if(decsymbol!=".")
		val=val.replace(decsymbol,".");
	fl=parseFloat(val);
	if(isNaN(fl))
		return ((returnblank>0)?null:new Number(0));
	return fl;
}
function JSVC2DP(val,maxno,minno)
{
	return JSVCNumLOC(val,maxno,minno,2);
}
function JSVC1DP(val,maxno,minno)
{
	return JSVCNumLOC(val,maxno,minno,1);
}
function JSVCInt(val,maxno,minno)
{
	return JSVCNumLOC(val,maxno,minno,0);
}
function JSVCCurr(val,maxno,minno,currencyformat)
{
	return JSVCNumLOC(val,maxno,minno,null,null,null,null,currencyformat);
}
function ObjText(obj)
{
	var maxchar=obj.getAttribute("MAXCHAR");
	if(maxchar!=null && maxchar!="")
	{
		maxchar=parseInt(maxchar);
		if (obj.value.length>maxchar)
		{
			alert(JSVClang("You have entered a total of "+"{0}"+" characters, which is greater than the maximum allowed ("+"{1}"+" characters). Please shorten your description/comment.",5004,0,JSVCgetInnerText(obj).length,maxchar));
			obj.focus();
		}
	}
	DoReq(obj);
}
function JSVCDOBDate(yr,eoy,dtformat) {
	var dt = new Date();
	if(dtformat=="" || dtformat==null)
		dtformat=jSVCdtformat;
	if (yr==null) return "";
	if (eoy==null) eay=0; 
	if (eoy==0)
		return new Date(sysdt.getFullYear()-yr, 0, 1);
	else 
		return new Date(sysdt.getFullYear()-yr, 11, 31)
}
/*-------------------- INTERNATIONALIZATION - DATES and CALENDAR --------------------*/
function JSVCdtDBtoLOC(db,locid,dtformat,tmformat,shiftsecs) {
	if(db==null||db=="")
		return "";
	if(db.constructor==String) {
		var dt;
		dt=new Date(db); // 1) parsing as client PC's locale format?
		if(isNaN(dt)) {
			dt=new Date();
			dt.setISO8601(db); // 2) parsing as ISO standard format
		}
		db=dt;
	}
	if(db.constructor!=Date)
		return "";
	if(locid==null)
		locid=jSVClocid;
	if(dtformat==null)
		dtformat=jSVCdtformat;
	if(tmformat==null)
		tmformat="";
	if(tmformat==""&&dtformat=="")
		return "";
	if(shiftsecs==null)
		shiftsecs=(jSVCloctmz-jSVCapptmz)*60*60;
	else
		shiftsecs=(jSVCloctmz-jSVCapptmz)*60*60+shiftsecs;
	if(shiftsecs!=0)
		db=db.add("s",shiftsecs);
	if(tmformat=="") {
		return db.DateFormat(dtformat);
	}
	else {
		if(dtformat=="")
			return db.TimeFormat(tmformat);
		else
			return db.DateFormat(dtformat) + " " + db.TimeFormat(tmformat);
	}
}
function ObjDate(obj,doNotPrompt)
{
	var dtformat,dt,dtmin,dtmax;
	dtformat=obj.getAttribute("DTFORMAT");
	if(dtformat=="" || dtformat==null)
		dtformat=jSVCdtformat;
	if(doNotPrompt==null)
		doNotPrompt=obj.getAttribute("DTNOTPROMPT");
	dt=CalParseDate(obj.value,dtformat);
	if(dt!=null)
		if(CalCheckRange(obj,dt,dtformat,doNotPrompt)!=null)
			dt=null;
	obj.value=(dt==null?"":CalConstructDate(dt.getDate(),dt.getMonth(),dt.getFullYear(),dtformat));
	try { DoReq(obj); } catch(e) {}
	return dt;
}
function CalConstructFromDate(dt,dtformat)
{
	if(dtformat=="" || dtformat==null)
		dtformat=jSVCdtformat;
	return CalConstructDate(dt.getDate(),dt.getMonth(),dt.getFullYear(),dtformat,dt.getHours(),dt.getMinutes(),dt.getSeconds());
}
function CalConstructDate(d,m,y,sTmp,hr,mi,sc)
{
	var	mthName =	new	Array(JSVClang("January",1681),JSVClang("February",1682),JSVClang("March",1683),JSVClang("April",1684),JSVClang("May",1685),JSVClang("June",1686),JSVClang("July",1687),JSVClang("August",1688),JSVClang("September",1689),JSVClang("October",1690),JSVClang("November",1691),JSVClang("December",1692));
	sTmp = sTmp.replace	("dd","<e>");
	sTmp = sTmp.replace	("d","<d>");
	sTmp = sTmp.replace	("<e>",(d<10)? '0'+d :d);
	sTmp = sTmp.replace	("<d>",d);
	sTmp = sTmp.replace	("mmm","<o>");
	sTmp = sTmp.replace	("mm","<n>");
	sTmp = sTmp.replace	("m","<m>");
	sTmp = sTmp.replace	("<m>", (m+1));
	sTmp = sTmp.replace	("<n>", ((m+1)<10)? '0'+(m+1) :(m+1));
	sTmp = sTmp.replace	("<o>",mthName[m]);
	if(hr!="") sTmp = sTmp.replace("hh",(hr<10?'0':"")+hr);
	if(mi!="") sTmp = sTmp.replace("nn",(mi<10?'0':"")+mi);
	if(sc!="") sTmp = sTmp.replace("ss",(sc<10?'0':"")+sc);
	return sTmp.replace ("yyyy",y)
}
function CalCheckRange(obj,dt,dtformat,doNotPrompt)
{
	dtmin=obj.getAttribute("DTMIN");
	if(dtmin!=null)
	{
		// Check minimum
		if((typeof(dtmin))=="string")
		{
			dtmin=CalParseDate(dtmin,dtformat);
			obj.setAttribute("DTMIN",dtmin);
		}
		if(dtmin!=null && dt<dtmin)
		{
			if(!(doNotPrompt>0))
				alert(JSVClang("Minimum date allowed is ",5013)+CalConstructDate(dtmin.getDate(),dtmin.getMonth(),dtmin.getFullYear(),dtformat)+".");
			return dtmin;
		}
	}
	dtmax=obj.getAttribute("DTMAX");
	if(dtmax!=null)
	{
		if((typeof(dtmax))=="string")
		{
			dtmax=CalParseDate(dtmax,dtformat);
			obj.setAttribute("DTMAX",dtmax);
		}
		if(dtmax!=null && dt>dtmax)
		{
			if(!(doNotPrompt>0))
				alert(JSVClang("Maximum date allowed is ",5014)+CalConstructDate(dtmax.getDate(),dtmax.getMonth(),dtmax.getFullYear(),dtformat)+".");
			return dtmax;
		}
	}
	return null;
}
function CalParseDate(val,dtformat)
{
	var dt,pos,dofs;
	if(dtformat=="" || dtformat==null)
		dtformat=jSVCdtformat;
	pos=val.indexOf("{");
	if(pos>0)
	{
		dofs=parseInt(val.slice(pos+1));
		val=val.substring(0,pos);
	}
	if(val.toUpperCase()=="TODAY")
		dt=new Date(sysdt.getFullYear(),sysdt.getMonth(),sysdt.getDate())
	else
	{
		if(dtformat.substring(0,5)=="dd/mm")
			dt=new Date(CalFlipDateMonth(val))
		else
			dt=new Date(val);
	}
	// Parsed correctly?
	if(dt==null || isNaN(dt))
		return null;
	// If 2-digit year then default to 19/20th century
	curyear=dt.getFullYear();
	if(curyear<1900 || curyear>2999)
		return null;
	if(curyear>=1900 && curyear<1970 && (val.indexOf(curyear))<0)
		dt.setFullYear(curyear+100);
	if(!isNaN(dofs) && (dofs>0 || dofs<0))
		return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + dofs);
	return dt;
}
//Flips the date and month portion of a datestring, 1/2/2003 becomes 2/1/2003, can specify separator
function CalFlipDateMonth(dt,separator)
{
	var datearray,f,s;
	dt=dt.replace(/[.-]/g,"/");
	if(separator==null) separator = "/";
	datearray = dt.split(separator);
	f = datearray[0];
	s = datearray[1];
	datearray[0] = s;
	datearray[1] = f;
	dt = datearray.join(separator);
	return dt;
}
/*-------------------- FORM PROCESSING --------------------*/
function IsDisplayed(obj)
{
	while(obj!=null)
	{
		if(obj.style.display=="none" || obj.style.display=="NONE")
			return false;
		obj=obj.parentElement;
	}
	return true;
}
function FormObjVerify(obj)
{
	var val,ver,ival,val2,extinfo;
	val="";
	// Obtain val for all sort of form objs
	if(obj.type=="radio" && obj.name!="")
	{
		var objlist=document.getElementsByName(obj.name);
		var len=objlist.length;
		if(len!=null)
		{
			for(var t=0;t<len;t++)
			{	if(objlist[t].checked==true)
				{
					val=Trim(objlist[t].value);
					break;
				}
			}
		} else
			if(objlist.checked==true)
				val=Trim(obj.value);
	} else
		val=Trim(obj.value);
	// Check if CHKREQUIRED specified
	ver=obj.getAttribute("CHKREQUIRED");
	extinfo=obj.getAttribute("CHKREQUIREDINFO");
	if(ver!=null)
	{
		if(ver!="")
		{
			// Dependency
			if(eval(ver)==true && val=="")
				return JSVClang("should be specified.",5005)+(extinfo!=null&&extinfo!=''?'\n'+extinfo:'');
		} else
		{
			if(val=="")
				return JSVClang("should be specified.",5005)+(extinfo!=null&&extinfo!=''?'\n'+extinfo:'');
		}
	}
	if(val=="")
		return "";
	ver=obj.getAttribute("CHKFORMAT");
	if(ver!=null && ver!="")
	{	if(ver.substring(0,3)=="FN:")
		{
			val2=eval(ver.substring(3,ver.length));
			if(val2!="")
				return val2;
		} else
		{	val2=eval(ver);
			if(val2!="")
				return val2;
		}
	}
	// Otherwise check if compliant to other flags
	ival=parseInt(val,10);
	chkmin=obj.getAttribute("CHKMIN");
	chkmax=obj.getAttribute("CHKMAX");
	ver=obj.getAttribute("CHKINT");
	if (ver!=null)
	{
		if(Trim(val)!=ival.toString())
			return JSVClang("should be an integer.",5006);
		if(chkmin!=null && ival<parseInt(ver,10))
			return JSVClang("should be more than ",5007)+ver+".";
		if(chkmax!=null && ival>parseInt(ver,10))
			return JSVClang("should be less than ",5008)+ver+".";
	}
	ver=obj.getAttribute("CHKDATE");
	if (ver!=null)
	{
		var dt=CalParseDate(val);
		if(dt!=null)
		{
			if(ver=="TODAY" && sysdt!=null && dt>sysdt)
				return JSVClang("should be a valid date not later than today.",5009);
		} else
			return JSVClang("should be a valid date.",5010);
	}
	ver=obj.getAttribute("CHKREFORMAT");
	if(ver!=null && ver.length>0) {
		var re=new RegExp(ver,"gi");
		if(!re.test(val)) {
			var sample=obj.getAttribute("CHKRESAMPLE");
			if(sample!=null && sample.length>0)
				return JSVClang("incorrect. For example: {0}",7644,0,sample);
			else
				return JSVClang("should be specified.",5005);
		}
	}
	return "";
}
function JSVCgetInnerText(o){
	if (o == null) 
		return ""
	else 
		if (o.textContent) 
			return o.textContent
		else 
			return o.innerText;
}
function ObjVerify(obj,noprompt)
{
	var nm,ret;
	if(obj.disabled || IsDisplayed(obj)==false)
//	if(obj.disabled || obj.readOnly || IsDisplayed(obj)==false)
		return true;
	ret=FormObjVerify(obj);
	if(ret!="")
	{
		nm=obj.getAttribute("CHKNAME");
		if(nm==null)
		{
			// Check for preceding text first
//			alert(obj.nodeValue);
			if (obj.previousSibling && obj.nodeType==3) {
				nm = JSVCgetInnerText(obj.previousSibling);
			}
			else 
				nm = null;
			
//			alert(EmulgetAdjacentTextBefore(obj));
//			nm=obj.getAdjacentText("beforeBegin");
			if(nm!=null)
				nm=Trim(nm);
			if(nm==null||nm=="")
			{
				var ptd=obj.parentNode;
				if(ptd.tagName=="TD")
				{
					var ptd=ptd.previousSibling;
					if(ptd!=null && ptd.tagName=="TD")
						nm=JSVCgetInnerText(ptd);//.innerText;
				}
			}
		}
		if(nm==null) nm="Value highlighted";
		obj.focus();
		if(noprompt>0)
			return false;
		alert(nm+" "+ret);
		if((obj.tagName=="INPUT" && obj.type=="text") ||
				obj.tagName=="TEXTAREA")
				obj.select();
		return false;
	}
	return true;
}
function FormVerify(form,noprompt)
{
	var nm,ret,obj,col,t;
	col=form.elements;
	if(col!=null)
	{	for(t=0;t<col.length;t++)
		{	obj=col[t];
			if(!ObjVerify(obj,noprompt))
				return false;
	}	}
	return true;
}
function FormSubmit(obj)
{
	var obj2=document.getElementById("FORMSAVESUCCESS");
	if(obj2!=null)
	{
		if(obj2.value!="0")
		{
			alert(JSVClang("This document is outdated. You might have clicked 'Back'\n or clicked on 'Save' twice.\n\nPlease click on Refresh now (next to Stop button at the top of the window).",5011));
			return false;
		}
		obj2.value="1";
	}
	if(obj!=null)
		if(obj.tagName=="INPUT" && obj.type=="submit")
			obj.click()
		else if(obj.tagName=="FORM")
			obj.submit();
	return true;
}
function FormFail(win,errtxt)
{
	var obj=document.getElementById("FormSubmitQuote");
	if(obj!=null)
	{
		obj.style.display="";
		if(errtxt!=null)
			obj.innerText="\n"+errtxt+"\n ";
		alert(errtxt);
	}
}
function FormVSubmit(frm,confirmstr)
{
	if(confirmstr==null)
		confirmstr="";
	if(typeof(frm)=="string")
		frm=document.getElementById(frm);
	if(FormVerify(frm))
		if(confirmstr=="" || confirm(confirmstr))
			FormSubmit(frm);
}
function JSVCSetReqList(list,chk)
{
	var obj2,listarr,abc;
	listarr=list.split(",");
	for(abc in listarr)
	{	obj2=JSVCall(listarr[abc]);
		if(obj2!=null)
		{	if(chk)
				obj2.setAttribute("CHKREQUIRED","")
			else
				obj2.removeAttribute("CHKREQUIRED");
			DoReq(obj2);
}	}	}
function JSVCAddUniqueObject(arr,obj)
{
	// Call this function to add an obj to an existing array arr, only if unique
	if(arr==null)arr=new Array();
	if(obj==null)return arr;
	for(var y=0;y<arr.length;y++)
		if(arr[y]==obj)
			return arr;
	arr[arr.length]=obj;
	return arr;
}
function JSVCGetFormElementsArray(obj)
{
	// Returns an array of FORM elements under a certain node
	var ret,col;
	ret=new Array();
	col=obj.getElementsByTagName("input");
	for (var y = 0; y < col.length; y++) 
		ret[ret.length]=col[y];
	col=obj.getElementsByTagName("select");
	for (var y = 0; y < col.length; y++) 
		ret[ret.length]=col[y];
	col=obj.getElementsByTagName("textarea");
	for (var y = 0; y < col.length; y++) 
		ret[ret.length]=col[y];
	return ret;
}
function JSVCSetDisabledList(list,chk)
{	// List now accepts string, array or collection
	var obj2,listarr,abc,obj3;
	if(typeof(list)=="string")
	{
		listarr=list.split(",");
		list=new Array();
		for (abc in listarr) 
		{
			obj2 = document.getElementById(listarr[abc]);
			if(obj2!=null)
			JSVCAddUniqueObject(list, obj2);
			obj2 = document.getElementsByName(listarr[abc]);
			for (var y = 0; y < obj2.length; y++) 
				JSVCAddUniqueObject(list, obj2[y]);
		}
	}
	for(var x=0;x<list.length;x++) {	
		obj2=list[x];
		if(obj2!=null) {
			//obj2.disabled=(chk?true:false);
			obj2.disabled=(parseInt(chk|(obj2.getAttribute('PDISABLED')||obj2.getAttribute('PDISABLED')==''?1:0))==1?true:false);
			DoReq(obj2);
			if(obj2.type&&obj2.type.toLowerCase()=="radio") {
				var rd=document.getElementsByName(obj2.name);
				for(var r=0;r<rd.length;r++)
					if(rd[r]) rd[r].disabled=(parseInt(chk|(rd[r].getAttribute('PDISABLED')||rd[r].getAttribute('PDISABLED')==''?1:0))==1?true:false);
			}
			obj3=obj2.getElementsByTagName("INPUT");
			for(var i=0;i<obj3.length;i++) {
				var j=obj3[i];
				if(j.type.toLowerCase()=="text" || j.type.toLowerCase()=="button") { // also disable textboxes
					j.disabled=(parseInt(chk|(j.getAttribute('PDISABLED')||j.getAttribute('PDISABLED')==''?1:0))==1?true:false);
					DoReq(j);
				}
			}
			obj3=obj2.getElementsByTagName("SELECT");
			for(var i=0;i<obj3.length;i++) {
				var j=obj3[i];
				j.disabled=(parseInt(chk|(j.getAttribute('PDISABLED')||j.getAttribute('PDISABLED')==''?1:0))==1?true:false);
				DoReq(j);
			}
			obj3=obj2.getElementsByTagName("TEXTAREA");
			for(var i=0;i<obj3.length;i++) {
				var j=obj3[i];
				j.disabled=(parseInt(chk|(j.getAttribute('PDISABLED')||j.getAttribute('PDISABLED')==''?1:0))==1?true:false);
				DoReq(j);
			}
		}
	}
}
function MRMPreprocessFormItem(obj,doreqonly)
{
	var str,sid,o;
	
	// Preprocess 1: Check for required highlighting
	DoReq(obj,null,false);
	/*if(obj.type!="checkbox" && obj.type!="radio")
	{
		if(FormObjVerify(obj)!="" && obj.disabled!=true && !(obj.style.backgroundColor=='#f2cccc'||obj.style.backgroundColor=="rgb(242, 204, 204)"))
		{
			obj.setAttribute("BKGROUND",obj.style.backgroundColor);
			obj.style.backgroundColor='#f2cccc';
		}
	}*/
	if(doreqonly!=1)
	{
	str=obj.getAttribute("MRMOBJ");
	if(str!=null && str!="")
	{	// Preprocess 2: MRMOBJ=DATE or CALDATE
		if(str=="DATE" || str=="CALDATE")
		{	if(obj.onblur==null)
				obj.onblur=new Function("ObjDate(this);");
			if(obj.maxLength=="" || obj.maxLength==null || obj.maxLength>1000)
				obj.maxLength=10;
			if(str=="CALDATE")
			{	sid=obj.name;
				if(sid==null || sid=="")
					sid=obj.id;
				if(sid!=null && sid!="")
				{	if(obj.onkeydown==null && obj.onkeyup==null)
					{	obj.onkeydown = function(e){
							CalScrollKey(e,obj);
						}
						obj.onkeyup = function(e){
							CalScrollKey(e,obj);
						}
					}
					o=document.createElement("span");
					o.innerHTML="&nbsp;"+CalGenScript(sid,1);
					obj.parentNode.insertBefore(o,obj.nextSibling);
				}
			}
		}
		// Preprocess 3: MRMOBJ=TEXTAREA
		else if(str=="TEXTAREA")
		{	if(obj.onblur==null)
				obj.onblur=new Function("ObjText(this);");
		}
		//Preprocess 4: MRMOBJ=SRCDDL
		else if(str=="SRCDDL")
		{
			SVCAJAXDropDown(obj.id);
		}
	}
	}
	
}
function MrmPreprocessFormInner(frm,doreqonly)
{
	// Inner routine for preprocessing forms
	var col,len,t;
	if(frm.onreset==null)
		frm.onreset=new Function("event.returnValue=false;");
	col=frm.elements;
	if(col==null)
		return;
	len=col.length;
	if(len!=null)
		for(t=0;t<len;t++)
			MRMPreprocessFormItem(col[t],doreqonly)
}
function MrmPreprocessForm(frm)
{
	// Outer routine for preprocessing forms. If form object passed in, then preprocess
	// only that form, otherwise, preprocess ALL forms attached to the document object
	var col,len,frm,t;
	if(frm==null)
	{
		col=document.forms;
		len=col.length;
		if(len!=null)
		{
			for(t=0;t<len;t++)
				MrmPreprocessFormInner(col[t]);
		}
	} else
		MrmPreprocessFormInner(frm);
}

/*-------------------- FORM STORE & FORM-to-URL function --------------------*/
function FormStoreUpdate(obj,val,donotoverride)
{
	var store,nm,str,pos,posend;
	if(typeof(obj)=="string")
	{
		if(val==null)
			return;
		nm = obj;
	} else
	{
		DoReq(obj);
		nm=obj.id;
		if(val==null)
			if(obj.tagName=="INPUT" && obj.type=="checkbox")
				val=(obj.checked?"1":"0")
			else
				val=escape(obj.value);
	}
	store=document.getElementById("FORMSTORE");
	if(store==null)
		return;
	str=store.value;
	pos = str.indexOf("\\"+nm+":");
	if(pos>=0)
	{
		if(!(donotoverride>0))
		{
			// Update
			posend=str.indexOf("\\",pos+1);
			if(posend==-1)
				store.value=str.substring(0,pos+nm.length+2)+val;
			else
				store.value=str.substring(0,pos+nm.length+2)+val+str.slice(posend);
		}
	} else
		// Insert
		store.value=store.value+"\\"+nm+":"+val;
}
function JSVCall(nm)
{
	var o=document.getElementById(nm);
	if(o!=null)return o;
	o=document.getElementsByName(nm);
	if(o.length>0)
		return o[0] 
	else return null;
}
function FormStoreApply()
{
	var pos,nm,val,obj,formstore,list;
	formstore=document.getElementById('FORMSTORE');
	if(formstore==null)
		return;
	list=formstore.value.split("\\");
	for(str in list)
	{
		pos=list[str].indexOf(":");
		if(pos > 0)
		{
			nm=list[str].substring(0,pos);
			val=unescape(list[str].slice(pos+1));
			obj=JSVCall(nm);
			if(obj!=null)
			{
			if(obj.tagName=="INPUT" && obj.type=="checkbox")
				obj.checked=(val=="1"?true:false)
			else
				obj.value=val;
			if(obj.onchange!=null)
				obj.onchange()
			else if(obj.onblur!=null)
				obj.onblur();
			}
		}
	}
}
function FormURLVAR(form,prefix)
{
	var urlstr,obj,urlstrall,col,len,nm,spos;
	if(prefix==null)
		prefix="";
	urlstrall="";
	col=form.elements;
	if(col!=null)
	{
		len=col.length;
		if(len>0)
			for(var t=0;t<len;t++)
			{
				obj=col[t];
				if(obj.disabled || IsDisplayed(obj)==false)
					continue;
				urlstr=obj.getAttribute("URLVAR");
				if(urlstr!=null)
				{
					nm=prefix+escape(obj.name).toUpperCase();
					if((obj.type!="checkbox" && obj.type!="radio") || obj.checked==true)
					{
						regexp=new RegExp("&"+nm+"="); 
						spos=urlstrall.search(regexp);
						if(spos>=0)
							urlstrall=urlstrall.substring(0,spos+nm.length+2)+escape(obj.value)+"%2C"+urlstrall.slice(spos+nm.length+2)
						else
							urlstrall=urlstrall+"&"+nm+"="+escape(obj.value);
					}
				}
			}
	}
	return urlstrall;
}
function FormDisable(frm) { // Disable all input elements in a form
    if(!frm)
        for(var i=0;i<document.forms.length;i++) {
            if(document.forms[i].name) {
                frm=document.forms[i];
                break;
            }
        }
    if(!frm) return;
    for(var i=0;i<frm.elements.length;i++) {
        var e=frm.elements[i];
        e.disabled=true;
    }
}
/*-------------------- FORM/INPUT CHECKING --------------------*/
function DoReq(obj,doprompt,cascade)
{
	var tgname,col,len,obj2,objcolor,bkcolor,str,oid;
	if(cascade==null)cascade=true;
	if(obj==null)return;
	tgname=obj.tagName;
	if(typeof(obj)=="string") { // obj able to accept name list
		var lst=obj.split(",");
		if(lst.length==0)
			lst[0]=obj;
		for(var t=0,a=JSVCall(lst[t]);t<lst.length&&a!=null;t++)
			DoReq(a,doprompt,false);
	}
	else if(tgname=="FORM")
	{
		col=obj.elements;
		len=col.length;
		if(len!=null)
		{	for(var t=0;t<len;t++)
			{	DoReq(col[t],doprompt,false);/*obj2=col[t];objcolor=obj2;
				if(obj2.type=="checkbox" || obj2.type=="radio")
				{
					objcolor=obj2.nextSibling;
					if(objcolor==null || objcolor.tagName!="LABEL")
						objcolor=null;
				}
				if(objcolor!=null && obj2.disabled==false && !(objcolor.style.backgroundColor=='#f2cccc'||objcolor.style.backgroundColor=="rgb(242, 204, 204)"))
				{	str=FormObjVerify(obj2);
					if(str!="")
					{	if(doprompt)alert("Field "+str);
						objcolor.setAttribute("BKGROUND",objcolor.style.backgroundColor);
						objcolor.style.backgroundColor='#f2cccc';
					}
				}*/
			}
		}
	} else
	{
		bkcolor=obj.getAttribute("BKGROUND");
		objcolor=obj;
		if(obj.type!="radio")
			cascade=false;
		if(obj.type=="checkbox" || obj.type=="radio")
		{
			if(obj.id!=null && obj.id.length>0)
				objcolor=objcolor.nextSibling;
			else
				objcolor=null;
			if(objcolor!=null && objcolor.tagName!="LABEL")
				objcolor=objcolor.nextSibling;
			if(objcolor!=null && objcolor.tagName!="LABEL")
				objcolor=null;
			if(objcolor!=null && objcolor.htmlFor!=obj.id)
				objcolor=null;
		}
		str=FormObjVerify(obj);
		if(objcolor!=null && (str=="" || obj.disabled==true))
		{
			bkcolor=objcolor.getAttribute("BKGROUND");
			if(bkcolor!=null)
			{
				objcolor.style.backgroundColor=bkcolor;
				objcolor.removeAttribute("BKGROUND");
			}
		}
		else 
		{	if(doprompt && str!="")
				alert("Field "+str);
		
		if(objcolor!=null && !(objcolor.style.backgroundColor=='#f2cccc'||objcolor.style.backgroundColor=="rgb(242, 204, 204)"))
		{
			objcolor.setAttribute("BKGROUND",objcolor.style.backgroundColor);
			objcolor.style.backgroundColor='#f2cccc';
		}}


		if(cascade && obj.name && obj.name.length>0 && obj.form && obj.form.elements)
		{	// For radio cascade to all related elements to set req
			col=obj.form.elements;
			len=col.length;
			if(len!=null)
			{	for(var t=0;t<len;t++)
					if( obj.name==col[t].name)
						DoReq(col[t],false,false);
			}
		}
	}
}
function AddOnloadCode(strload,fpm)
{
	if(window.onload == null)
		window.onload = new Function(strload)
	else
	{
		var fnexp = window.onload.toString();
		var pos1 = fnexp.search("{");
		if(pos1 > 0)
			if(fpm==1)
				window.onload = new Function(strload+fnexp.slice(pos1+1,-1))
			else
				window.onload = new Function(fnexp.slice(pos1+1,-1)+strload)
		else
			window.onload = new Function(strload);
	}
}
function JSVCAppendEvtFunc(obj,strobjev,strfunc) 
{ 
  if(strfunc!=null) {
    if(typeof(obj)=='string') obj=JSVCall(obj);
    if(!typeof(obj.length=='undefined')) obj=obj[0];
    
    var fn=eval('obj.'+strobjev).toString();
    var pos1 = fn.search("{");
    var strcur='';
    if (pos1>0) strcur=fn.slice(pos1+1,-1); 
    eval('obj.'+strobjev+'= new Function(strcur+strfunc)');
  }
}

function Trim(val)
{
	if(val==null)
		return "";
	val = val.toString();
	while(val.charAt(0) == " ")
		val = val.slice(1);
	while(val.charAt(val.length - 1) == " ")
		val = val.substr(0,val.length - 1);
	return val;
}
function Despace(str)
{
	if(typeof(str)=="string")
		return str.replace(/ /g,"")
	else
	{
		str.value=str.value.replace(/ /g,"");
		DoReq(str);
	}
}
function ObjAlphaNum(obj, minlen, maxlen)
{
	var msg=CheckAlphaNum(obj.value, minlen, maxlen);
	if (msg!="")
	{
		alert(msg);
		obj.value="";
		obj.focus();
	}
	DoReq(obj);
}
// returns "" only if val is alphanumeric (includes underscore character) and length falls within minlen and maxlength.
function CheckAlphaNum(val, minlen, maxlen)
{
	var msg="";
	var regex = /\W/gi;
	if (minlen==null) minlen=0;
	if (maxlen==null) maxlen=-1; // -1 means unlimited	
	if (regex.test(val))
		msg=msg+JSVClang("Only alphanumeric characters (A-Z, 0-9 or _) are allowed in this field. ",1675);
	if(val!="" && val.length<minlen)
		msg=msg+JSVClang("Minimum length for this field is "+"{0}"+" characters. ",1676,0,minlen);
	else if (val!="" && val.length>maxlen && maxlen!=-1)
		msg=msg+JSVClang("Maximum length for this field is "+"{0}"+" characters. ",1677,0,maxlen);
	return msg;
}
function JSVCMaxLength(obj, MaxLen)
{
	if(MaxLen==null)
	{
		MaxLen=obj.getAttribute("maxlength");
	}
	if(MaxLen>0)
	{
		obj.value=obj.value.substring(0,MaxLen);
		return (obj.value.length < MaxLen);
	}
}
function JSVCRadioGetSelObj(obj,dis)
{
	var o,i;
	if(typeof(obj)=="string")
		o=document.getElementsByName(obj)
	else if(obj.name!="")
		o=document.getElementsByName(obj.name);
	if(o==null)return null;
	for(i = 0; i < o.length; i++)
		if(o[i].checked && (dis==null || dis==o[i].disabled))
			return o[i];
	return null;
}
function JSVCRadioGetValue(obj,dis)
{	// dis: null:ignore disabled status,true:only if disabled
	var o=JSVCRadioGetSelObj(obj,dis);
	return (o==null?null:o.value);
}
function JSVCRadioSetValue(obj,val,dis)
{
	if(typeof(obj)=="string")
		o=document.getElementsByName(obj)
	else
		o=document.getElementsByName(obj.name);		
	if(o==null)return null;
	for(var i = 0; i < o.length; i++)
	{
		if(val!=null)
			if (o[i].value == val)
				o[i].checked = true;
			else 
				o[i].checked = false;
		if(dis!=null)
			o[i].disabled=dis;
	}
}
/*-------------------- URL/WINDOWS/NAVIGATION --------------------*/

/////////////////////////////////////////////////////////////////////////////////////////
// JSVCReloadParent
//  Win - defaults to window.self
//  
// Modified By		Modified On		Comments
// -----------		-----------		--------
// Theng Hey		22 Mar 2003		Simplified, no need to take any arguments
// Theng Hey		25 mar 2003		Reloads all ancestors, via recursive call
////////////////////////////////////////////////////////////////////////////////////////
function JSVCReloadParent(Win,doclose,doreload)
{
	var ParWin,propagate;
	if(Win==null)
		Win=window.self;
	if(doreload==null)
		doreload=-1;
	if(Win!=null)
	{
		ParWin = Win.opener;
		if (ParWin != null)
		{
			if(ParWin.closed)
			{
				if((doclose>0 || doclose==-1) && !(Win.closed))
					Win.close();
				return;
			}
			if(doreload>0 || doreload==-1)
			{			
				ParWin.location.href=ParWin.location.href;
				if(doreload>0) doreload--;
				propagate=1;
			}
			if(doclose>0 || doclose==-1)
			{
				if(!(Win.closed))
				{
					Win.close();
					ParWin.focus();
					if(doclose>0) doclose--;
				} else
					doclose=0;
				propagate=1;
			}
			if(propagate>0)
				JSVCReloadParent(ParWin,doclose,doreload);
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////
// NavigateParent
//  Win - defaults to window.self
//  
// Modified By		Modified On		Comments
// -----------		-----------		--------
//
////////////////////////////////////////////////////////////////////////////////////////
function NavigateParent(url, Win)
{
	if (Win==null) Win=window.self;
	var ParWin = Win.opener; 
	if (ParWin != null)
		{
		ParWin.navigate(url);
		ParWin.focus();
		}			
}
function URLBack(URL)
{
	var rgexp,txt;
	if(URL == null || URL == "")
		URL = window.location.pathname + window.location.search;
	rgexp = /((linkfrom)|(module)|(loginmode)|(cfid)|(cftoken)|(jsessionid)|(userid)|(nolayout)|(rid)|(lastlogon)|(br)|(ct)|(usid))[=][^&]*[&]*/gi;
	URL=URL.replace(rgexp, "");
	rgexp = /[&][&]+/gi;
	return URL.replace(rgexp, "");
}

/*-------------------- CONTEXT WINDOWS --------------------*/
function JSVCCtxMenuFrame(parobj,id,menuname,width,bCollapse,bClose,scrollfn)
{
	if(parobj==null)
		parobj=document.body;
	obj=document.createElement("div");
	obj.id=id;
	obj.setAttribute("CURTOP",150);
	obj.className="clsSVCCtxFrame";

	if(width!=null&&width!=""&&scrollfn!=null)
	{
		if(window.attachEvent)
			window.attachEvent('onscroll',scrollfn)
		else
			window.addEventListener('scroll',scrollfn,false);
	}
	if(width!=null&&width!="")
		obj.style.width=width+"px";
	obj.innerHTML="<div class=\"clsSVCCtxTitle\" style=height:3ex>"+(bCollapse?"<input type=button class=clsButton style=\"float:left;font-weight:bold\" onclick=JSVCCtxMenuCollapseToggle(this) value=\"&uarr;&uarr;\">":"")+(bClose?"<input type=button class=clsButton style=float:right onclick=\"JSVCcloseCtxMenu(this.parentNode.parentNode)\" value=\" X \">":"")+"&nbsp;"+menuname+"</div><div>&nbsp;</div>";
	parobj.appendChild(obj);
	JSVCDrag.init(obj);
	return obj;
}
function JSVCCtxMenuContent(obj,context)
{
	obj.firstChild.nextSibling.innerHTML=context;
}
function JSVCCtxMenuCollapseToggle(obj)
{
	var o=obj.parentNode.nextSibling;
	if(o.style.display=="none")
	{	o.style.display="";
		obj.value=String.fromCharCode(8593,8593);
	}
	else
	{	o.style.display="none";
		obj.value=String.fromCharCode(8595,8595);
	}
}
function JSVCshowCtxMenu(objname,ctxval,pos,nocap,posX,posY)
{
	return JSVCshowCtxMenuEv(event,objname,ctxval,pos,nocap,posX,posY);
}
function JSVCshowCtxMenuEv(event,objname,ctxval,pos,nocap,posX,posY)
{
	var pos,obj,postop,posleft;
	var e,eobj,eobjpos;
	// POS:1 - At Object, POS:2 - Center of screen, -1: Current location, else: - At Mouse
	if(typeof(objname)=="object")obj=objname
	else
		obj=document.getElementById(objname);
	if(obj==null)
		return;
	obj.setAttribute("ctxVal",ctxval);
	obj.removeAttribute("ctxSel");
	obj.style.display="block";

	// POS 111 - Position of top left corner is posX, posY
	if(pos==111)
	{
		obj.style.left=document.body.scrollLeft + posX;
		obj.style.top=document.body.scrollTop + posY;
		if(posY+obj.clientHeight > document.body.clientHeight)
		{
			pos=document.body.clientHeight-obj.clientHeight+document.body.scrollTop-2;
			if(pos<0)pos=0;
			obj.style.top=pos;
		}
		if (posX+obj.clientWidth > document.body.clientWidth) 
		{
			pos=document.body.clientWidth-obj.clientWidth-2;
			obj.style.left=pos;
		}
	}
	else if(pos==1)
	{
		// At source obj position
		postop=document.body.scrollTop+event.clientY-event.offsetY;
		obj.style.left=document.body.scrollLeft+event.clientX-event.offsetX;
		obj.style.top=postop;
		if(postop-document.body.scrollTop+obj.clientHeight > document.body.clientHeight)
		{
			pos=document.body.clientHeight-obj.clientHeight+document.body.scrollTop-2;
			if(pos<0)pos=0;
			obj.style.top=pos;
		}
	} else if (pos==2)
	{
		// Center of screen
		obj.style.left=document.body.scrollLeft+(document.body.clientWidth-obj.clientWidth)/2;
		postop=document.body.scrollTop+(document.body.clientHeight-obj.clientHeight)/2;
		obj.style.top=postop;
		if(postop-document.body.scrollTop+obj.clientHeight > document.body.clientHeight)
		{	pos=document.body.clientHeight-obj.clientHeight+document.body.scrollTop-2;
			if(pos<0)pos=0;
			obj.style.top=pos;
		}
	} else if(pos!=-1)
	{
		// At Mouse location
		obj.style.left=document.body.scrollLeft+event.clientX;
		if(event.clientX+obj.clientWidth > document.body.clientWidth)
		{
			pos=document.body.clientWidth-obj.clientWidth+document.body.scrollLeft-2;
			if(pos<0)pos=0;
			obj.style.left=pos;
		}
		obj.style.top=document.body.scrollTop+event.clientY;
		if(event.clientY+obj.clientHeight > document.body.clientHeight)
		{
			pos=document.body.clientHeight-obj.clientHeight+document.body.scrollTop-2;
			if(pos<0)pos=0;
			obj.style.top=pos;
		}
	}
	if(nocap==2)
	{
		JSVCPageDisable(obj,true);
		//obj.setCapture(false);
	} else if(nocap!=1) {
	   if (obj.setCapture) obj.setCapture(false);
    }
	return false;
}
function JSVCtoggleCtxMenu(obj,e)
{
	//var e=event.srcElement;  --- not supported by Fs
	//e=(e!=null?e.srcElement:window.event.srcElement);
	e=(e!=null?e.target || e.srcElement:event.target || event.srcElement);
	
	while(e!=null)
	{
		switch(e.className)
		{
			case "clsSVCCtxMenuItem": e.className="clsSVCCtxMenuHlight"; obj.ctxSel=e; return;
			case "clsSVCCtxMenuItem2": e.className="clsSVCCtxMenuHlight2"; obj.ctxSel=e; return;
			case "clsSVCCtxMenuHlight": e.className="clsSVCCtxMenuItem"; if(obj.ctxSel==e) obj.ctxSel=null; return;
			case "clsSVCCtxMenuHlight2": e.className="clsSVCCtxMenuItem2"; if(obj.ctxSel==e) obj.ctxSel=null; return;
			default:
				e=e.parentElement;
		}
	}
}
function JSVCclickCtxMenu(obj,itm)
{
	JSVCcloseCtxMenu(obj);
	if(itm==null)
	{
		itm=obj.ctxSel;
		if(itm==null) return;
	}
	var othis=itm; // Required: used in eval
	/* --- not supported by FF 
	if(itm.doFunction != null) {
		eval(itm.doFunction);
	}*/
	if(itm.getAttribute('doFunction')!=null) {
		eval(itm.getAttribute('doFunction'));
	}
}
function JSVCcloseCtxMenu(obj)
{
	if(typeof(obj)=="string")
		obj=document.getElementById(obj);
	obj.style.display="none";
	JSVCPageDisable(obj,false);
	if (obj.releaseCapture) 
		obj.releaseCapture();
}
/*-------------------- CONTEXT-WINDOWS - MAKING IT DRAGGABLE --------------------*/
var JSVCDrag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= JSVCDrag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{	var tn,to;
		var o = JSVCDrag.obj = this;
		e = JSVCDrag.fixE(e);
		if(e.srcElement)to=e.srcElement
		else if(e.target)to=e.target;
		tn=to.tagName;
		if(!(tn=="DIV"&&to.className=="clsSVCCtxTitle"))return true;
		//if(tn=="INPUT"||tn=="SELECT"||tn=="TEXTAREA")return true;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		document.onmouseup		= JSVCDrag.end;
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= JSVCDrag.drag;

		return false;
	},

	drag : function(e)
	{
		e = JSVCDrag.fixE(e);
		var o = JSVCDrag.obj;
		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)
		JSVCDrag.obj.root.CURTOP=ny;
		JSVCDrag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		JSVCDrag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		JSVCDrag.obj.lastMouseX	= ex;
		JSVCDrag.obj.lastMouseY	= ey;

		JSVCDrag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		JSVCDrag.obj.root.onDragEnd(	parseInt(JSVCDrag.obj.root.style[JSVCDrag.obj.hmode ? "left" : "right"]), 
									parseInt(JSVCDrag.obj.root.style[JSVCDrag.obj.vmode ? "top" : "bottom"]));
		JSVCDrag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};
/*-------------------- USERDATA PERSISTENCE ON BROWSER (IE only) --------------------*/
function MrmSetPersistUserData(attr,val)
{
	var obj=document.getElementById("MRMUSERDATA");
	if(obj==null)
	{
		obj=document.createElement("<DIV ID=MRMUSERDATA class=persistUserData>");
		document.body.insertAdjacentElement("afterBegin",obj);
	}
	obj.setAttribute(attr,val);
//	obj.save(attr);
	try	{ obj.save(attr); } catch(e) {};
}
function MrmGetPersistUserData(attr)
{
	var obj,val;
	obj=document.getElementById("MRMUSERDATA");
	if(obj==null)
	{
		obj=document.createElement("<DIV ID=MRMUSERDATA class=persistUserData>");
		document.body.insertAdjacentElement("afterBegin",obj);
	}
//	obj.load(attr);
	try	{ obj.load(attr); } catch(e) { return null; };
	val=obj.getAttribute(attr);
	if(val==null)
		val=="";
	return val;
}
/*-------------------- NAME + ID input generation --------------------*/
var jSVCidstr;
function JSVCSetIDDefStr(idstr)
{
	jSVCidstr=idstr;
}
function JSVCNameClick(obj)
{
	var nm,val,osel,o2,clrid,spclist,noprompt;
	if(typeof(obj)=="string")
	{
		obj=JSVCRadioGetSelObj(obj+"nmsel");
//		obj=document.getElementsByName(obj+"nmsel");
		if(obj==null)
			return;
		noprompt=1;
	}
	if(obj!=null)
		spcnm=obj.getAttribute("SPCNM");
	if(spcnm==null||spcnm=="")
		spclist=new Array()
	else
		spclist=spcnm.split("|");
	val=JSVCRadioGetValue(obj);
	clrid=0;
	if(val!=null)
	{	nm=obj.name.substring(0,obj.name.length-5);
		if(val=="1" || val==spclist[0])
		{	// Company selected
			osel=document.getElementsByName(nm+"ID1cel");
			o2=document.getElementsByName(nm+"ID1");
			if(o2!=null && o2.length>0)
			{
				if(osel==null)
					o2[0].disabled=true
				else
					o2[0].disabled=false;
				DoReq(o2[0]);
			}
			if(val==spclist[0] && noprompt!=1)
			{
				if(!confirm(JSVClang("Are you sure you want to register this Name as {0}?\nPlease check properly and confirm.\n\nClick OK to Confirm {1}, Click Cancel to revert back to Normal",1541,0,spclist[1],spclist[1])))
				{
					val=JSVCRadioGetValue(nm+"ID1cel",false);
					if(val=="1")JSVCRadioSetValue(obj,"1")
					else  JSVCRadioSetValue(obj,"2");
					return;
				}
			}
			if(osel!=null&&osel.length>0)
			{	osel[0].checked=true;osel[0].disabled=false; }
			JSVCRadioSetValue(nm+"ID1sel",null,true);
			o2=document.getElementsByName(nm+"nm")[0];
			if(val==spclist[0])
			{	o2.readOnly=true;
				o2.style.color="gray";
				o2.value=spclist[2];
			} else
			{	if(o2.readOnly==true)
				{ o2.value="";clrid=1; }
				o2.readOnly=false;
				o2.style.color="";
			}
			DoReq(o2);
			o2=document.getElementsByName(nm+"ID1")[0];
			if(o2!=null)
			{
				if(val==spclist[0])
				{	o2.readOnly=true;
					o2.style.color="gray";
					o2.value=spclist[3];
				} else
				{	o2.readOnly=false;
					o2.style.color="";
					if(clrid==1)
						o2.value="";
				}
				JSVCIDChk(o2);
			}
			o2=document.getElementsByName(nm+"ID2")[0];
			if(o2!=null)
			{
				JSVCRadioSetValue(nm+"ID2sel",null,true);
				o2.disabled=true;
				o2.style.backgroundColor="silver";
				JSVCIDChk(o2);
			}
		}
		else if(val=="2")
		{	osel=document.getElementsByName(nm+"ID1cel");
			if(osel!=null&&osel.length>0)
			{	osel[0].checked=false;osel[0].disabled=true; }
			JSVCRadioSetValue(nm+"ID1sel",null,false);
			o2=JSVCRadioGetSelObj(nm+"ID1sel");
			if(o2==null)
			{	o2=document.getElementsByName(nm+"ID1sel");
				if(o2!=null&&o2.length>0)
					o2[0].checked=true;
			}
			o2=document.getElementsByName(nm+"nm")[0];
			if(o2.readOnly==true)
			{ o2.value="";clrid=1;o2.style.color="";o2.readOnly=false; }
			DoReq(o2);
			o2=document.getElementsByName(nm+"ID1")[0];
			if(o2!=null)
			{
				o2.disabled=false;
				if(clrid==1)
				{	o2.value="";o2.readOnly=false;o2.style.color=""; }
				JSVCIDChk(o2);
			}
			if(o2==null)
			{	o2=document.getElementsByName(nm+"ID2sel");
				if(o2!=null&&o2.length>0)
					o2[0].checked=true;
			}
			o2=document.getElementsByName(nm+"ID2")[0];
			if(o2!=null)
			{
				JSVCRadioSetValue(nm+"ID2sel",null,false);
				o2.disabled=false;
				o2.style.backgroundColor="";
				JSVCIDChk(o2);
			}
		}
	}
}

function JSVCGenIDStr(idtyp,nm,dis,req,sel,val, hiderad)
{	// idtyp: 1=Main ID, 2=Sec ID (cannot be both)
	var o,t,itm,musttyp,genstr,chkformat,maxl,chkreq,idval, strhide = '',found=0;
	o=jSVCidstr.split("|");
	if(val==null)val="";
	genstr="";
	chkformat="";
	chkreq=req;
	if(sel==null)
		sel=-1;
	if(chkreq==2)
		if(sel==null || sel<=0)chkreq=0;
	if(hiderad != null && hiderad == 1)
		strhide = " style=\"display: none;\""
	if (idtyp != 2 && o[0].length > 0) {
		itm=o[0].split("!");
		idval=itm[0];
		genstr += "<input URLVAR CHKNAME=\"ID type\" id=\"_" + nm + "0cel\" name=\"" + nm + "cel\"" + (sel == 1 ? " CHECKED" : "") + (dis == 1 || sel != 1 ? " DISABLED" : "") + " type=radio value=\""+idval+"\" onclick=\"JSVCIDChk('" + nm + "')\"" + strhide + "><label for=\"_" + nm + "0cel\"" + strhide + "> " + itm[1] + "</label>";
	}
//	document.write("<SELECT name=\""+nm+"\">");
	for(t=1;t<o.length;t++)
	{	itm=o[t];
		if(o[t].length!="")
		{	if(itm.substring(0,1)=="*")musttyp=1
			else if(itm.substring(0,1)=="+")musttyp=2
			else musttyp=0;
			if(musttyp>0)itm=itm.slice(1);
			itm=itm.split("!");
			idval=itm[0];
			itm=itm[1].split("~");
			if(musttyp==0 || musttyp==idtyp)
			{
				//if(sel==-1&&val=="")sel=t+1;
				genstr+=" <input URLVAR CHKNAME=\"ID type\" id=\"_"+nm+t+"sel\" name=\""+nm+"sel\" "+(chkreq>0?"CHKREQUIRED ":"")+(sel==1||dis==1?" DISABLED":"")+(sel!=1&&dis!=1&&(sel==idval||(sel==-1&&val==""&&found!=1))?" CHECKED":"")+" type=radio"+(itm.length>1&&itm[1].length>0?" DOCHKFORMAT=\""+itm[1]+"\"":"")+" value=\""+idval+"\" onblur=DoReq(this) onclick=\"JSVCIDChk('"+nm+"');DoReq(this);\"" + strhide + "><label for=\"_"+nm+t+"sel\"" + strhide + "> "+itm[0]+"</label>";
				if(sel!=1&&dis!=1&&(sel==t+1)&&itm.length>1&&itm[1].length>0)
					chkformat=itm[1];
				found=1;
			}
		}
	}
	if(typeof(val)=="string" && val.length>15)maxl=30
	else maxl=15;
	if(req==2 && val=="")req=0;
	if (genstr != "") 
	{
		if(hiderad == null || hiderad == 0)
			genstr += "<br>";
		genstr += "<input URLVAR " + (req > 0 ? "CHKREQUIRED " : "") + "name=\"" + nm + "\"" + " id=\"" + nm + "\"" + (chkformat == "" ? "" : " CHKFORMAT=\"" + chkformat + "\"") + " maxlength=" + maxl + " size=30 style=text-transform:uppercase VALUE=\"" + (val != null ? val : "") + "\" onblur=\"JSVCIDChk(this)\"" + (dis == 1 ? " DISABLED" : "") + ">";
	}
	return genstr;
}
function JSVCIsDate(dateStr) { // dd/mm/yyyy
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); 
	if (matchArray == null) return false;
	day = matchArray[1]; // parse date into variables
	month = matchArray[3];
	year = matchArray[5];
	if ( (month < 1 || month > 12) || (day < 1 || day > 31) || ((month==4 || month==6 || month==9 || month==11) && day==31))  
		return false;
	else if (month == 2) {
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) return false;
	}
	return true; // date is valid
}
function JSVCCHKMyICDOB(str,ret) { // 0-return true/false   1-return date str.
	if (ret==null)ret=0;
	if (str.length == 6 /*&& str.search(/^[0-9]+$/) == 0*/) {
		var yyyy=str.substr(0,2);
		var mm=str.substr(2,2);
		var dd=str.substr(4,2);
		var dt=new Date(), century, curyear;
		curyear=dt.getFullYear();
		century=dt.getFullYear().toString().substr(0,2);

		if ( parseInt(century+yyyy) <= parseInt(curyear)-12 )
			yyyy=century+''+yyyy;
		else
			yyyy=(parseInt(century-1).toString())+''+yyyy; 
		
		if (JSVCIsDate(dd+'/'+mm+'/'+yyyy)) 
			return (ret?(dd+'/'+mm+'/'+yyyy):true);
	}	
	return (ret?"":false);
}
function JSVCSetDOB(src,tgt) {
	var sobj=(typeof(src)=="object"?src:document.getElementById(src));
	var tobj=document.getElementById(tgt);
	if(sobj!=null&&tobj!=null) {
		var tmp=JSVCCHKMyICDOB(sobj.value.substring(0,6),1);
		if(tmp!="") tobj.value=tmp;
		DoReq(tobj); ObjDate(tobj);
	}
	return "";
}
function JSVCIDChkMyIC(obj,chkdob)
{
	if(obj==null)return "";
	if(chkdob==null)chkdob=0; // 1=make sure yymmdd is valid
	str=obj.value.replace(/[^0-9]/g,"");
	if(str.length==12 && (chkdob==0 || (chkdob==1 && JSVCCHKMyICDOB(str.substring(0,6),0)==true  )))
	{	obj.value=str.substring(0,6)+"-"+str.substring(6,8)+"-"+str.substring(8,12);
		return "";
	}
	return "should be Malaysian NRIC format [yymmdd-xx-xxxx].";
}
function JSVCIDChkSgIC(obj)
{	var chksum,chk;
	if(obj==null)return "";
	str=obj.value.toUpperCase().replace(/[^A-Z0-9]/g,"");
	if(str.search(/^[SFTG][0-9]{7}[A-Z]$/)==0)
	{	// Checksum
		obj.value=str;
		chksum=(((str.charAt(0)=="T"||str.charAt(0)=="G")?4:0)+parseInt(str.charAt(1))*2+parseInt(str.charAt(2))*7+parseInt(str.charAt(3))*6+parseInt(str.charAt(4))*5+parseInt(str.charAt(5))*4
			+parseInt(str.charAt(6))*3+parseInt(str.charAt(7))*2)%11;
		if(str.charAt(0)=="S"||str.charAt(0)=="T")chk="JZIHGFEDCBA"
		else chk="XWUTRQPNMLK";
		if(str.charAt(8)==chk.charAt(chksum))
			return "";
		return "fails validation for a valid Singapore NRIC.\nPlease check you typed it in correctly.";
	}
	return "should be Singapore NRIC format [X9999999X].";
}
function JSVCIDChk(obj)
{	// Customize per-locale ID checking here
	var nm,obj2,ver;
	if(typeof(obj)=="string")
	{	nm=obj;obj=document.getElementsByName(nm)[0]; }
	else
		nm=obj.name;
	// Get selected object
	if(obj==null)return;
	obj2=JSVCRadioGetSelObj(nm+"sel",false);
	if(obj2==null)
		obj2=JSVCRadioGetSelObj(nm+"cel",false);
	if(obj2==null)
		obj.disabled=true
	else
		obj.disabled=false;
	if(obj2!=null)
		ver=obj2.getAttribute("DOCHKFORMAT");
	if(ver!=null && typeof(ver)=="string" && ver.length>0)
		obj.setAttribute("CHKFORMAT",ver)
	else
		obj.removeAttribute("CHKFORMAT");
	DoReq(obj);
}
//Kian Yee : Generate ID string return as string instead
function JSVCGenNameIDStr(text,nmtyp,iddisp,nm,dis,nmreq,nmsel,nmval,req1,sel1,val1,req2,sel2,val2,spcnm,nmselchgExec,appendHTML,hiderad1,hiderad2)
{	// text: String or String Array of text (e.g. Claimant,Insured,Driver)
	// nmtyp: Name type - 1 - Individual only, 2 - Individual and company
	// iddisp: Bit 1: Show Main ID, Bit 2: Show Sec ID
	// nm: Name of object
	// dis: Disabled or not
	// req/sel/val: Required(2=only if existing)/Type-Sel-Value/Value
	// spcnm: Special claimant like SPANCO (format: COID|ShortName|Name|CoRegNo)
	// appendHTML: HTML to append to Name column
	var spclist,genstr,fnlstr;
	if(hiderad1 == null) hiderad1 = 0;
	if(hiderad2 == null) hiderad2 = 0;
	fnlstr="";
	if(typeof(text)=="string")
	{   var tmp=text;
	    text=new Array();
	    text[0]=tmp+" "+JSVClang("Name",1173);
	    text[1]=tmp+" "+JSVClang("ID",2122);
	    text[2]=tmp+" "+JSVClang("Second ID",6030);
	}
	if(nmselchgExec==null)nmselchgExec="";
	if(nmreq==null)nmreq=0;
	if(nmtyp==null)nmtyp=2;
	fnlstr+="<tr id=TRINSUREDDTL1><td valign=baseline>"+text[0]+"</td><td>";
	if(nmtyp==2)
	{	fnlstr+="<input URLVAR ID=\"_"+nm+"nmselIND\" name=\""+nm+"nmsel\" CHKREQUIRED "+(nmsel==2?"CHECKED ":"")+"type=radio "+(dis==1?"DISABLED ":"")+" value=2 onclick=\"JSVCNameClick(this);"+nmselchgExec+"\"><label for=\"_"+nm+"nmselIND\"> "+JSVClang("Individual",6031)+"</label> ";
		fnlstr+="<input URLVAR ID=\"_"+nm+"nmselCOM\" name=\""+nm+"nmsel\" CHKREQUIRED "+(nmsel==1?"CHECKED ":"")+" type=radio value=1 "+(dis==1?" DISABLED ":"")+" onclick=\"JSVCNameClick(this);"+nmselchgExec+"\"><label for=\"_"+nm+"nmselCOM\"> "+JSVClang("Company",2033)+"</label> ";
		if(spcnm!=null && spcnm.length>0)
		{	spclist=spcnm.split("|");
			fnlstr+="<input URLVAR ID=\"_"+nm+"nmselSPC\" SPCNM=\""+spcnm+"\" name=\""+nm+"nmsel\" value="+spclist[0]+" CHKREQUIRED "+(nmsel==spclist[0]?"CHECKED ":"")+(dis==1?"DISABLED ":"")+" type=radio onclick=\"JSVCNameClick(this);"+nmselchgExec+"\"><label for=\"_"+nm+"nmselSPC\"> "+spclist[1]+"</label>";
		}
		fnlstr+="<br>";
	}
	//fnlstr+="<input URLVAR "+(nmreq>0?"CHKREQUIRED ":"")+" name=\""+nm+"nm\" id=\""+nm+"nm\" maxlength=100 size=50 VALUE=\""+nmval+"\" "+(dis==1?"DISABLED ":"")+" onblur=DoReq(this)>";
	fnlstr+="<input URLVAR "+(!isNaN(nmreq)&&nmreq>0?"CHKREQUIRED ":(nmreq!=''?"CHKREQUIRED=\""+nmreq+"\" ":""))+" name=\""+nm+"nm\" id=\""+nm+"nm\" maxlength=100 size=50 VALUE=\""+nmval+"\" "+(dis==1?"DISABLED ":"")+" onblur=DoReq(this)>";
	fnlstr+=(nmtyp!=2?"<br><input type=radio style=visibility:hidden>":"")+(appendHTML!=null?"<br>"+appendHTML:"")+"</td></tr>";
	if((iddisp&1)==1)
	{	genstr=JSVCGenIDStr(1,nm+"ID1",dis,req1,sel1,val1, hiderad1);
		if(genstr!="" && genstr!=null)
			fnlstr+="<tr id=TRINSUREDDTL2><td valign=baseline>"+text[1]+"</td><td>"+genstr+"</td></tr>";
	}
	if((iddisp&2)==2)
	{	
		genstr=JSVCGenIDStr(2,nm+"ID2",dis,req2,sel2,val2, hiderad2);
		if(genstr!="" && genstr!=null)
			fnlstr+="<tr id=TRINSUREDDTL3><td valign=baseline>"+text[2]+"</td><td>"+genstr+"</td></tr>";
	}
	if(dis!=1)
	{
		AddOnloadCode("JSVCNameClick('"+nm+"');");
	}
	return fnlstr;
}
function JSVCDoMobile(obj,re,allowNoPhone)
{
	var r;
	Despace(obj);
	r=obj.value.toUpperCase();
	if(allowNoPhone==null)
		allowNoPhone=1;
	if(r.length>0)
	{	if(r=="NOPHONE" && allowNoPhone==1)
			obj.value=r
		else
		{	if(re==null)
				re=obj.getAttribute("MRMREFORMAT");
			if(re!="")
			{
			re=new RegExp(re);
			if(r.search(re)<0 || (r==(("000000000000000000").substring(0,r.length))))
			{
				alert(JSVClang("Invalid mobile number.",3337));
				obj.value="";
				obj.select();
			}}
		}
	}
	DoReq(obj.previousSibling);
}
function JSVCDoPhone(obj,rx)
{
	var val,re,val2,chkreq;
	val=obj.value;
	val2=obj.getAttribute("CURVALUE");
	chkreq=obj.getAttribute("CHKREQUIRED");
	if(val2 && val2!="" && val==val2)
		return;
	if(rx!=null && rx!="") {
		re=new RegExp(rx);
	} else {
		if(jSVClocid==2)
			re=/^[689][0-9]{7}$/;
		else
			re=/^\+?[0-9]{2,}\-[0-9]{6,8}(\/[0-9]+)*$/;
	}
	if(val.search(re)<0 && val!="")
	{
		if(chkreq!=null && val.toUpperCase().search("NOPHONE")>=0)
			val="NOPHONE"
		else {
			if(rx)
				alert("Invalid phone format.");
			else
				if(jSVClocid==2)
					alert("Invalid phone format. Use 6xxxxxxx/8xxxxxxx/9xxxxxxx format.");
				else
					alert(JSVClang("Invalid phone format. Use xxx-xxxxxxx or xxx-xxxxxxx/xx/xx format.",5693));
			val="";
		}
	}
	obj.value=val;
	DoReq(obj);
}
function JSVCDoEmail(obj,type,allownoemail) {
	var r,rx;
	Despace(obj);
	r=obj.value;
	if(type==null) type=0;
	if(allownoemail==null) allownoemail=1;
	if(r.length>0) {
	  if(allownoemail==1 && r.toUpperCase()=='NOEMAIL') {
      obj.value=r.toUpperCase();
	  } else if(type==1)
			rx=/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9_\.\-]+\.[a-zA-Z0-9]{2,4}$|^([0-9a-zA-Z_]{3,20})$/;
		else
			rx=/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9_\.\-]+\.[a-zA-Z0-9]{2,4}$/;
		if(!rx.test(r)) {
			alert("Invalid Email.");
			obj.select();
		}
	}
	DoReq(obj);
}
function JSVCGetMobile(nm)
{	var o,ret;
	o=document.getElementsByName(nm);
	if(o!=null && o.length>0)
	{	o=o[0];
		o2=o.previousSibling;
		if(o.value!="NOPHONE"&&o.value!=""&&o2!=null&&o2.tagName=="SELECT"&&o2.value!="")
			return o2.value+o.value;
	}
	return "";	
}

//KY: To set value for mobile phone field from javascript populate
function JSVCSetMobile(objname,val){
	var phoneobj,prefixobj,t,preflen;
	phoneobj=document.getElementById(objname);
	prefixobj=document.getElementById(objname+'pref');
	if(phoneobj&&prefixobj){
		preflen=0;
		prefixobj.value = '';
		if(val==null)val='';
		if(val.length > 0){
			for (t = 0; t < prefixobj.options.length; t++) {
				if (val.substring(0, prefixobj.options[t].value.length) == prefixobj.options[t].value) {
					prefixobj.value = prefixobj.options[t].value;
					preflen = prefixobj.options[t].value.length;
				}
			}			
		}
		document.getElementById(objname).value=val.substring(preflen, val.length);
		document.getElementById(objname).onblur();		
	}
}

function JSVCGenMobile(name,prefixes,postfixRE,value,req,disabled,allowNoPhone)
{
	var aprefixes,t,sel,out;
	out="";
	if(prefixes==null)
		prefixes="";
	if(req==null)
		req=1;
	if(allowNoPhone==null)
		allowNoPhone=1;
	if(prefixes!="")
	{
		sel=0;
		aprefixes=prefixes.split(",");
		if (aprefixes.length > 1) // If more than one  Prefixes
		{
			out += "<select CHKREQUIRED=\"obj.nextSibling.value!='NOPHONE'" + (req == 1 ? "" : "&&obj.nextSibling.value!=''") + "\" id=\"" + name + "pref\" name=\"" + name + "pref\" onblur=DoReq(this);DoReq(this.nextSibling); " + (disabled ? "DISABLED" : "") + ">" + (aprefixes.length > 1 ? "<OPTION/>" : "");
			for (t = 0; t < aprefixes.length; t++) {
				if (sel == 0 && value != null && value.length > 0 && value.substring(0, aprefixes[t].length) == aprefixes[t]) {
					sel = 1;
					value = value.slice(aprefixes[t].length);
				}
				else 
					sel = 0;
				out += "<OPTION value=\"" + aprefixes[t] + "\"" + (sel == 1 ? " SELECTED" : "") + ">" + aprefixes[t] + "</OPTION>";
			}
		}
		else // IF only one Prefix (Added By Oliver 11May2010)
		{	
			var prefvalue = aprefixes[0];		
			var preflen = prefvalue.length;

			if(value.length>=preflen && value.substring(0,preflen)==prefvalue) 
				value=value.slice(preflen);

			out += "<input CHKREQUIRED=\"obj.nextSibling.value!='NOPHONE'" + (req == 1 ? "" : "&&obj.nextSibling.value!=''") + 
			        "\" id=\"" + name + "pref\"" + 
					"name=\""  + name + "pref\"" + 
					"value=\"" + prefvalue + "\"" +
					"Size=\""  + preflen + "\"" +
					"Maxlength=\"" + preflen + "\"" + 
					"onblur=DoReq(this);DoReq(this.nextSibling); " +				
					"READONLY>"; // To Display				
					//"DISABLED>";	
			/*
			out += "<input TYPE=Hidden CHKREQUIRED=\"obj.nextSibling.value!='NOPHONE'" + (req == 1 ? "" : "&&obj.nextSibling.value!=''") + 
			        "\" id=\"" + name + "pref\"" + 
					"name=\""  + name + "pref\"" + 
					"value=\"" + prefvalue + "\"" +
					"Size=\""  + preflen + "\"" +
					"Maxlength=\"" + preflen + "\"" + 
					"onblur=DoReq(this);DoReq(this.nextSibling); " +				
					">";			// To Pass Over Act File	
					*/			
		}
	}
	// Mike
	// Commented out by Andrew - wrong way to do thing should make it non required rather than force NOPHONE!
//	if(locid!=null&&value.length==0&&(locid==2||locid==4||locid==6))
//		value="NOPHONE";
	out+="<input "+(req==1?"CHKNAME=\""+JSVClang("Mobile No",6032)+"\" CHKREQUIRED ":"")+"name=\""+name+"\" id=\""+name+"\" VALUE=\""+value+"\" MRMREFORMAT=\""+postfixRE+"\" onblur='JSVCDoMobile(this,null,"+(allowNoPhone==1?1:0)+");DoReq(this);' "+(disabled?"DISABLED":"")+">";
	return out;
}

/*
function JSVCGenMobile(name,prefixes,postfixRE,value,req,disabled,allowNoPhone)
{
	var aprefixes,t,sel,out;
	out="";
	if(prefixes==null)
		prefixes="";
	if(req==null)
		req=1;
	if(allowNoPhone==null)
		allowNoPhone=1;
	if(prefixes!="")
	{
		sel=0;
		aprefixes=prefixes.split(",");
		out+="<select CHKREQUIRED=\"obj.nextSibling.value!='NOPHONE'"+(req==1?"":"&&obj.nextSibling.value!=''")+"\" id=\""+name+"pref\" name=\""+name+"pref\" onblur=DoReq(this);DoReq(this.nextSibling); "+(disabled?"DISABLED":"")+">"+(aprefixes.length>1?"<OPTION/>":"");
		for(t=0;t<aprefixes.length;t++)
		{
			if(sel==0 && value!=null && value.length>0 && value.substring(0,aprefixes[t].length)==aprefixes[t])
			{	sel=1;value=value.slice(aprefixes[t].length); }
			else
				sel=0;
			out+="<OPTION value=\""+aprefixes[t]+"\""+(sel==1?" SELECTED":"")+">"+aprefixes[t]+"</OPTION>";
		}
	}
	// Mike
	// Commented out by Andrew - wrong way to do thing should make it non required rather than force NOPHONE!
//	if(locid!=null&&value.length==0&&(locid==2||locid==4||locid==6))
//		value="NOPHONE";
	out+="<input "+(req==1?"CHKNAME=\""+JSVClang("Mobile No",6032)+"\" CHKREQUIRED ":"")+"name=\""+name+"\" id=\""+name+"\" VALUE=\""+value+"\" MRMREFORMAT=\""+postfixRE+"\" onblur=JSVCDoMobile(this,null,"+(allowNoPhone==1?1:0)+") "+(disabled?"DISABLED":"")+">";
	return out;
}
*/

function SVChtm(txt,typ,relist,reresult)
{	if(typeof(txt)!="string")return null;
	txt=txt.replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
	if(typ==2){	
		if(txt.substring(txt.length-2,txt.length)=="\n ")
			txt=txt.substring(0,txt.length-2)+"<br>&nbsp;";
		txt=txt.replace(/\n/g,"<br>");
		if(relist!=null&&reresult!=null)
		for(var t in relist)
			txt=txt.replace(relist[t],reresult[t]);
	}
	return txt;
}
function JSVCremoveURL(url,str)
{
	// Sync: JSVCremoveURL() and FN.SVCremoveURL()
    rgexp=new RegExp("([&\?])("+str+")[=][^&]*","gi");
    result=url.replace(rgexp,"$1");
    result=result.replace(/([&\?])&*/gi,"$1");
    result=result.replace(/&*$/,""); // remove at ending
    return result;
}
function JSVCgenOptions(str,sep,sel,rettext,sort){
	var lst, t, ret;
	if (sep == null || sep == "") 
		sep = ",";
	ret = "";
	var srt={
		load:function(str,sep) {
			var lst=str.split(sep);
			this.sep=sep;
			this.list=[];
			for(t=0;t<lst.length-1;t+=2) {
				this.list[t/2]=[lst[t],lst[t+1]];
			}
		},
		sf:function(a,b) {
			var a1=a[1];var b1=b[1];var c=0;			
			if(a1>b1) c=1;
			else if(a1<b1) c=-1;
			else c=0;
			return c;
		},
		result:function() {
			var ar=this.list.sort(this.sf);
			for(var i in ar)
				ar[i]=ar[i].join(this.sep);
			ar=ar.join(this.sep);
			return ar;
		}
	}
	if(sort==1) {
		srt.load(str,sep);
		lst=srt.result().split(sep);
	}
	else
		lst=str.split(sep);
	for (t = 0; t < lst.length-1; t += 2) {
		if(lst[t+1]=="")lst[t+1]=lst[t];
		if(sel==lst[t] && rettext!=null)rettext.txt=lst[t + 1];
		ret += "<OPTION VALUE=\"" + lst[t] + "\"" + (sel == lst[t] ? " SELECTED" : "") + ">" + SVChtm(lst[t + 1]) + "</OPTION>";
	}
	return ret;
}
function JSVCbodyResize(obj)
{
	if(parent!=null)
		if(parent.bodyResizeHook!=null)
			parent.bodyResizeHook(obj);
}
function JSVCoptionsAdd(obj,text,value) {
    if(!(obj!=null && obj.tagName=="SELECT")) return;
	
	var chkdupe=function(options,value) {
		for(var i=0;i<options.length;i++) {
			if(options[i].value==value)
				return true;
		}
		return false;
	}

    if(text!=null && text.constructor.toString().indexOf("Array")>=0) {
		if(!chkdupe(obj.options,text[1]))
	        obj.options[obj.options.length]=new Option(text[0],text[1]);
	}
    else if(value!=null && value.constructor.toString().indexOf("Array")>=0) {
		if(!chkdupe(obj.options,value[0]))
	        obj.options[obj.options.length]=new Option(value[1],value[0]);
	}
    else {
		if(!chkdupe(obj.options,value))
	        obj.options[obj.options.length]=new Option(text,value);
	}
}
function JSVCoptionsRemove(obj,value) {
    if(!(obj!=null && obj.tagName=="SELECT")) return;
	
	for(var i=0;i<obj.options.length;i++) {
		if(obj.options[i].value==value) {
			obj.remove(i);
			break;
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////
// To open a new window
// src = URL to point to in the new window
// cascade = offset from the parent window in pixel
// menubar = to turn on menu bar ('yes' or 'no')
// awidth = width of the window
// aheight = height of the window
// returnwin = true: returns a reference to the new window; false: no return
// wintype = window type - window: opens a new window; modeless: opens a modeless dialog box; modal: opens a modal dialog box
////////////////////////////////////////////////////////////////////////////////////////
function JSVCopenWin(src, cascade, menubar, awidth, aheight, returnwin, wintype, winname )
{
	if (cascade == null) cascade = 0;
	if (menubar == null) menubar = "no";
	if (returnwin==null) returnwin = false;
	if (wintype==null) wintype = "window";

	var aWin = window.self;
	var x_offset, y_offset, win_width, win_height, aStr, newwin;
    
    if (awidth == null)
    {    
        x_offset = 50;        
    }
    else
    {
        x_offset = (aWin.screen.availWidth - awidth )/ 2;
    }    
    if (aheight == null)
    {
        y_offset = 50;        
    }
    else
    {
        y_offset = (aWin.screen.availHeight - aheight ) / 2;      
    }    
    win_width = aWin.screen.availWidth - (2 * x_offset);
    win_height = aWin.screen.availHeight -(2 * y_offset);
	if (menubar="yes") win_height -= 50; // roughly the size of the menubar
    y_offset = y_offset + cascade;
    x_offset = x_offset + cascade;	
	if(winname==null)
		winname="";
	switch (wintype)
	{
		case "window": 
		{
			aStr = "left=" + x_offset + ",height=" + win_height + ",top=" + y_offset + ",width=" + win_width + ",scrollbars=yes,resizable=yes,status=yes,menubar="+menubar;
			newwin=window.open(src, winname, aStr );
			break;
		}
		case "modeless":
		{
		 	aStr = "dialogLeft:" + x_offset + "px; dialogHeight:" + win_height + "px; dialogTop:" + y_offset + "px; dialogWidth:" + win_width + "px; resizable:'yes'; status:'yes'"; 
			newwin=window.showModelessDialog(src, winname, aStr);
			break; 
		}
		case "modal":
		{
			aStr = "dialogLeft:" + x_offset + "px; dialogHeight:" + win_height + "px; dialogTop:" + y_offset + "px; dialogWidth:" + win_width + "px; resizable:'yes'; status:'no'"; 
			newwin=window.showModalDialog(src, winname, aStr);
			break;
		}
	}
	if (returnwin) return newwin; 	
}
function JSVCDoBackWarning()
{
	document.write("<form autocomplete='off'><blockquote class=clsColorNote style=display:none><input type=hidden id=MMPARSEONCE>"+JSVClang("You are returning to a previous page. This page may be outdated.<br>Please click 'Refresh' to refresh the page.",1378)+"</blockquote></form>");
	AddOnloadCode("var obj=document.getElementById('MMPARSEONCE');if(obj.value=='1') { obj.parentNode.style.display=''; } else { obj.value='1'; };");
}
function JSVCshow(obj,show)
{
    if(show==null)
        show=1;
    var o,listarr;
    if(typeof(obj)=="string") {
		listarr=obj.split(",");
		for(abc in listarr) {
			o=JSVCall(listarr[abc]);
		    if(o!=null)
		        o.style.display=(show==1?"":"none");
		}
		return;
	}
    else if(obj!=null)
        o=obj;
    if(o!=null)
        o.style.display=(show==1?"":"none");
}
function JSVChide(obj)
{
    JSVCshow(obj,0);
}

/*------------------------Kian Yee:Popup a Window ------------------*/
//1 - for maximize ,2 - for fullscreen,3 - clean params
function JSVCgenPopLink(url, winname, w, h,full,exstring)
{
	var params,PopupWin;
	if (winname==null||winname==""){
		winname = 'PopupWin';
		}
	if (w==null||w==""){
		w = 600;
	}
	if (h==null||h==""){
		h = 600;
	}
	if (exstring==null){
		exstring="";
	}
	if (full!=null&&full==1){
		params  = 'scrollbars=yes,resizable=yes,width='+screen.width+', height='+screen.height+', top=0, left=0'+', fullscreen=yes'+exstring;
	}
	if  (full==3){
		params  = 'width='+w+',height='+h+exstring;
	}
	else{		
		params = 'scrollbars=yes,resizable=yes,width='+w+',height='+h+exstring;
	}		
	PopupWin = window.open(url,winname,params);
	PopupWin.focus();
}

/*----------------------Kian Yee:Check Leap Year ----------------*/
function JSVCCheckLeapYear(chkyear)
{
	if (chkyear%4 == 0&&(chkyear%100 != 0||chkyear%400 == 0))
	{
		return true;
	}
	else
	{
		return false;
	}	
}
/*---------------------Kian Yee: Date Functions --------------*/
/*
 DateAdd:
 type - year,month,day (will add on later)
 num - num to be added
refdate - date to be added from
 
 return new date value
 *REMARKS: This is to handle the leap year problem in javascript and also the month rounded to next month problem; date will follow sql style
 */
function JSVCDateAdd(type,num,refdate)
{
	if(num==""||num==null) num=0;
	if(refdate==null||refdate=="")return refdate;
	if(typeof refdate=='string') refdate = CalParseDate(refdate);
	var newdate = new Date(refdate);
	if(type.toUpperCase() == 'Y' || type.toUpperCase() == 'YEAR' || type.toUpperCase() == 'YY' || type.toUpperCase() == 'YYYY')
	{
		newdate.setYear(refdate.getFullYear()+num);
		if (refdate.getDate()!= newdate.getDate()) newdate.setDate(newdate.getDate() - 1); 
		return newdate;
	}
	else if(type == 'M' || type.toUpperCase() == 'MONTH' || type == 'MM')
	{
		newdate.setMonth(refdate.getMonth()+num);
		while ((refdate.getMonth()+num)%12 < newdate.getMonth())
		{
			newdate.setDate(newdate.getDate() - 1);
		} 
		return newdate;		
	}
	else if (type.toUpperCase()=='D' || type.toUpperCase()=='DAY' || type.toUpperCase()== 'DD')
	{
		newdate.setDate(refdate.getDate()+num);
		return newdate;
	}
}

/* Andrew 02Nov2010 */
function JSVCFullDateDiff(firstdate,seconddate)
	{	
		var a=new Object();
		a.Year=0;
		a.Month=0;
		a.Day=0;
		while(JSVCDateAdd("Y",a.Year+1,firstdate) <= seconddate)
		{
			a.Year++;
		}
		firstdate=JSVCDateAdd("Y",a.Year,firstdate);

		while(JSVCDateAdd("M",a.Month+1,firstdate) <= seconddate)
		{
			a.Month++;
		}
		
		firstdate=JSVCDateAdd("M",a.Month,firstdate);

		while(JSVCDateAdd("D",a.Day+1,firstdate) <= seconddate)
		{	
			a.Day++;
		}
		return a;
	}

/*PC Comment*/
function JSVCDateDiff(type,firstdate,seconddate)
{
	if (firstdate==null || firstdate=='' || seconddate==null || seconddate=='') return null;
	if(firstdate.constructor!=Date)
		firstdate = CalParseDate(firstdate);
	if(seconddate.constructor!=Date)
		seconddate = CalParseDate(seconddate);
	if (firstdate==null || firstdate=='' || seconddate==null || seconddate=='') return null;
	
	var diffval=0;
	if (type.toUpperCase()=='D' || type.toUpperCase()=='DAY' || type.toUpperCase()== 'DD')
	{
	    var difference = seconddate.getTime() - firstdate.getTime();
	    var daysDifference = Math.floor(difference/1000/60/60/24);
		/*
	    difference -= daysDifference*1000*60*60*24;
	    var hoursDifference = Math.floor(difference/1000/60/60);
	    difference -= hoursDifference*1000*60*60;
	    var minutesDifference = Math.floor(difference/1000/60);
	    difference -= minutesDifference*1000*60;
	    var secondsDifference = Math.floor(difference/1000);
	    document.write('difference = ' + daysDifference + ' day/s ' + hoursDifference + ' hour/s ' + 
		minutesDifference + ' minute/s ' + secondsDifference + ' second/s ');*/
		diffval=daysDifference;
	}
	else if(type == 'M' || type.toUpperCase() == 'MONTH' || type == 'MM')
	{
		diffval = ((seconddate.getFullYear() - firstdate.getFullYear()) * 12) + seconddate.getMonth() - firstdate.getMonth();
	}
	else if(type.toUpperCase() == 'Y' || type.toUpperCase() == 'YEAR' || type.toUpperCase() == 'YY' || type.toUpperCase() == 'YYYY')
	{
		diffval = seconddate.getFullYear() - firstdate.getFullYear();
	}
	else if(type.toUpperCase() == 'H' || type.toUpperCase() == 'HOUR' || type.toUpperCase() == 'HH')
	{
		diffval = Math.floor((seconddate.getTime() - firstdate.getTime()) / (1000 * 60 * 60));
	}
	else if(type == 'm' || type.toUpperCase() == 'MIN' || type == 'mm' || type.toUpperCase() == 'MINUTE')
	{
		diffval = Math.floor((seconddate.getTime() - firstdate.getTime()) / (1000 * 60));
	}
	else if(type.toUpperCase() == 'S' || type.toUpperCase() == 'SECOND' || type.toUpperCase() == 'SS' || type.toUpperCase() == 'SEC')
	{
		diffval = Math.floor((seconddate.getTime() - firstdate.getTime()) / 1000);
	}
	
	return diffval;
}

/*
 CompareDate:
 firstdate - first date input to compare (from date)
 seconddate - second date input to compare (to date)
 type - 1:year , 2:month , 3:day
 num - maximum range (ex: type 1 - maximum years allowed for the date range)
 range - 0:any range 1:must be in round number year 2:must be in round number month
 firstdatename - name for firstdate
 seconddatename - name for seconddate
 
 return true - valid; false - not valid
 *REMARKS: Currently, it will add 1 min to end date for every check, need to find a better solution
 *Took off null checking, empty is treated as null by default
 */
function JSVCCompareDate(firstdate,seconddate,firstdatename,seconddatename,type,num,range)
{
	if(range==null||range=='')range = 0;
	if (firstdate != null && seconddate != null) {
		if (firstdatename == '' || firstdatename == null) 
			firstdatename = 'Start Date';
		if (seconddatename == '' || seconddatename == null) 
			seconddatename = 'End Date';
		if(typeof firstdate=='string') firstdate = CalParseDate(firstdate);
		if(typeof seconddate=='string') seconddate = CalParseDate(seconddate);
		if (seconddate != null && firstdate >= seconddate) {
			alert(firstdatename + " is greater than " + seconddatename + ". Please make sure that the date range specified is valid.");
			return false;
		}
		if (range==1)
		{
			if (firstdate.getMonth()!=seconddate.getMonth()||firstdate.getDate()!=seconddate.getDate())
			{
				alert("The range of " + firstdatename + " and " + seconddatename + " is not in rounded years. Please make sure that the date range specified is valid.");
				return false;			
			}
		}
		else if (range==2)
		{
			if (firstdate.getDate()!=seconddate.getDate())
			{
				alert("The range of " + firstdatename + " and " + seconddatename + " is not in rounded months. Please make sure that the date range specified is valid.");
				return false;					
			}			
		}
		if ((type != null && type != '') && (num != null && num != '')) {
			if (type == 1) {
				var validdate = new Date(firstdate.setFullYear(firstdate.getFullYear() + num));
				if (seconddate > validdate) {
					alert("The range of " + firstdatename + " and " + seconddatename + " is out of the permitted date range which is " + num + " year/s. Please make sure that the date range specified is valid.");
					return false;
				}
			}
			else 
				if (type == 2) {
					var validdate = new Date(firstdate.setMonth(firstdate.getMonth() + num));
					if (seconddate > validdate) {
						alert("The range of " + firstdatename + " and " + seconddatename + " is out of the permitted date range which is " + num + " month/s. Please make sure that the date range specified is valid.");
						return false;
					}
				}
				else 
					if (type == 3) {
						var validdate = new Date(firstdate.setDate(firstdate.getDate() + num));
						if (seconddate > validdate) {
							alert("The range of " + firstdatename + " and " + seconddatename + " is out of the permitted date range which is " + num + " day/s. Please make sure that the date range specified is valid.");
							return false;
						}
					}
		}
	}
	return true;
}
/*--------------------------------End of Date functions ----------------------------------------------*/

function JSVCLabelStr(lblname,colorbgrnd,colortxt)
{	return "<span style=\"background-color:"+colorbgrnd+";color:"+colortxt+";font-size:10px;padding:2px;padding-left:8px;padding-right:8px;\">"+lblname+"</span>";
}
function JSVCLabelEditClick(event,obj)
{	var grpid,pobj,olist;
	grpid=obj.getAttribute("GRPID");
	if(typeof(grpid)=="string" && grpid!=null && grpid!="")
	{
		pobj=obj.parentNode.parentNode;
		if(pobj==null)return;
		olist=pobj.getElementsByTagName("input");
		for(var t=0;t<olist.length;t++)
		{	if(olist[t]!=obj && olist[t].name=="chklbl" && olist[t].type=="checkbox" && olist[t].checked && olist[t].checked==true && olist[t].getAttribute("GRPID")==grpid)
				olist[t].checked=false;
		}		
	}
}
function JSVCLabelList(lst) // Accept triples of lblname,colorbgrnd,colortxt
{	var s,i;
	s="";
	for(i=0;i+3<=lst.length;i+=3)
		s+=JSVCLabelStr(lst[i],lst[i+1],lst[i+2]);
	return s;
}

/*--------Kian Yee: Firefox Adaption Functions----*/
 function JSVCCleanWhitespace(node) 
 {
      var notWhitespace = /\S/;
      for (var i=0; i < node.childNodes.length; i++) {
         var childNode = node.childNodes[i];
          if ((childNode.nodeType == 3)&&(!notWhitespace.test(childNode.nodeValue))) {
             // that is, if it's a whitespace text node
            node.removeChild(node.childNodes[i]);
             i--;
          }
          if ( childNode.nodeType == 1) {
              // elements can have text child nodes of their own
              JSVCCleanWhitespace(childNode);
          }
      }
 }

JSVCinsertAdjacentElement = function (obj,where,parsedNode) 
{ 
	switch (where){ 
	case 'beforeBegin': 
	obj.parentNode.insertBefore(parsedNode,obj) 
	break; 
	case 'afterBegin': 
	obj.insertBefore(parsedNode,obj.firstChild); 
	break; 
	case 'beforeEnd': 
	obj.appendChild(parsedNode); 
	break; 
	case 'afterEnd': 
	if (obj.nextSibling) 
	obj.parentNode.insertBefore(parsedNode,obj.nextSibling); 
	else obj.parentNode.appendChild(parsedNode); 
	break;
	}
}
 
JSVCinsertAdjacentHTML = function (obj,where,htmlStr) 
{ 
if (document.all){obj.insertAdjacentHTML(where,htmlStr);}
else
	{
	var r = obj.ownerDocument.createRange(); 
	r.setStartBefore(obj); 
	var parsedHTML = r.createContextualFragment(htmlStr); 
	JSVCinsertAdjacentElement(obj,where,parsedHTML)
	} 
}
function JSVCGetPosXY(obj,type){
	if(type==null||type=='')type=1; //type 1: absolute position ; type 2: relative to window displayed
	var x=0,y=0;
	while (obj!=null&&obj.nodeName!="BODY"){
		x+=obj.offsetLeft-obj.scrollLeft;
		y+=obj.offsetTop-obj.scrollTop;
		obj=(obj.offsetParent?obj.offsetParent:obj.parentNode);
	}
	if (type==2){
		x= x-document.body.scrollLeft;
		y= y-document.body.scrollTop;
	}
	return {x:x,y:y};
}

//TESTING VERSION: DUN USE IT YET!!!
function JSVCSelectSingleNode(obj,path)
{  
	if (document.implementation && document.implementation.createDocument)      
	{ 
		var nodes=document.evaluate(path, obj, null, XPathResult.ANY_TYPE, null);
		var results=nodes.iterateNext();
		return results;       
	}
	else 
	{
		obj.selectSingleNode(path);
	}   
}

function JSVChtmUnescape(sXml) {
    return sXml.replace(/&apos;/g,"'")
    .replace(/&quot;/g,"\"")
    .replace(/&gt;/g,">")
    .replace(/&lt;/g,"<")
    .replace(/&amp;/g,"&");
}
/*----End of Firefox Adaption function---*/
function JSVCArrayIndexOf(arr,elt/*,from*/) 
{
	var len = arr.length;    
	var from = Number(arguments[2]) || 0;
	from = (from < 0)? Math.ceil(from) : Math.floor(from);
	if (from < 0)
		from += len;
	for (; from < len; from++) 
	{
		if (from in arr && arr[from] == elt)
			return from;
    }
	return -1;  
}
function JSVCArrayRemove(arr,val) {
	for(var i=0;i<arr.length;i++) {
		if(arr[i]==val)         
			arr.splice(i--,1);
	}
}
/* Generates a TBODY DOM object from HTML (gets around DOM limitation, can use for TR too) */
function JSVCcreateTBODY(html)
{	var otmp,t2;
	var otmp=document.createElement("DIV");
	otmp.style.display="none";
	otmp.style.position="absolute";
	otmp.style.zIndex=-1000;
	document.body.appendChild(otmp);
	if(otmp==null)
		return null;
	otmp.innerHTML="<table>"+html+"</table>";
	t2=otmp.firstChild.tBodies[0];
	if(t2!=null)
		t2=t2.cloneNode(true);
	document.body.removeChild(otmp);
	return t2;
}
function JSVCqueryGetColNo(query,column) {
	column=column.toLowerCase();
	if(!query.COLUMNS||!query.DATA) { // returned from serialiseJSON()
		return null;
	}
	for(var x in query.COLUMNS)
		if(query.COLUMNS[x].toLowerCase()==column) {
			return x;
		}
	return -1;
}
function JSVCqueryFindRow(query,colno,value,rowstart) {
	if(!query.COLUMNS||!query.DATA) { // returned from serialiseJSON()
		return null;
	}
	if(rowstart==null)
		rowstart=0;
	for(var t=rowstart;t<query.DATA.length;t++)
	{
		if(query.DATA[t][colno]==value)
			return query.DATA[t];
	}
	return null;
}
function JSVCqueryFindRows(query,colno,clause) {
	if(!query.COLUMNS||!query.DATA) { // returned from serialiseJSON()
		return null;
	}
	var rs={};
	rs.COLUMNS=query.COLUMNS;
	rs.DATA=[];
	for(var t=0;t<query.DATA.length;t++)
	{
		if(typeof(clause)=="function") { // a clause which returns boolean
			if(clause(query.DATA[t][colno]))
				rs.DATA.push(query.DATA[t]);
		} else {
			if(query.DATA[t][colno]==clause)
				rs.DATA.push(query.DATA[t]);
		}
	}
	return rs;
}
function JSVCqueryGetValue(query,column,rowIndex) {
	var i,x;
	if(query==null||!query.COLUMNS||!query.DATA) { // returned from serialiseJSON()
		return null;
	}
	i=JSVCqueryGetColNo(query,column);
	if(i>=0&&query.DATA[rowIndex]) {
		return query.DATA[rowIndex][i];
	}
	return null;
}
/* --------------------------
 System Prototype
-----------------------------*/
String.prototype.padLeft=function(char,maxLength) {
	var result=this.valueOf();
	for(var i=this.length;i<maxLength;i++)
		result=char+result;
	return result;
}
Date.prototype.add=function(interval,num) {
	var dt=this;
	if (num==0)
		return dt;
	switch(interval.toLowerCase()) {
		case "ms":
			dt.setMilliseconds(dt.getMilliseconds()+num);
			break;
		case "s":
			dt.setSeconds(dt.getSeconds()+num);
			break;
		case "mi":
			dt.setMinutes(dt.getMinutes()+num);
			break;
		case "h":
			dt.setHours(dt.getHours()+num);
			break;
		case "d":
			dt.setDate(dt.getDate()+num);
			break;
		case "mo":
			dt.setMonth(dt.getMonth()+num);
			break;
		case "y":
			dt.setFullYear(dt.getFullYear()+num);
			break;
	}
	return dt;
}
Date.prototype.DateFormat=function(format) {
	var smth=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
	var lmth=["January","February","March","April","May","June","July","August","September","October","November","December"];
	var sday=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
	var lday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
	var list=[
		["yyyy",function(dt){return dt.getFullYear()}],
		["mm",function(dt){return ((dt.getMonth()+1)<10?"0":"")+(dt.getMonth()+1)}],
		["dd",function(dt){return (dt.getDate()<10?"0":"")+dt.getDate()}],
		["mmm",function(dt){return smth[dt.getMonth()]}]
	];
	var rs=format;
	for(var i=0;i<list.length;i++) {
		var itm=list[i];
		if(format.indexOf(itm[0])>=0) {
			rs=rs.replace(itm[0],itm[1](this));
		}
	}
	return rs;
}
Date.prototype.TimeFormat=function(format) {
	var s="";
	var list=[
		["HH",function(dt){return (dt.getHours()<10?"0":"")+dt.getHours()}],
		["mm",function(dt){return (dt.getMinutes()<10?"0":"")+dt.getMinutes()}],
		["ss",function(dt){return (dt.getSeconds()<10?"0":"")+dt.getSeconds()}],
		//12 hour format
		["h",function(dt){return (dt.getHours()>=12?(dt.getHours()==12?12:dt.getHours()-12):(dt.getHours()==0?12:dt.getHours()))}],
		["TT",function(dt){return (dt.getHours()>=12?"PM":"AM")}]
	];
	var rs=format;
	for(var i=0;i<list.length;i++) {
		var itm=list[i];
		if(format.indexOf(itm[0])>=0) {
			rs=rs.replace(itm[0],itm[1](this));
		}
	}
	return rs;
}
/* http://delete.me.uk/2005/03/iso8601.html */
/* KY : fixing for DB string, output without the T, no offset*/ 
Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "((T| )([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));
    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[8]) { date.setHours(d[8]); }
    if (d[9]) { date.setMinutes(d[9]); }
    if (d[11]) { date.setSeconds(d[11]); }
    if (d[13]) { date.setMilliseconds(Number("0." + d[13]) * 1000); }
    /*if (d[15]) {
        offset = (Number(d[17]) * 60) + Number(d[18]);
        offset *= ((d[16] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();*/
    time = (Number(date) /*+ (offset * 60 * 1000)*/);
    this.setTime(Number(time));
}
/* --------------------------
 JSVCform Class
-----------------------------*/
function JSVCform(id,type,title,columns,order,repeat,queryPK,query,showinit,allowdel,nopreprocessform,titlestyle) {
	this.id=id; // varname
	this.type=type;
	this.title=title;
	this.columns=columns;
	this.order=order;
	this.repeat=repeat;
	if(this.repeat>1)
		this.type="TABLE";
	this.queryPK=queryPK; // for repeat>1
	this.query=query; // for repeat>1	
	this.showinit=(showinit==null?1:showinit);
	this.allowdel=(allowdel==null?0:allowdel);
	this.nopreprocessform=nopreprocessform;
	this.titlestyle=(titlestyle==null?0:titlestyle);
}
JSVCform.prototype.gen=function(cols) {
	JSVCArrayRemove(cols,null);
	this.cols=cols;
	if(this.repeat>1) {
		this.show=this.query.DATA.length;
		if(this.show>this.repeat)
			this.repeat=this.show;
		if(this.show==0)
			this.show=this.showinit;
	}
	else
		this.show=1;
	document.write("<input type=hidden name="+this.id+"_ROWCNT value="+this.show+">");
	document.write("<input type=hidden name="+this.id+"_REPEATROWS value="+this.repeat+">");
	document.write("<div id="+this.id+">");
	if(this.repeat>1) {
		for(var i=0;i<this.repeat;i++)
			this.gen2(cols,i);
		if(this.repeat>1&&this.show<this.repeat)
			document.write("<div style=margin-top:6px align=left><input type=button class=clsSVCButton value='"+(this.show>0?JSVClang("Add More",7645):JSVClang("Add",2210))+" >>' onclick='var result="+this.id+".addMore(this);if(result){JSVChide(this.parentNode)}'></div>");
	}
	else
		this.gen2(cols,null);
	document.write("</div>");
	if(!this.nopreprocessform&&!/MrmPreprocessForm/gi.test(window.onload))
		AddOnloadCode("MrmPreprocessForm();");
}
JSVCform.prototype.gen2=function(cols,index) {
	var str="";
	for(var i=0;i<cols.length;i++) {
		if(i>0 && (i%this.columns)==0)
			str+="</tr>";
		if(i<cols.length && (i%this.columns)==0)
			str+="<tr>";
		str+="<td>"+(cols[i]?cols[i][1]:"")+"</td>"+"<td id=TAB"+this.id+index+"COL"+i+">"+this.getCol(cols[i],index)+"</td>";
	}
	if(cols.length>0)
		str+="</tr>";
	if(index==null)
		index=0;
	var rowid=JSVCqueryGetValue(this.query,this.queryPK,index);
	if(this.type=="TABLE") {
		document.write("<table class=clsClmTable width=100%"+(this.repeat>1?" id=TAB"+this.id+index:"")+" style=margin-top:6px;"+(this.repeat>1&&(index+1)>this.show?"display:none;":"")+">");
		if(this.title) {
			var title="";
			if(this.titlestyle==1)
				title=this.title+" #"+(index+1);
			else
				title=this.title+(index>0?" "+(index+1):"");
			document.write("<tr><td class=header colspan="+2*this.columns+" valign=bottom><div style=float:left>"+title+"</div>");
			if(this.allowdel==1 && this.repeat>1)
				document.write("<div style=float:right><input type=checkbox value='"+index+"|"+(rowid==null?0:rowid)+"' name="+this.id+"_CHKDEL id="+this.id+index+"_CHKDEL onclick=JSVCSetDisabledList('TAB"+this.id+index+"BODY',this.checked)><label for="+this.id+index+"_CHKDEL>Mark as Delete</label></div>");
			document.write("</td></tr>");
		}
		for(var i=0;i<this.columns;i++)
			document.write("<col class=clsClmRefTone1 style=font-weight:bold;width:35ex><col class=clsClmRefTone2 style='width:"+(this.columns>1?100/this.columns/2:"auto")+"%'>")
	}
	var tbodyid="TAB"+this.id+index+"BODY";
	str="<tbody id="+tbodyid+">"+str+"</tbody>";
	document.write(str);
	if(this.type=="TABLE") {
		document.write("</table>");
	}
	// trigger onblur for all input elements if possible
	var elem=JSVCall(tbodyid).getElementsByTagName("INPUT");
	for(var i=0;i<elem.length;i++) {
		var o=elem[i];
		if(o.onblur&&typeof(o.onblur)=="function")
			o.onblur();
	}
	document.write("<input type=hidden name="+this.id+"_"+this.queryPK+" value='"+(rowid==null?0:rowid)+"'>");
	this.ajaxStart();
}
JSVCform.prototype.getCol=function(col,index) {
	// standard cols - 0:type,1:title,2:objname,3:req,4:qryvaluename
	if(col==null)
		return "";
	var str="";
	var name,value,rowid;
	var multirows=(this.repeat>1 && index!=null && index>=0);
	if(multirows) { // multiple rows
		rowid=JSVCqueryGetValue(this.query,this.queryPK,index);
		if(rowid!=null) {
			name=col[2]+"_"+rowid; // existing row
			value=jGetVal(this.query,col[4]);
		} else {
			name=col[2]+index; // new row
			value="";
		}
	} else { // one row
		name=col[2];
		value=jGetVal(this.query,col[4]);
	}
	if(col[0]=="TEXT") {
		// 5:maxlength,6:size,7:uppercase,8:blurfunc,9:warnmsg
		str="<input type=text name="+name+(col[3]==1?" CHKREQUIRED":"")+" value=\""+value+"\""+(col[5]>0?" maxlength="+col[5]:"")+(col[6]>0?" size="+col[6]:"")+" onblur=DoReq(this);"+(col[8]!=null?col[8]+";":"")+(col[7]==1?"this.value=this.value.toUpperCase(); style=text-transform:uppercase":"")+">";
		if(col[9]!=null) {
			var msg="";
			eval(jTrParam(this.query,col[9]));
			if(msg!="")
				str+="<div class=clsSVCColorWarning>"+JSVChtmUnescape(msg)+"</div>";
		}
	}
	else if(col[0]=="CALDATE") {
		// 5:dtmin,6:dtmax,7:warnmsg
		str="<input MRMOBJ=CALDATE type=text name="+name+(col[3]==1?" CHKREQUIRED":"")+" value=\""+jFormat(0,value)+"\" maxlength=10"+(col[5]!=""?" DTMIN='"+col[5]+"'":"")+(col[6]!=""?" DTMAX='"+col[6]+"'":"")+" onblur=ObjDate(this)>";
		if(col[7]!=null) {
			var msg="";
			eval(jTrParam(this.query,col[7]));
			if(msg!="")
				str+="<div class=clsSVCColorWarning>"+JSVChtmUnescape(msg)+"</div>";
		}
	}
	else if(col[0]=="MONEY") {
		// 5:blurfunc
		str="<input type=text name="+name+(col[3]==1?" CHKREQUIRED":"")+" value=\""+jFormat(1,value)+"\" maxlength=12 size=20 onblur=JSVCCurr(this);"+(col[5]!=null?col[5]+";":"")+">";
	}
	else if(col[0]=="CHECKBOX") {
		// 5:bitmask,6:clickfunc
		var bitmask=(isNaN(col[5])?0:col[5]);
		var onclick=col[6];
		str="<input type=checkbox name="+name+(col[3]==1?" CHKREQUIRED":"")+" value="+bitmask+((value&bitmask)==bitmask?" checked":"")+(onclick!=null?" onclick="+this.id+".objCallback(this,'CHECKBOX','"+name+"')":"")+">";
	}
	else if(col[0]=="TEXTAREA") {
		// 5:maxchar,6:rows,7:width
		var maxchar=(col[5]==null?1024:col[5]);
		var rows=(col[6]==null?5:col[6]);
		var colwidth=(col[7]==null?"100%":col[7]);
		str="<textarea WRAP=SOFT MRMOBJ=TEXTAREA MAXCHAR="+maxchar+" ROWS="+rows+" name="+name+(col[3]==1?" CHKREQUIRED":"")+" style=width:"+colwidth+" onblur=ObjText(this)>"+value+"</textarea>";
	}
	else if(col[0]=="SELECT") {
		// 5:optionlist,6:seprator
		str="<select name="+name+(col[3]==1?" CHKREQUIRED":"")+" onblur=DoReq(this)><option>";
		str+=JSVCgenOptions(col[5],col[6],value);
		str+="</select>";
	}
	else if(col[0]=="JS") {
		// 5:qryvaluename2,6:jsfunc
		var value2=jGetVal(this.query,col[5]);
		str=eval(col[6]);
	}
	else if(col[0]=="HTML") {
		// 5:html
		str=col[5];
	}
	else if(col[0]=="AJAX") {
		// 5:url
		str="<div>Loading... <img style=vertical-align:middle src='"+request.approot+"services/images/loading-anim.gif'></div>";
	}
	return str;
	function jFormat(type,value) {
		var e=document.createElement("INPUT");
		e.value=value;
		if(type==0)
			ObjDate(e);
		else if(type==1)
			JSVCCurr(e);
		return e.value;
	}
	function jGetVal(qry,colname) {
		var value=JSVCqueryGetValue(qry,colname,(multirows?index:0));
		if(value==null)
			value="";
		return value;
	}
	function jTrParam(qry,str) {
		var rx=new RegExp("\{([a-z0-9_]+)\}","i"); // translate params i.e. {CASEID}
		var m=rx.exec(str)
		while(m!=null) {
			str=str.replace(m[0],jGetVal(qry,m[1]));
			m=rx.exec(str);
		}
		return str;
	}
}
JSVCform.prototype.addMore=function(obj) {
	var next=JSVCall("TAB"+this.id+this.show);
	if(next!=null) {
		JSVCshow(next);
		this.show++;
		next=JSVCall(this.id+"_ROWCNT");
		next.value=this.show;
	}
	// button text
	obj.value=(this.show>0?JSVClang("Add More",7645):JSVClang("Add",2210))+" >>"
	if(this.show>=this.repeat) // last to show?
		return true;
	else
		return false;
}
JSVCform.prototype.objCallback=function(sender,type,objname) {
	if(type=="CHECKBOX") {
		for(var i in this.cols)
			if(objname.indexOf(this.cols[i][2])>=0) {
				if(this.cols[i][6]!=null) {
					this.cols[i][6](sender);
				}
			}
	}
}
JSVCform.prototype.attachOnloadCode=function() {
	for(var i in this.cols) {
		var col=this.cols[i];
		if(col[0]=="CHECKBOX" && col[6]!=null && typeof(col[6])=="function") { // has function
			var f=col[6].toString();
			if(f.substr(0,8)=="function") {
				f=f.replace(/function[^\(]*\([^\)]*\)[^\{]*\{([\s\S]+)\}/,"$1");
			}
			AddOnloadCode(f+";");
		}
	}
}
JSVCform.prototype.ajaxStart=function() {
	for(var r=0;this.repeat>1 && r<this.repeat;r++)
		if((r+1)<=this.show) {
			for(var c=0;c<cols.length;c++) {
				var rowid=JSVCall("TAB"+this.id+r+"COL"+c);
				var col=this.cols[c];
				if(rowid!=null && col[0]=="AJAX") {
					MRMHTTPRequest("GET",col[5],null,this.ajaxComplete,null,null,null,null,rowid);
				}
			}
		}
}
JSVCform.prototype.ajaxComplete=function(xmlhttp,readyparam) {
	if(xmlhttp!=null) {
		var obj=JSVCall(readyparam);
		if(obj!=null) {
			var txt=xmlhttp.responseText;
			if(txt.length==0) {
				obj.innerHTML="ERROR";
			}
			else
				if(txt.length>0 && txt.match(/^[\s\t]*function/i))
					obj.innerHTML=eval(txt);
				else
					obj.innerHTML=txt;
		}
	}
}
function JSVCgetElementsByTagNameAndId(obj,tagname,id)
{
	var l=obj.getElementsByTagName(tagname);
	for(var t=0;t<l.length;t++)
	{	if(l[t].id==id)
			return l[t];
	}
	return null;
}
function JSVCRateInputChg(nm)
{	var sel,o1,o2,o3,tmp;
	o1=document.getElementsByName(nm+"DAYS")[0];
	o2=document.getElementsByName(nm+"RATE")[0];
	sel=JSVCRadioGetValue("rb"+nm);
	if(sel!=null)
	{
		o3=document.getElementsByName("sle"+nm)[0];
		if(sel=="1")
		{	o1.disabled=false;o2.disabled=false;o3.disabled=true;
		} else
		{	o1.disabled=true;o2.disabled=true;o3.disabled=false;
		}
		JSVCCurr(o3);
	}
	JSVC2DP(o1,9999,0.1);
	//JSVC1DP(o1,9999,0.1);
	JSVCCurr(o2);
	// Check if got TOTDISPID --> update total there instead
	tmp=o2.getAttribute("TOTDISPID");
	if(tmp!=null && tmp!="")
	{
		o3=document.getElementById(tmp);
		if(o3!=null&&o3.tagName=="INPUT")
		{
			o3.value=((o1.value==""||o2.value=="")?"":JSVCNumDBtoLOC(JSVCNumLOCtoDB(o1.value)*JSVCNumLOCtoDB(o2.value)));
			o3.onblur();
		}
	} else
		o2.nextSibling.nextSibling.nextSibling.innerHTML=((o1.value==""||o2.value=="")?"?":JSVCNumDBtoLOC(JSVCNumLOCtoDB(o1.value)*JSVCNumLOCtoDB(o2.value)));
}
function JSVCRateInputGenStr(nm,curr,desc,req,allow_lumpsum,days,rate,lumpsum,totdisp_id)
{	var str,chk;
	str="";
	if(days==null)days="";if(rate==null)rate="";if(lumpsum==null)lumpsum="";
	if(totdisp_id==null)totdisp_id="";
	if(days==""&&allow_lumpsum>0&&lumpsum!="")chk=0
	else chk=1;
	str+=
		/* Generate radio-button, if allow_lumpsum */
		(allow_lumpsum>0?"<input type=radio id=\"_rb"+nm+"1\" name=\"rb"+nm+"\" onclick=\"JSVCRateInputChg('"+nm+"')\" value=\"1\" "+(chk==0?"":" checked")+"><!--label for=\"_rb"+nm+"1\"--> ":"")+
		/* Generate day/rate calc fields */
			"<input CHKNAME=\""+desc+" ("+JSVClang("days",3642)+")\" "+(req?"CHKREQUIRED ":"CHKREQUIRED=\"obj.nextSibling.nextSibling.value!=''\" ")+" size=7 maxlength=6 name=\""+nm+"DAYS\" onblur=\"JSVCRateInputChg('"+nm+"')\" value=\""+days+"\"> "+" x <input  CHKNAME=\""+desc+" ("+JSVClang("rate",7213)+")\" "+(req?"CHKREQUIRED ":"CHKREQUIRED=\"obj.previousSibling.previousSibling.value!=''\" ")+"size=10 maxlength=8 "+(totdisp_id!=""?"TOTDISPID=\""+totdisp_id+"\" ":"")+" name=\""+nm+"RATE\" onblur=\"JSVCRateInputChg('"+nm+"')\" value=\""+JSVCCurr(rate)+"\"> "+
			curr+"("+JSVClang("rate",7213)+")"+(totdisp_id==""?" = <b>"+curr+"</b><b>&nbsp;</b>":"")+
		(allow_lumpsum>0?"<!--/label--><br><input type=radio id=\"_rb"+nm+"0\" name=\"rb"+nm+"\" onclick=\"JSVCRateInputChg('"+nm+"')\" value=\"0\" "+(chk==0?" checked":"")+"><!--label for=\"_rb"+nm+"0\"--> "+JSVClang("Lump-Sum",7214)+" ("+curr+"): <input "+(req?"CHKREQUIRED ":"")+"name=\"sle"+nm+"\" value=\""+lumpsum+"\" maxlength=14 onblur=JSVCCurr(this)><!--/label-->"
			:"");
	return str;
}


// the checkboxes and exception links are disabled without this, this gives the "can see (grey) but can't touch" effect
// to remove the semi transparent div, just change the 100%'s to 0%'s or comment out the related lines
function JSVCPageDisable(oCapture,bActivate){
	var gen_cntrl;
	var disable_div = document.getElementById('JSVCdivfullpage');
	if(disable_div==null && bActivate==false)
		return;
	if(disable_div==null)
	{	disable_div=document.createElement("DIV");
		disable_div.className="clsSVCdisablelayer";
		disable_div.id="JSVCdivfullpage";
		disable_div.setAttribute("HIDDEN","1");
		document.body.appendChild(disable_div);
		gen_cntrl="1";
	} else
		gen_cntrl=disable_div.getAttribute("HIDDEN");
	if(bActivate){
//	if(disable_div.width == 0 || disable_div.width == 0+'px' || gen_cntrl == "1"){
		// Josh wrote: a trick to get real height and width of document
		// somehow setting dimensions in % does not work for opacity, so get height and set it back to pixel value
//		disable_div.style.width = '100%';
//		disable_div.style.height = '100%';
		disable_div.style.width= document.body.scrollWidth + 'px';
		disable_div.style.height = document.body.scrollHeight + 'px';
//		disable_div.setAttribute("HIDDEN","0");
		disable_div.setAttribute("CAPTUREOBJ",oCapture);
	}else{
		disable_div.style.width=0+'px';
		disable_div.style.height=0+'px';
//		disable_div.setAttribute("HIDDEN","1");
	}
}
function JSVCsymbol(name,deftext,locid) {
	var result=Trim(deftext);
	if(locid==null)
		locid=jSVClocid;
	if(jSVCsymbol==null)
		return result;
	var test=eval("jSVCsymbol."+name);
	if(test!=null && test!="")
		result=Trim(test);
	result=result.replace(/(\/\*|<!---){[\/]*LID[0-9]*}(\*\/|--->)/gi);
	return result;
}

//Kian Yee : Regex checking for other form variable type
function JSVCRegex(val, regex, minlen, maxlen)
{
	var str;
	if(typeof(val)=="object"){obj=val;val=val.value;}
	if (minlen==null) minlen=0;
	if (maxlen==null) maxlen=-1;
	if(typeof(regex=="string"))
		regex=new RegExp(regex);
	if (!regex.test(val)||val.length<minlen||(val.length>maxlen && maxlen!=-1))
		str="";
	else
		str=val;
	if(obj!=null){obj.value=str;DoReq(obj);}
	return str;
}

function JSVCAddSSL(str) {
	return str.replace(/^(http:\/\/)/i, "https://");
}

function JSVCRemSSL(str) {
	return str.replace(/^(https:\/\/)/i, "http://");
}
/* --------------------------
 JSVCrpt Class
-----------------------------*/
function JSVCrpt(varname,query,totLabel) {
	this.varname=varname; // varname
	this.query=query; // JSON
	this.grpBy=null;
	this.sumBy=null;
	this.totLabel=(totLabel==null?["Sub Total","Grand Total"]:totLabel);
	this.rowTitle=null;
}
JSVCrpt.prototype.gen=function(cols,retstr) {
	this.cols=cols;
	var htm="";
	if(this.query.DATA.length==0) {
		htm="<p align=center>- There is no record -</p>";
		if(retstr) return htm; else document.write(htm);
		return;
	}
	htm+="<table border=1 align=center cellpadding=1 cellspacing=0 style=width:100%;font-size:85%;>";
	for(var c in this.cols) {
		var col=this.cols[c];
		htm+=this.getCol(col,0);
	}
	if(this.rowTitle!=null) {
		htm+="<tr class=header><td colspan="+this.cols.length+">"+this.rowTitle.toUpperCase()+"</td></tr>"
	}

/* HTML rowspan example
<table width="100%" border="1">
  <tr>
    <td rowspan=2>January</td><td colspan=3>ttt</td><td rowspan=2>col3</td><td>col4</td>
  </tr>
  <tr>
    <td>test2</td><td>test3</td><td>test4</td><td>test5</td>
  </tr>
</table>
*/

	// Generate columns, currently support 2 rowspan
	var colcfg={rowsplit:1,cols:[]};
	var x=0;
	for(var c in this.cols) {
		var col=this.cols[c];
		var rx=new RegExp("^(.+?)//(.+?)$");
		var m=rx.exec(col[1],"gi");
		colcfg.cols[c]={};
		colcfg.cols[c].split=false;
		colcfg.cols[c].colspan=1;
		colcfg.cols[c].header=[];
		colcfg.cols[c].header[0]=col[1];
		if(m&&m.length>0) {
			colcfg.rowsplit=2;
			colcfg.cols[c].split=true;
			colcfg.cols[c].header[0]=m[1];
			colcfg.cols[c].header[1]=m[2];
			if(c>0&&(colcfg.cols[c].header[0]==colcfg.cols[c-1].header[0])) {
				colcfg.cols[x].colspan+=1;
				colcfg.cols[c].colspan=0;
			} else {
				x=c;
			}
		} else {
			colcfg.cols[c].colspan=0;
		}
	}
	if(colcfg.rowsplit>1) {
		for(var i=0;i<colcfg.rowsplit;i++) {
			htm+="<tr class=clsColumnHeader>";
			for(var c in this.cols) {
				var col=this.cols[c];
				if(i==0) {
					if(colcfg.cols[c].split==false)
						htm+="<td align=center rowspan="+colcfg.rowsplit+">"+colcfg.cols[c].header[i]+"&nbsp;</td>";
					else if(colcfg.cols[c].colspan>0)
						htm+="<td align=center colspan="+colcfg.cols[c].colspan+">"+colcfg.cols[c].header[i]+"&nbsp;</td>";
				}
				else if(i==1) {
					if(colcfg.cols[c].split==true)
						htm+="<td align=center>"+colcfg.cols[c].header[i]+"&nbsp;</td>";
				}
			}
			htm+="</tr>";
		}
	} else {
		htm+="<tr class=clsColumnHeader>";
		for(var c in this.cols) {
			var col=this.cols[c];
			htm+="<td align=center>"+col[1]+"&nbsp;</td>";
		}
		htm+="</tr>";
	}

	// Generate data rows
	var prev=null;
	var subtot=[],subcnt=[];
	var grdtot=[],grdcnt=[];
	for(var i=0;i<this.query.DATA.length;i++) {
		// generate group by separator
		if(this.grpBy!=null && (prev==null || this.getData(this.grpBy,i)!=prev)) {
			// show subtotal row
			if(this.sumBy!=null && prev!=null) {
				htm+=trSubTotal(this,subtot,subcnt,this.totLabel[0],1);
			}
			// show grouping row
			htm+="<tr class=clsColumnSubHeader><td colspan="+this.cols.length+" align=left style=font-size:110%>"+this.getData(this.grpBy,i)+"</td></tr>";
			prev=this.getData(this.grpBy,i);
		}
		htm+="<tr class=clsRptTone"+((i+1)%2==0?"2":"1")+">";
		for(var c in this.cols) {
			var col=this.cols[c];
			var value=this.getCol(col,1,i);
			htm+="<td>"+value+(value.toString().length==0?"&nbsp;":"")+"</td>";
			if(this.sumBy!=null && JSVCArrayIndexOf(this.sumBy,col[2])>=0 && (col[0]=="MONEY"||col[0]=="SMALLNO")) {
				if(subtot[c]==null) subtot[c]=0;
				if(subcnt[c]==null) subcnt[c]=0;
				if(grdtot[c]==null) grdtot[c]=0;
				if(grdcnt[c]==null) grdcnt[c]=0;
				var x=this.getData(col[2],i);
				if(x.toString()!="") {
					subtot[c]+=x;subcnt[c]+=1;
					grdtot[c]+=x;grdcnt[c]+=1;
				}
			}
		}
		htm+="</tr>";
	}
	// show subtotal row
	if(this.sumBy!=null && prev!=null) {
		htm+=trSubTotal(this,subtot,subcnt,this.totLabel[0],1);
	}
	// show grandtotal row
	htm+=trSubTotal(this,grdtot,grdcnt,this.totLabel[1],0);
	htm+="</table>";
	if(retstr) return htm; else document.write(htm);
	
	function trSubTotal(o,ar,cnt,title,separator) {
		var htm="";
		if(!ar.length>0)
			return htm;
		htm+="<tr class=clsRptTotal>"+tdSubTotal(o,ar,cnt,title)+"</tr>";
		if(separator==1)
			htm+="<tr><td colspan="+o.cols.length+">&nbsp;</td></tr>";
		for(var i in ar) // zerorize subtotal
			if(ar[i]!=null) ar[i]=0;
		for(var i in cnt) // zerorize subcount
			if(cnt[i]!=null) cnt[i]=0;
		return htm;
	}
	function tdSubTotal(o,ar,cnt,title) {
		var cs=0,i;
		var str="";
		for(i=0;i<ar.length && ar[i]==null;i++)
			cs+=1;
		if(cs>0)
			str+="<td colspan="+cs+" align=right>"+(title==null?"":title)+"&nbsp;</td>";
		for(;i<ar.length || i<o.cols.length;i++) {
			if(ar[i]==null)
				str+="<td>&nbsp;</td>";
			else {
				var x="";v=ar[i];
				var type=o.cols[i][0];
				var aggType=o.cols[i][3];
				var decplace=o.cols[i][4];
				if(aggType==1) // avg
					v=v/cnt[i];
				if(type=="MONEY")
					x=JSVCCurr(v);
				else if(type=="SMALLNO")
					x=JSVCNum(v,decplace);
				str+="<td>"+x+(x.toString().length==0?"&nbsp;":"")+"</td>";
			}
		}
		return str;
	}
}
JSVCrpt.prototype.getCol=function(col,type/*0:colClass,1:getValue*/,index) {
	if(col[0]=="REGNO") { // [0:type,1:label,2:queryCol,3:showLink,4:CaseIDcol]
		if(col[1]==null)
			col[1]="Reg. No.";
		if(type==0)
			return "<col class=clsSVCColRegNo>";
		else if(type==1) {
			if(col[3]==1)
				return "<a href=javascript:openClm("+this.getData(col[4],index)+")>"+this.getData(col[2],index)+"</a>";
			else
				return this.getData(col[2],index);
		}
	}
	else if(col[0]=="RFQNO") { // [0:type,1:label,2:queryCol,3:showLink,4:CaseIDcol,5:RfqIDCol]
		if(col[1]==null)
			col[1]="RFQ No.";
		if(type==0)
			return "<col class=clsSVCColRegNo>";
		else if(type==1) {
			if(col[3]==1)
				return "<a href=javascript:openRFQ("+this.getData(col[4],index)+","+this.getData(col[5],index)+")>"+this.getData(col[2],index)+"</a>";
			else
				return this.getData(col[2],index);
		}
	}
	else if(col[0]=="LINK") { // [0:type,1:label,2:queryCol,3:url,4:itemLabel]
		if(col[1]==null)
			col[1]="";
		if(type==0)
			return "<col class=clsSVCColID>";
		else if(type==1) {
			if(col[3]!=null) {
				var url=col[3];
				var rx=new RegExp("\{([^\}]+)\}","i"); // translate params i.e. {CASEID}
				var m=rx.exec(url)
				while(m!=null) {
					url=url.replace(m[0],this.getData(m[1],index));
					m=rx.exec(url);
				}
				return "<a href=\""+url+"\")>"+(col[4]!=null?col[4]:this.getData(col[2],index))+"</a>";
			}
			else
				return this.getData(col[2],index);
		}
	}
	else if(col[0]=="SMALLNO") { // [0:type,1:label,2:queryCol,3:aggregateBy(0=sum,1=avg),4:DecimalPlace,5:FormatFunc]
		if(type==0)
			return "<col class=clsSVCColSmallNo>";
		else if(type==1) {
			var x;
			x=calcFormula(this,col[2],index);
			x=JSVCNum(x,col[4]);
			if(typeof(col[5])=="function")
				x=col[5](x,index);
			return x;
		}
	}
	else if(col[0]=="TEXT") { // [0:type,1:label,2:queryCol]
		if(type==0)
			return "<col class=clsSVCColText>";
		else if(type==1) {
			var value=this.getData(col[2],index);
			if(value==null) value="";
			value=value.toString().replace(/\r/g,"<br>").replace(/\n/g,"");
			return value;
		}
	}
	else if(col[0]=="SMALLTEXT") { // [0:type,1:label,2:queryCol]
		if(type==0)
			return "<col class=clsSVCColName>";
		else if(type==1)
			return this.getData(col[2],index);
	}
	else if(col[0]=="DATE") { // [0:type,1:label,2:queryCol]
		if(type==0)
			return "<col class=clsSVCColDate>";
		else if(type==1) {
			return JSVCdtDBtoLOC(this.getData(col[2],index));
		}
	}
	else if(col[0]=="DATETIME") { // [0:type,1:label,2:queryCol,3:timeFormat]
		if(type==0)
			return "<col class=clsSVCColDate>";
		else if(type==1) {
			var tmformat="HH:mm:ss";
			if(col[3]!=null && col[3]!="STD")
				tmformat=col[3];
			return JSVCdtDBtoLOC(this.getData(col[2],index),null,null,tmformat);
		}
	}
	else if(col[0]=="MONEY") { // [0:type,1:label,2:queryCol,3:aggregateBy(0=sum,1=avg),4:DecimalPlace]
		if(type==0)
			return "<col class=clsSVCColMoney>";
		else if(type==1) {
			var x;
			x=calcFormula(this,col[2],index);
			return JSVCCurr(x,9999999999,-9999999999);
		}
	}
	else if(col[0]=="CNT") { // [0:type,1:label]
		if(type==0)
			return "<col class=clsSVCColNo>";
		else if(type==1)
			return (index+1);
	}
	else if(col[0]=="NO") { // [0:type,1:label,2:queryCol]
		if(type==0)
			return "<col class=clsSVCColNo>";
		else if(type==1) {
			return this.getData(col[2],index);
		}
	}
	return "";
	
	function calcFormula(o,q,index) {
		var x,s=q,rx=new RegExp("\{([a-z0-9\_]+)\}","gi"); // finding queryCol like {RTOT1}-{RTOT2}
		var m=rx.exec(q);
		if(m!=null) {
			while(m!=null) {
				var val=o.getData(m[1],index);
				if(val=="") val=0;
				s=s.replace(m[0],val);
				m=rx.exec(q);
			}
			x=eval(s);
		} else
			x=o.getData(q,index);
		return x;
	}
}
JSVCrpt.prototype.getData=function(colname,index) {
	var value=JSVCqueryGetValue(this.query,colname,index);
	if(value==null) value="";
	return value;
}
JSVCrpt.prototype.groupBy=function(param) {
	this.grpBy=param;
}
JSVCrpt.prototype.aggBy=function(param) {
	var ar=param.split(",");
	this.sumBy=ar;
}
JSVCrpt.prototype.genFootNote=function(list) {
	if(list==null || list=="")
		return;
	var htm="";
	htm+="<br><table border=0 align=center cellpadding=1 cellspacing=0 style=width:100%>";
	for(var i in list) {
		htm+="<tr class=clsRptNote><td>NOTE"+(parseInt(i)+1)+":"+list[i]+"</td></tr>";
	}
	htm+="</table>";
	document.write(htm);
}
JSVCrpt.prototype.setRowTitle=function(title) {
	this.rowTitle=title;
}
function JSVCstrEndWith(str,endwithstr)
{	var len;
	if(str==null)str="";
	len=str.length;
	if(endwithstr.length>len||endwithstr.strlength==0)return false;
	if(str.substring(len-endwithstr.length,len).toUpperCase()==endwithstr.toUpperCase())return true;
	return false;
}
function JSVClang(TEXT,LID,LGID) {
	if(LID==null)
		LID=0;
	if(LGID==null)
		LGID=0;

	if(arguments.length==1)
		return TEXT;

	if(LID>0) {
		if(LGID==0) {
			if(request.lgid>=0)
				LGID=request.lgid;
			else if(jSVClgid>=0)
				LGID=jSVClgid;
		}
		if(LGID>0) {
			if(request.DS.LANG[LGID]!=null && request.DS.LANG[LGID][LID]!=null)
				TEXT=request.DS.LANG[LGID][LID];
		}
	}

	if(arguments.length>3) {
		for(var P=3;P<arguments.length;P++)
			TEXT=TEXT.replace(new RegExp(RegExp.escape("{"+(P-3)+"}"),"gi"),arguments[P]);
	}
	return TEXT;
}
function JVSClangCode(lcode) {
	if(!(typeof(lcode)=="string" && request && request.DS && request.DS.LANGDEF))
		return;
	var a=request.DS.LANGDEF;
	for(var i=0;a[i]!=null;i++) {
		if(a[i].LCODE.toLowerCase()==lcode.toLowerCase())
			return a[i]; // .LCODE/.DESC/.LANGID
	}
	return;
}
RegExp.escape=function(str)
{
  var specials=new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
  return str.replace(specials, "\\$&");
}
function JSVCopenWinPost(url,winname,postdata/*array*/) {
	var frm=document.createElement("form");
	frm.setAttribute("method","post");
	frm.setAttribute("action",url);
	frm.setAttribute("target",winname);
	for(var i in postdata) {
		var f=document.createElement("input");
		f.setAttribute("type","hidden");
		f.setAttribute("name",postdata[i][0]);
		f.setAttribute("value",postdata[i][1]);
		frm.appendChild(f);
	}
	document.body.appendChild(frm);
	frm.submit();
}
/* ======= JSVCgenMultiRows =================
varname - name of this JS variable
parentid - container's object ID
formname - name of the input element
valuelist - value list
valuelistsep - value list delimiter
disptype - 0:textbox,1:dropdown,2:date with datepicker
============================================= */
function JSVCgenMultiRows(varname,parentid,formname,valuelist,valuelistsep,onblur,capcontent,chkrequired,maxrows,disptype,optvaluelist,optvaluelistsep) {
	this.varname=varname;
	this.parentid=parentid;
	this.formname=formname;
	this.valuelist=valuelist.split(valuelistsep);
	this.onblur=onblur;
	this.capcontent=capcontent;
	this.chkrequired=chkrequired;
	this.maxrows=(maxrows>0?maxrows:10); // default 10 rows max
	this.currow=1;
	this.disptype=disptype;
	this.optvaluelist=optvaluelist;
	this.optvaluelistsep=optvaluelistsep;	
}
JSVCgenMultiRows.prototype.gen=function(returnstr) {
	var htm="";
	htm+=this.elemT(this.formname,(this.valuelist!=null?this.valuelist[0]:""));
	htm+="&nbsp;<input type=button class=clsSVCbutton value=' + ' onclick="+this.varname+".addRow() style=margin-bottom:2px>";
	if(this.valuelist!=null)
		for(var i=1;i<this.valuelist.length&&i<this.maxrows;i++) {
			htm+="<br>"+this.elemT(this.formname,this.valuelist[i]);
			this.currow+=1;
		}
	if(returnstr)
		return htm;
	else
		document.write(htm);
}
JSVCgenMultiRows.prototype.addRow=function() {
	var o=JSVCall(this.parentid);
	if(this.currow<this.maxrows) {
		o.innerHTML+="<br>"+this.elemT(this.formname,"");
		//DoReq(o.lastChild);
		MRMPreprocessFormItem(o.lastChild);
		this.currow+=1;
	}
}
JSVCgenMultiRows.prototype.clear=function() {
	var o=JSVCall(this.parentid);
	this.currow=1;
	this.valuelist=null;
	o.innerHTML=this.gen(true);
}
JSVCgenMultiRows.prototype.elemT=function(name,value) {
	if(this.disptype==1) {
		var str="<select"+(this.chkrequired?" CHKREQUIRED":"")+" name="+name+" id="+name+"_"+this.currow+" onblur=DoReq(this);"+this.onblur+" style=margin-top:2px;margin-bottom:1px>";
		str+=JSVCgenOptions(this.optvaluelist,this.optvaluelistsep,value);
		str+="</select>";
		return str;
	}
	else if (this.disptype==2) {
		/*
		<input MRMOBJ=CALDATE DTMAX="TODAY" name="sleFINALREMINDERDATE" VALUE="#FN.SVCdtdbtoloc(dtCLMFINALREMINDER)#" onblur="ObjDate(this)">
		*/
		
		return "<input TESTINGROWRRRRR MRMOBJ=CALDATE name="+name+" value=\""+value+"\" onblur=ObjDate(this);"+this.onblur+">";
	}
	else
		return "<input"+(this.chkrequired?" CHKREQUIRED":"")+" name="+name+" maxlength=100 size=40 value=\""+value+"\" onblur=DoReq(this);"+this.onblur+" onchange="+(this.capcontent?"javascript:this.value=this.value.toString().toUpperCase(); style='text-transform:uppercase'":"")+">";
}
/* ======= JSVCrecordBrowser =================
varname	- name of this JS variable
parentid - container's object ID
xmlurl - URL request which returns XML data rows
============================================= */
function JSVCrecordBrowser(varname,parentid,xmlfeedurl,title,locid,filter,sort) {
	this.varname=varname;
	this.parentid=JSVCall(parentid);
	this.xmlfeedurl=xmlfeedurl;
	this.title=(title==null?"":title);
	this.rcwin=this.varname+"_rcwin";
	this.ctlwin=this.varname+"_ctlwin";
	this.locid=locid;
	this.locale=request.DS.LOCALES[locid];
	this.filter=filter;
	this.sort=sort;
	this.page=1;
	this.pagemax=1;
	this.recordpage=20;
	this.recordcount=0;
}
JSVCrecordBrowser.prototype.gen=function() {
	var htm="";
	htm+="<div style=width:100% align=center>";
	if(this.title!="")
		htm+="<div class=header style=padding:2px;text-align:left>"+this.title.toUpperCase()+"</div>";
	htm+="<div id="+this.ctlwin+" align=center>";
	htm+="<table cellspacing=0 cellpadding=1 width=100%>";
	htm+="<tr>";
	if(this.filter==1)
		htm+="<td><b>Keyword:</b>&nbsp;<input id="+this.varname+"_filter type=text size=25 maxlength=25 value='' onkeydown=\"if(event.keyCode==13&&Trim(this.value)!=''){"+this.varname+".submit()}\">&nbsp;<input type=button value='Go' class=clsSVCButton onclick=\"var o=JSVCall('"+this.varname+"_filter');if(Trim(o.value)!=''){"+this.varname+".submit()}\">&nbsp;<input type=button value='Clear' class=clsSVCButton onclick=\"var o=JSVCall('"+this.varname+"_filter');o.value='';"+this.varname+".submit()\"></td>";
	if(this.sort!=null) {
		htm+="<td align=right><b>Sort&nbsp;By:</b>&nbsp;<select id="+this.varname+"_sort>"+JSVCgenOptions(this.sort)+"</select></td>";
	}
	htm+="<td align=right><input type=button class=clsSVCButton value='|<' onclick="+this.varname+".navig(1)>&nbsp;<input type=button class=clsSVCButton value='<<' onclick="+this.varname+".navig(2)>&nbsp;<span id="+this.varname+"_page style=font-weight:bold></span>&nbsp;<input type=button class=clsSVCButton value='>>' onclick="+this.varname+".navig(3)>&nbsp;<input type=button class=clsSVCButton value='>|' onclick="+this.varname+".navig(4)></td>";
	htm+="</tr>";
	htm+="</table>";
	htm+="</div>";
	htm+="<div id="+this.rcwin+" align=center></div>";
	htm+="</div>";
	this.parentid.innerHTML=htm;
	this.submit();
}
JSVCrecordBrowser.prototype.submit=function(page,filter,sort,recordpage) {
	var url=this.xmlfeedurl,o;

	if(page==null) // page
		page=this.page;
	url=JSVCremoveURL(url,"p");
	url+="&p="+page;

	if(filter==null) { // filter
		o=JSVCall(this.varname+"_filter");
		if(o!=null) {
			filter=Trim(o.value);
			if(filter.length>0 && filter.length<3) {
				alert("Please specify at least 3 characters.")
				o.select();
				return;
			}
		}
	}
	url=JSVCremoveURL(url,"f");
	if(filter!=null && filter.length>=3) url+="&f="+filter;

	if(sort==null) { // sort by
		o=JSVCall(this.varname+"_sort");
		if(o!=null)
			sort=o.value;
	}
	url=JSVCremoveURL(url,"s");
	if(sort>=0) url+="&s="+sort;

	if(recordpage==null) { // records per page
		recordpage=this.recordpage;
	}
	url=JSVCremoveURL(url,"r");
	if(recordpage>0) url+="&r="+recordpage;

	var rcwin=JSVCall(this.rcwin),ctlwin=JSVCall(this.ctlwin);
	rcwin.innerHTML="<div style=width:90%;background-color:whitesmoke;border:2px solid brown><br><b>"+JSVClang("Loading, please wait...",7062)+"</b>&nbsp;<img style=vertical-align:middle src=\""+request.approot+"services/images/loading-anim.gif\"><br><br></div>";
	ctlwin.disabled=true;
	MRMHTTPRequest("POST",url,null,this.load,null,null,null,null,this);
}
JSVCrecordBrowser.prototype.navig=function(mode) {
	var p=this.page,pm=this.pagemax;
	if(mode==1) // first page
		p=1;
	else if(mode==2 && p>1) // previous page
		p--;
	else if(mode==3 && p<pm) // next page
		p++;
	else if(mode==4 && p<pm) // last page
		p=pm;
	if(this.page!=p) {
		this.page=p;
		this.submit(this.page);
	}
}
JSVCrecordBrowser.prototype.resetPage=function(recordcount,recordpage) {
	this.recordcount=recordcount;
	if(recordpage!=null)
		this.recordpage=recordpage;
	this.page=(this.recordcount==0?0:1);
	this.pagemax=Math.ceil(this.recordcount/this.recordpage);
	if(isNaN(this.pagemax))
		this.pagemax=1;
}
JSVCrecordBrowser.prototype.load=function(o,p/*JSVCrecordBrowser object*/) {
	var xml=o.responseXML;
	var rcwin=JSVCall(p.rcwin),ctlwin=JSVCall(p.ctlwin);
	var lst;
	lst=xml.selectSingleNode("dataset/summary/recordcount");
	if(lst==null) {
		rcwin.innerHTML="Error 1";return;
	}
	var t=Number(lst.text);
	if(t!=p.recordcount)
		p.resetPage(t);
	var pgobj=JSVCall(p.varname+"_page");
	pgobj.innerHTML=p.page+"/"+p.pagemax;
	// generating records
	lst=xml.selectNodes("dataset/summary/columns");
	if(lst==null) {
		rcwin.innerHTML="Error 2";return;
	}
	lst=lst[0].childNodes;
	// Reusing JSVCrpt
	var coldef=[],query={"COLUMNS":[],"DATA":[]},colnm=[],rows=[];
	for(var i=0;i<lst.length;i++) {
		if(lst[i].getAttribute("SHOW")!=0) {
			var x=coldef.length;
			var type=lst[i].getAttribute("COLTYPE"),label=lst[i].getAttribute("COLNAME"),queryCol=lst[i].nodeName;
			coldef[x]=[type,label,queryCol];
			if(type=="LINK") {
				var url=lst[i].getAttribute("HREF");
				coldef[x][3]=url;
			}
		}
		colnm[colnm.length]=lst[i].nodeName;
	}
	lst=xml.selectNodes("dataset/D");
	if(lst==null) {
		rcwin.innerHTML="Error 3";return;
	}
	for(var i=0;i<lst.length;i++) {
		var row=[];
		for(var j=0;j<colnm.length;j++) {
			var value=lst[i].getAttribute(colnm[j]);
			row[row.length]=(value!=null?value:null);
		}
		rows[rows.length]=row;
	}
	query.COLUMNS=colnm;
	query.DATA=rows;
	var rpt=new JSVCrpt(p.varname+"_rpt",query);
	JSVCSetLocale(p.locid,null,p.locale.DTFORMAT,p.locale.TMFORMAT,p.locale.TIMEZONE);
	rcwin.innerHTML=rpt.gen(coldef,true);
	ctlwin.disabled=false;
}
function JSVCpopup(varname,formname,ctxname) {
	this.varname=varname;
	this.formname=formname;
	this.formobj=JSVCall(formname);
	this.ctxname=ctxname;
	this.ctxframe=JSVCall(this.ctxname);
	this.msgheader=this.ctxname+"_msg"; // message container
	// Properties
	this.title="Popup"; // title of the popup window
	this.width=300;
	this.msg=null;
	this.fnOK=null;
	this.fnCancel=null;
	this.exfields=null; // array: [["title","html"],...]
	this.btnFlag=3; // 1:OK,2:Cancel
}
JSVCpopup.prototype.gen=function() {
	if(this.ctxframe==null)
		this.ctxframe=JSVCCtxMenuFrame(this.formobj,this.ctxname,this.title,this.width,false,false);
	var html="<table cellpadding=3 cellspacing=0 border=0 width=100%>"+
	"<tr><td colspan=2"+((this.btnFlag&3)==1?" align=center":"")+"><span id="+this.msgheader+">"+(this.msg?this.msg:"")+"</span></td></tr>";
	if(this.exfields) {
		for(var i in this.exfields) {
			var f=this.exfields[i];
			html+="<tr>"+(f[0]?"<td width=25%><b>"+f[0]+"</b></td><td":"<td colspan=2")+" id="+this.ctxname+"_itm"+i+" valign=top>"+f[1]+"</td></tr>";
		}
	}
	if((this.btnFlag&3)==1)
		html+="<tr><td colspan=2 align=center><input type=button class=clsSVCButton value='  OK  ' onclick=\"JSVCcloseCtxMenu('"+this.ctxname+"')\"></td></tr>"
	else
		html+="<tr><td colspan=2 align=right><input type=button class=clsSVCButton value='  OK  ' onclick='"+(this.fnOK?this.fnOK+"();":"")+"'>&nbsp;&nbsp;&nbsp;<input type=button class=clsSVCButton value='Cancel' onclick="+(this.fnCancel?this.fnCancel+"();":"")+"JSVCcloseCtxMenu('"+this.ctxname+"')></td></tr>"
	html+="</table>";
	JSVCCtxMenuContent(this.ctxframe,html);
	for(var i in this.exfields) {
		MRMPreprocessFormItem(JSVCall(this.ctxname+"_itm"+i).firstChild);
	}
	DoReq(this.formobj);
}
JSVCpopup.prototype.show=function(event) {
	JSVCshowCtxMenuEv(event,this.ctxframe,null,2,2);
}
JSVCpopup.prototype.hide=function(event) {
	JSVCcloseCtxMenu(this.ctxname);
}
JSVCpopup.prototype.showChk=function(event,fnChk) {
	if(fnChk(this)==true)
		this.show(event);
	else
		JSVCcloseCtxMenu(this.ctxname);
}
JSVCpopup.prototype.setMsg=function(msg) {
	var o=JSVCall(this.msgheader);
	o.innerHTML=msg;
}
function JSVCSgVRegChk(str)
{
	if(typeof(str)!="string" && str.value!=null)
		str=str.value;
	
	str=Trim(str).toUpperCase();
	
	var r=/^([A-Z]{0,3})([0-9]{1,4})([A-Z0-9]{0,2})$/; // 3 groups
	var m=r.exec(str);
	
	if(m==null || m.length<3) // no matches or no capturing group 1 & 2
		return JSVClang("is invalid",7646);
	if(m[1]=="MID" && m[3]!="" && /^\d+$/.test(m[3]))
		return "";
	else if(m[1]=="S")
		return "";
	else if(/\d+/.test(m[3]))
		return JSVClang("is invalid",7646);
	if(m[1].length>0 && m[3]=="CD")
		return "";
	if(m[1].length==0 && /^\d{4}$/.test(m[2]) && m[3]=="S")
		return "";
		
	if(m[1].length==1)
		m[1]=" S"+m[1];
	else if(m[1].length==2)
		m[1]=" "+m[1];
	
	m[2]=m[2].toString().padLeft("0",4);
	
	if(m[3].length==2 && !(m[3]=="CD" && m[3]=="CC"))
		return JSVClang("is invalid",7646);

	// calculate checksum
	var c=(9*(m[1].charCodeAt(1)-65)+4*(m[1].charCodeAt(2)-65)+5*m[2].charAt(0)+4*m[2].charAt(1)+3*m[2].charAt(2)+2*m[2].charAt(3)+(m[1]=="CSS"?20:12))%19;
	var v=["A","B","C","D","E","G","H","J","K","L","M","P","R","S","T","U","X","Y","Z"];

	if(c>=0 && c<=18 && v[18-c]==m[3]) // 0 to 18 == Z to A (reversed)
		return "";
	else
		return JSVClang("is invalid",7646);

	return JSVClang("is invalid",7646);
}

function JSVCDOBtoAge(o,tgtid){ // o=source object, tgtid=target obj id
	var tgtobj=document.getElementById(tgtid);
	var tmpage="",i=0,age="";
	var thisyear=new Date().getFullYear();
	if (tgtobj!=null && o!=null && o.value!="") {
		i=jSVCdtformat.indexOf("yyyy");
		if (i>-1) {
			age=thisyear-parseInt(o.value.substring(i,i+4));
			if (tgtobj.value || tgtobj.tagName.toUpperCase()=='INPUT') tgtobj.value=age;
			else if (tgtobj.innerHTML) tgtobj.innerHTML = age;
		} 
	}
}

/* ======= JSVCSplitCols =================
Rearrange table columns to the number of columns specified
tableid - id of table to split
tbodyid - tbody id to split, null to split entire table
oric - original column length (default=2)
fnlc - new column length (default=4)
type - Arrangement type ... 1: vertical, 2: horizontal (default=1)
adjwidth - Adjust the column width specified in <col> ... 1:yes, 2:no (default=1)
============================================= */
function JSVCSplitCols(tableid, tbodyid, oric, fnlc, type, adjwidth){
	var c,clone,collen,reg,cwarr;
	var trowsobj,start,end;
	
	if (type==null) type=1;
	if (oric==null) oric=2;
	if (fnlc==null) fnlc=4; 
	if (oric>=fnlc || fnlc%oric!=0) return;
	if (adjwidth==null) adjwidth=1;
	if (tbodyid!=null)tbodyobj=document.getElementById(tbodyid);
	else tbodyobj=document.getElementById(tableid);
	if (tbodyobj==null) return;

	trowsobj = tbodyobj.rows;

 	colobj=tbodyobj.getElementsByTagName("col");
	if (colobj.length) collen=oric; else collen=0;

	for (c = 0;adjwidth==1&&c<collen; c++) { // colwidth
		var cw = colobj[c].style.width;
		if (cw) {
			reg = /(\d+) *([a-zA-Z%]+)/;
			cwarr = cw.match(reg);
			if (cwarr != null) {
				newwidth = Math.floor(parseInt(cwarr[1])/(fnlc/oric));
				newwidth = newwidth + cwarr[2];
				colobj[c].style.width = newwidth;
			}
		}
	}
	for(c=0;c<collen;c++){
		for(c1=0;c1<(fnlc/oric)-1;c1++) {
			clone = colobj[collen-1].cloneNode(true);
			colobj[0].parentNode.insertBefore(clone,colobj[0]);
		}
	}
	if (type == 1) {
		start=0;end=-1;
		for (var h = 0; h < tbodyobj.rows.length; h++) {
			for (var k = 0; k < trowsobj[h].cells.length; k++) { 
				if (SplitColsHeader(trowsobj[h].cells[k],oric,fnlc)) {
					if(h==0) start=0+1; 
					else end=h;
					break;
				}
				else if (end==-1 && h==tbodyobj.rows.length-1)
					end=tbodyobj.rows.length;
			}
			if (end != -1) {
				rowlen = (end - start);
				cellcount = oric * (end - start);
				totcol = fnlc;
				totrow = Math.ceil(cellcount / fnlc);
				chkcol = totcol - ((totrow * totcol) - cellcount);
				count=0;
				for (var i = oric; i < fnlc ; i=i+oric)
				{
					currowlen = (totrow - (i < chkcol ? 0 : 1));
					for (var j = start; j < start+currowlen; j++) {
						var tmprobj = trowsobj[totrow + j];
						for (var k = 0; k < tmprobj.cells.length; k++) { // col
							var x = tmprobj.cells[k].cloneNode(true);
							var xsel = tmprobj.cells[k].getElementsByTagName("SELECT");/* MS bug 829907 */
							if (xsel.length != 0) x.getElementsByTagName("SELECT")[0].options.selectedIndex = xsel[0].options.selectedIndex;
							trowsobj[j].appendChild(x);
						}
					}
					for (var j = start; j < start+currowlen; j++) {
						tbodyobj.rows[0].parentNode.removeChild(tbodyobj.rows[totrow + start]);
						count+=1;
					}
				}
				if (currowlen < totrow && start+totrow-1 != 0) {
					SplitColsAppendEmp(trowsobj[start+totrow-1], totcol);
				}
				start = end-count+1;
				h = start-1;
				rowlen = tbodyobj.rows.length;
				end = -1;
			} 
		}
	}
	if (type == 2) {
		var headerflag = 0;
		var move = (fnlc - oric) / oric;
		for (var i = 0; i <  tbodyobj.rows.length; i++) 
		{
			for (var h = 0; h < oric; h++) {
				headerflag = SplitColsHeader(trowsobj[i].cells[h],oric,fnlc);
				if (headerflag == 1) break;
			}
			for (var j = 1; headerflag == 0 && j <= move; j++) {
				var tmprobj = trowsobj[i + 1]; // row
				if (tmprobj) {
					for (var k = 0; k < tmprobj.cells.length; k++) { // col
						headerflag = SplitColsHeader(tmprobj.cells[k],oric,fnlc);
						if (headerflag == 1) {
							SplitColsAppendEmp(trowsobj[i], fnlc);
							break;
						}
						var x = tmprobj.cells[k].cloneNode(true);
						var xsel = tmprobj.cells[k].getElementsByTagName("SELECT");/* MS bug 829907 */
						if (xsel.length != 0) x.getElementsByTagName("SELECT")[0].options.selectedIndex = xsel[0].options.selectedIndex;
						trowsobj[i].appendChild(x);
					}
					if (headerflag == 0) tbodyobj.rows[i].parentNode.removeChild(tbodyobj.rows[i + 1]);
				}
				else {
					SplitColsAppendEmp(trowsobj[i], fnlc);
				}
			}
		}
	}
}
function SplitColsAppendEmp(rowobj,total) { 
	for (var k = rowobj.cells.length; k < total; k++) {
		var newtd = document.createElement("td");
		newtd.innerHTML = '&nbsp;';
		rowobj.appendChild(newtd);
	}
}
function SplitColsHeader(cell,oric,fnlc) {
	if (cell && / *header */.test(cell.className) || / *splithdr */.test(cell.className) || (oric > 1 && cell.colSpan == oric)) {
		cell.colSpan = fnlc;
		return 1;
	}
	return 0;
}
//Hide Rows with plus minus image
function JSVCShowHideRow(divname,imgname,byname){
	if (byname == null) byname = 1;	
	var detdiv = (byname==1?document.getElementsByName(divname):document.getElementById(divname));	
	
	if (byname == 1) {
		if (detdiv[0].style.display == "none") {
			for (i = 0; i < detdiv.length; i++) {
				detdiv[i].style.display = "";
			}
			document.images[imgname].src = request.approot + "services/images/minus.gif";
		}
		else {
			for (i = 0; i < detdiv.length; i++) {
				detdiv[i].style.display = "none";
			}
			document.images[imgname].src = request.approot + "services/images/plus.gif";
		}
	} else {
		if (detdiv.style.display == "none") {
			detdiv.style.display = "";
			document.images[imgname].src = request.approot + "services/images/minus.gif";
		}
		else {
			detdiv.style.display = "none";
			document.images[imgname].src = request.approot + "services/images/plus.gif";
		}		
	}
}

//Return bit from checkbox
function JSVCChkToBit(chkboxname)
{
		var slcitms = document.getElementsByName(chkboxname);
		var prevalue = 0;
		for (var i=0;i < slcitms.length;i++)
		{
			if(slcitms[i].checked==true)
			{
				prevalue += parseInt(slcitms[i].value);
			}
		}
		return prevalue;

}

// http://dean.edwards.name/weblog/2005/10/add-event/
function JSVCaddEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = JSVCaddEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
JSVCaddEvent.guid = 1;

function JSVCremoveEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};
function JSVCNameIDObject(objname,nmStr)
{
	var IDDefConfig={
		DefCountryID:1,
		OvrIDStr:"",
		CtryShortlist:"",
//		OvrIDStr:"1!Co Reg No|*2!NRIC~FN:JSVCIDChkMyIC(obj)|*3!Passport No|+4!Old IC|+5!Birth Cert No|*6!Army/Police ID",
//		CtryShortlist:"7,1,2,3,11",
		NameType:2, /* 1: Individual only, 2: Individual & Company */
		NationalityChangeID2:1, /* 1: Nationality change will update ID2 */
		NationalityDefaultCountryID:1, /* If nationality is blank use default country ID */
		Label_Postfix:"",
		Label_Individual:JSVClang("Individual",6031),
		Label_Company:JSVClang("Company",2033),
		Label_Name:JSVClang("Name",1173),
		Label_ID1:JSVClang("ID",2122),
		Label_ID2:JSVClang("Second ID",6030),
		Label_Nationality:JSVClang("Nationality",1178)
	}
	this.objname=objname;
	this.nmStr=nmStr;
	this.config=IDDefConfig;
}
JSVCNameIDObject.prototype.genName=function(nmval,id1type,chkrequired,disabled,spcnm,nmselchgExec,appendHTML) 
{
	var fnlstr,str,nmsel,spclist;
	if(nmselchgExec==null)nmselchgExec="";
	fnlstr="<tr><td valign=baseline>"+this.config.Label_Name+(this.config.Label_Postfix!=""?" "+this.config.Label_Postfix:"")+"</td><td>";
	this.isCom=0;
	if(this.config.NameType==2)
	{
		// determine if idtype is company or individual
		if(id1type!=null)
		{
			try{
				if(IDtypes[id1type].IdType==1)
					this.isCom=1
				else
					this.isCom=0;
			} catch (e) {}
		}	
		fnlstr+="<input URLVAR ID=\"_"+this.nmStr+"nmselIND\" name=\""+this.nmStr+"nmsel\" CHKREQUIRED "+(this.isCom==0?"CHECKED ":"")+"type=radio "+(disabled==1?"DISABLED PDISABLED ":"")+" value=2 onclick=\""+this.objname+".refresh(event);"+nmselchgExec+"\"><label for=\"_"+this.nmStr+"nmselIND\"> "+this.config.Label_Individual+"</label> ";
		fnlstr+="<input URLVAR ID=\"_"+this.nmStr+"nmselCOM\" name=\""+this.nmStr+"nmsel\" CHKREQUIRED "+(this.isCom==1?"CHECKED ":"")+" type=radio "+(disabled==1?" DISABLED PDISABLED ":"")+" value=1 onclick=\""+this.objname+".refresh(event);"+nmselchgExec+"\"><label for=\"_"+this.nmStr+"nmselCOM\"> "+this.config.Label_Company+"</label> ";
		if(spcnm!=null && typeof(spcnm)=="string" && spcnm.length>0)
		{	spclist=spcnm.split("|");
			fnlstr+="<input URLVAR ID=\"_"+this.nmStr+"nmselSPC\" SPCNM=\""+spcnm+"\" name=\""+this.nmStr+"nmsel\" value=\""+spclist[0]+"\" CHKREQUIRED "+(nmsel==spclist[0]?"CHECKED ":"")+(disabled==1?"DISABLED PDISABLED ":"")+" type=radio onclick=\""+this.objname+".refresh(event);"+nmselchgExec+"\"><label for=\"_"+this.nmStr+"nmselSPC\"> "+spclist[1]+"</label>";
		}
		fnlstr+="<br>";
	}
	fnlstr+="<input URLVAR "+(chkrequired=="1"?"CHKREQUIRED ":(chkrequired!=''?"CHKREQUIRED=\""+chkrequired+"\" ":""))+" name=\""+this.nmStr+"nm\" id=\"_"+this.nmStr+"nm\" maxlength=100 size=50 VALUE=\""+nmval+"\" "+(disabled==1?"DISABLED PDISABLED ":"")+" onblur=DoReq(this)>";
	if(this.config.NameType!=2)
		fnlstr+="<br><input type=radio style=visibility:hidden>";	
	if(appendHTML!=null && appendHTML!="")
		fnlstr+="<br>"+appendHTML;
	fnlstr+="</td></tr>";
	return fnlstr;
}
JSVCNameIDObject.prototype.genID1=function(id1,id1type,chkrequired,disabled)
{	var comStr,fnlstr,optStr,idchk,listStr;	
	this.id1disabled=disabled;
	fnlstr="<tr><td valign=baseline>"+this.config.Label_ID1+(this.config.Label_Postfix!=""?" "+this.config.Label_Postfix:"")+"</td><td>";
	comStr=((this.isCom==1)?"C":"I");
	idchk=null;
	this.ID1ListStr=comStr+":*"+this.config.DefCountryID;
 	optStr=this.genOptionList(this.ID1ListStr,null,id1type);
 	if(optStr=="")
 		disabled=1;

	fnlstr+="<select URLVAR id=\"_"+this.nmStr+"id1sel\" name=\""+this.nmStr+"id1sel\"  "+(disabled==1?"DISABLED PDISABLED":"")+" style='width=160px' onchange=\""+this.objname+".checkIDFormat(this.nextSibling.nextSibling,this)\">";
	fnlstr+=optStr;
	fnlstr+="</select> ";
	fnlstr+="<input URLVAR "+(disabled==1?"DISABLED PDISABLED style='background-color:silver'":"")+"  "+(chkrequired=="1"?"CHKREQUIRED ":(chkrequired!=''?"CHKREQUIRED=\""+chkrequired+"\" ":""))+" id=\"_"+this.nmStr+"id1\" name=\""+this.nmStr+"id1\"  maxlength=20 size=20  VALUE=\""+id1+"\"  "+(idchk!=null? "CHKFORMAT="+idchk+"":"" )+"  onblur=\""+this.objname+".checkIDFormat(this,this.previousSibling.previousSibling);\">";
	fnlstr+="</td></tr>";
	return fnlstr;
}
JSVCNameIDObject.prototype.genID2=function(id2,id2type,nationalityID,chkrequired,disabled)
{	var comStr,fnlstr,optStr,idchk;
	this.id2disabled=disabled;
	fnlstr="<tr><td valign=baseline>"+this.config.Label_ID2+(this.config.Label_Postfix!=""?" "+this.config.Label_Postfix:"")+"</td><td>";	
	idchk=null;
	comStr=(this.isCom==1?"C":"I");
	if(nationalityID!=null && nationalityID!="" && nationalityID!=this.config.DefCountryID)
		this.ID2ListStr=comStr+":*"+nationalityID+","+this.config.DefCountryID
	else
		this.ID2ListStr=comStr+":"+this.config.DefCountryID;
	optStr=this.genOptionList(this.ID2ListStr,null,id2type);
 	if(optStr=="")
 		disabled=1;
	
	fnlstr+="<select URLVAR  name=\""+this.nmStr+"id2sel\" id=\"_"+this.nmStr+"id2sel\"  "+(disabled==1?"DISABLED PDISABLED":"")+" style='width=160px' onchange=\""+this.objname+".checkIDFormat(this.nextSibling.nextSibling,this);\">";	
	fnlstr+=optStr;
	fnlstr+="</select> ";
	fnlstr+="<input URLVAR "+(disabled==1?"DISABLED PDISABLED style='background-color:silver'":"")+"  "+(chkrequired=="1"? "CHKREQUIRED ":(chkrequired!=''?"CHKREQUIRED=\""+chkrequired+"\" ":""))+"  name=\""+this.nmStr+"id2\" id=\"_"+this.nmStr+"id2\" maxlength=20 size=20 VALUE=\""+id2+"\" "+(idchk!=null? "CHKFORMAT="+idchk+"":"" )+"  onclick=\""+this.objname+".checkIDFormat(this,this.previousSibling.previousSibling);\"  onblur=DoReq(this)>";
	fnlstr+="</td></tr>";
	return fnlstr;
}
JSVCNameIDObject.prototype.genNationality=function(nationalityID,chkrequired,disabled)
{	
	var shortlist;
	var fnlstr="<tr><td valign=baseline>"+this.config.Label_Nationality+(this.config.Label_Postfix!=""?" "+this.config.Label_Postfix:"")+"</td><td>";	
	fnlstr+="<select URLVAR id=\"_"+this.nmStr+"nationsel\" name=\""+this.nmStr+"nationsel\"  "+(disabled==1?"DISABLED PDISABLED":"")+"  "+(chkrequired==1?"CHKREQUIRED":"")+"   "+(this.config.NationalityChangeID2==1? "onchange=\""+this.objname+".refresh(event);\" onblur=\""+this.objname+".refresh(event);\" ":" onchange=DoReq(this) onblur=DoReq(this)")+" ><option>";
	if(nationalityID==null)
		nationalityID=""
	else
		nationalityID=nationalityID.toString();
	if(nationalityID=="" && this.config.NationalityDefaultCountryID==1)
		nationalityID=this.config.DefCountryID;
	var ShortListCountryArray=new Array();
	if(this.config.CtryShortlist==null||this.config.CtryShortlist=="")
	{	// If NULL/missing then use default from CountrySettings
	 	if (CountrySettings[this.config.DefCountryID]!=null && CountrySettings[this.config.DefCountryID].CtryShortlist!=null) 
	 	{
			if(CountrySettings[this.config.DefCountryID].CtryShortlist!="")
			 	ShortListCountryArray=CountrySettings[this.config.DefCountryID].CtryShortlist.split(",");
	 	}
	} else
	{
		if(this.config.CtryShortlist!="")
		 	ShortListCountryArray=this.config.CtryShortlist.split(",");
	}
	
	if(ShortListCountryArray.length>0)
	{	// If not provided, check from 
	 	fnlstr+="<optgroup label=\"ShortList\">";
		for(var x=0;x<ShortListCountryArray.length;x++)
		{
			for(var i in countries)
			{
				if(countries[i].value==ShortListCountryArray[x])
				{
					fnlstr+="<option value=\""+countries[i].value+"\" "+(countries[i].value==nationalityID?"SELECTED":"")+">"+countries[i].name+"</option>";
					break;
				}
			}
		}
		fnlstr+="</optgroup>";
	   	fnlstr+="<optgroup label=\"Others\">";
	}
	for (var j=1; j<countries.length; j++)
	{	var found=0;
		for(var x=0;x<ShortListCountryArray.length;x++)
			if(countries[j].value==ShortListCountryArray[x])
			{
				found=1;break;
			}
		if(found==0)
			fnlstr+="<option value=\""+countries[j].value+"\" "+(countries[j].value==nationalityID?"SELECTED":"")+">"+countries[j].name+"</option>";		
	}
	if(ShortListCountryArray.length>0)
		fnlstr+="</optgroup>";
	fnlstr+="</td></tr>";
	return fnlstr;
}

JSVCNameIDObject.prototype.refresh=function(event)
{
	var o_com,IsCom,oNat,NatID,comStr,optListStr;
	// Check if company and reset isCom flag
	o_com=document.getElementById("_"+this.nmStr+"nmselCOM");
	if(o_com!=null && o_com.checked)
	{	this.isCom=1
		comStr="C";
	}
	else
	{	this.isCom=0;
		comStr="I";
	}
	// Check if option list done correctly
	oid_input=document.getElementById("_"+this.nmStr+"id1");
	oid_select=document.getElementById("_"+this.nmStr+"id1sel");
	if(oid_input!=null && oid_select!=null)
	{
		optListStr=comStr+":*"+this.config.DefCountryID;
		if(optListStr!=this.ID1ListStr)
		{
			this.ID1ListStr=optListStr;
			this.genOptionList(optListStr,oid_select,oid_select.value);
		}
		this.checkIDFormat(oid_input,oid_select);
		if (oid_select.options.length==0 || this.id1disabled==true)
		{			
			oid_select.disabled=true;
			oid_input.disabled=true;	
			oid_input.style.backgroundColor="silver";
		}
		else
		{
			oid_select.disabled=false;
			oid_input.disabled=false;
			oid_input.style.backgroundColor="";
		}
		DoReq(oid_input);
		DoReq(oid_select);
	}

	oNat=document.getElementById("_"+this.nmStr+"nationsel");
	if(oNat!=null)
	{
		NatID=oNat.value;
		DoReq(oNat);
	}
		
	oid_input=document.getElementById("_"+this.nmStr+"id2");
	oid_select=document.getElementById("_"+this.nmStr+"id2sel");
	if(oid_input!=null && oid_select!=null)
	{
		optListStr="";
		if(NatID!="" && NatID!=this.config.DefCountryID && this.config.NationalityChangeID2==1)
			optListStr=comStr+":*"+NatID+","+this.config.DefCountryID
		else
			optListStr=comStr+":"+this.config.DefCountryID;
		if(optListStr!=this.ID2ListStr)
		{
			this.ID2ListStr=optListStr;
			this.genOptionList(optListStr,oid_select,oid_select.value);
		}
		this.checkIDFormat(oid_input,oid_select);
		if (oid_select.options.length==0 || this.id2disabled==true)
		{			
			oid_select.disabled=true;
			oid_input.disabled=true;	
			oid_input.style.backgroundColor="silver";
		}
		else
		{
			oid_select.disabled=false;
			oid_input.disabled=false;
			oid_input.style.backgroundColor="";
		}
		DoReq(oid_input);
		DoReq(oid_select);
	}
}
JSVCNameIDObject.prototype.genOptionList=function(genOptStr,objSel,selID)
{	// genOptStr: Option string in this format: C:1*,2* ==> (C/I):CountryID*,CountryID*,...*=Primary
	var arr,mark,ctryID,ctryIdx,str,grpCnt,idval,pGrp,opt,idListArray,idList,idName;
	if(objSel!=null)
	{
		while (objSel.firstChild) {
			objSel.removeChild(objSel.firstChild);
		}
	}
	if(genOptStr==null || genOptStr=="")
	{
		return "";
	}
	str="";
	arr=genOptStr.split(":");
	if(arr[0]=="C")
		isCom=1
	else
		isCom=0;
	arr=arr[1].split(",");
	for(var x=0;x<arr.length;x++)
	{
		if(arr[x].substring(0,1)=="*")
		{
			mark=1;
			ctryID=arr[x].slice(1);
		} else
		{
			mark=0;
			ctryID=arr[x];		
		}
		idList=null;
		idListArray=new Array();
		ctryIdx=CSGetCountryIndexPos(ctryID);
		if(this.config.OvrIDStr!=null && this.config.OvrIDStr!="" && ctryID==this.config.DefCountryID)
		{	// Still using old IDStr format
			var idListTmp=this.config.OvrIDStr.split("|");
			if(isCom==1)
			{	// Old style: First element always company
				if(Trim(idListTmp[0])!="")
				{
					idListArray[0]=idListTmp[0];
					if(idListArray[0].length>0 && idListArray[0].substring(0,1)!="*")
						idListArray[0]="*"+idListArray[0];
				}
			} else
			{	
				if(idListTmp.length>1)
				{
					idListTmp.shift();
					idListArray=idListTmp;
				}
			}
		} else
		{	
			if (CountrySettings[ctryID]!=null)
			{
				if(isCom==1)
					idList=CountrySettings[ctryID].ComID
				else
					idList=CountrySettings[ctryID].IndID;
			}
			if(idList!=null)
				idListArray=idList.split("|");
		}
		if(idListArray.length>0)
		{	grpCnt=0;
			for(var y=0;y<idListArray.length;y++)
				if(idListArray[y].length>0)
				{
					var idval=null;
					if (mark==1)		//(mark=="*")
					{
						if (idListArray[y].substring(0,1)=="*")
							idval=idListArray[y].slice(1);
					}
					else
					{
						if (idListArray[y].substring(0,1)!="*")
							idval=idListArray[y];
					}
					if (idval!=null)
					{
						// Interprete ID string
						var idcomp=idval.split("!");
						if(idcomp.length>1)
						{
							idval=idcomp[0];
							idcomp=idcomp[1].split("~");
							idname=idcomp[0];
							if(idcomp.length>1)
								idchk=idcomp[1]
							else
								idchk=null;
						} else
						{
							idval=idcomp[0];
							idname=IDtypes[idval].Name;
							idchk=IDtypes[idval].IdChkStr;
						}

						if(grpCnt==0)
						{
							str+="<OPTGROUP LABEL=\""+countries[ctryIdx].name+"\">";
							pGrp=document.createElement("optgroup");
							pGrp.label=countries[ctryIdx].name;
						}
						grpCnt++;
						//idchk=IDtypes[idval].IdChkStr;
						str+="<OPTION "+((idchk!=null && typeof(idchk)=="string" && idchk.length>0)?" IDCHKSTR=\""+idchk+"\" ":"")+" VALUE=\""+idval+"\" "+(idval==selID?"SELECTED":"")+">"+idname+"</OPTION>";
						opt=document.createElement("option");
						opt.value=idval;
						opt.innerHTML=idname;
						if(idchk!=null && typeof(idchk)=="string" && idchk.length>0)
							opt.setAttribute("IDCHKSTR",idchk);
						if(idval==selID)
							opt.selected=true;
						pGrp.appendChild(opt);
					}
				}
			if(grpCnt>0)
			{
				str+="</OPTGROUP>";
				if(objSel)
					objSel.appendChild(pGrp);	
			}
		}
	}
	return str;
}
JSVCNameIDObject.prototype.checkIDFormat=function(obj,obj2)
{	//obj:id string		obj2:idtype select
	var opt;
	if (obj2.selectedIndex>=0 && obj2.options.length>0)
	{	var opt=obj2.options[obj2.selectedIndex];
		idchk=opt.getAttribute("IDCHKSTR");
		if (idchk!=null && typeof(idchk)=="string" && idchk.length>0)		
			obj.setAttribute("CHKFORMAT",idchk)
		else
			obj.removeAttribute("CHKFORMAT");
	}
	DoReq(obj);
}
JSVCNameIDObject.prototype.setConfigStruct=function(setup_config)
{
	if(setup_config!=null && typeof(setup_config)=="object")
	{
		for (var name in setup_config)
	  		if (setup_config.hasOwnProperty(name) && this.config.hasOwnProperty(name)) 
    			this.config[name]=setup_config[name];
	}
}
JSVCNameIDObject.prototype.getConfigStruct=function()
{
	return this.config;
}
JSVCNameIDObject.prototype.setDefCountryID=function(ctryid)
{
	this.config.DefCountryID=ctryid;
}
JSVCNameIDObject.prototype.setOvrIDStr=function(idstr)
{
	this.config.OvrIDStr=idstr;
}
JSVCNameIDObject.prototype.setCtryShortlist=function(ctryshortlist)
{
	this.config.CtryShortlist=ctryshortlist;
}

//make tables highlightable - type=0 is for tr highlighting, while type 1 for td 'deep' highlighting.
//usage : highlighter( tableobj,0 ); 

highlighter = function(o,type,onclass,offclass,oncolor,offcolor){

    var oldclass = new Array();

    if (type==null) type = 1;
    if (onclass==null) onclass='clsSVChlon';
    if (offclass==null) offclass='clsSVChloff';
    if (oncolor==null) oncolor='pink';
    if (offcolor==null) offcolor='';
   
    this.hlon = function (e) { // highlight
        var obj = getTR(e);
        var j = 0;
        if (obj&& obj.tagName == 'TR' && obj.parentNode.tagName != "THEAD" && obj.parentNode.tagName != "TFOOT") {
            if (type == 1){ 
                for (j=0;j<obj.cells.length;j++) { //cells                
					if (document.all) {
						oldclass[j] = (obj.cells[j].style && obj.cells[j].style.backgroundColor != ''?obj.cells[j].style.backgroundColor:offcolor);
						obj.cells[j].style.backgroundColor = oncolor;
					} else 				
                    	obj.cells[j].className= onclass + ' ' + obj.cells[j].className;
                    	
                }
            }
			if (document.all) {					
                oldclass[j] = (obj.style&&obj.style.backgroundColor!=''?obj.style.backgroundColor:offcolor);
	            obj.style.backgroundColor = oncolor; 
			} else {				
				obj.className = onclass + ' ' + obj.className;
			} 
			
        }
    }

    this.hloff = function (e) { // highlight off
        var obj = getTR(e);
        var j = 0;
        var color;
		var c = obj.className || "";
        if (obj&& obj.tagName == 'TR' && obj.parentNode.tagName != "THEAD" && obj.parentNode.tagName != "TFOOT") {
            if (type==1) {
                for (j=0;j<obj.cells.length;j++) {   
					if (document.all) obj.cells[j].style.backgroundColor = oldclass[j];			
					else obj.cells[j].className = obj.cells[j].className.replace(new RegExp("(^|\\s)"+onclass+"(\\s|$)"),"$1");
                }
            }
			if(document.all) obj.style.backgroundColor = oldclass[j];
			else obj.className = obj.className.replace(new RegExp("(^|\\s)"+onclass+"(\\s|$)"),"$1");
        }
    }

    this.getTR = function(e) { // get the row from the triggered event element
        var obj;
        if (window.event)    
        {
            e = window.event;
            obj = e.srcElement;
        } else {
            obj = e.target;
        }
        while ( obj.parentNode && obj.tagName != 'TR' && obj.tagName != 'TABLE') {
            obj = obj.parentNode;
        }
        return obj;
    }
   
    this.addTableHighlight = function () { // adds onmouseover/out listening events
        if( !(o&&o.tagName== 'TABLE')) return;
        if (o.addEventListener){
            o.addEventListener('mouseover', hlon, true); 
            o.addEventListener('mouseout', hloff, true); 
        } else if (o.attachEvent){ 
            o.attachEvent('onmouseover', hlon); 
            o.attachEvent('onmouseout', hloff);
        }
    }   
   
    this.addTableHighlight();
}
var SVCStatSummary=function(cols,coltitles,order,lnk,totstr)
{
	this.cols=cols.split("|");
	this.coltitles=coltitles.split("|");
	if(order==null || order=="")
		this.order=null
	else
		this.order=order.split("|");
	this.itms=new Array();
	this.cnt=0;
	this.tot=0;
	this.lnk=lnk;
	this.totstr=totstr;
}
SVCStatSummary.prototype.add=function(id,desc,cnt,supp)
{
	var o=new Object();
	o.desc=desc;
	o.cnt=cnt;
	o.supp=supp;
	this.itms[id]=o;
}
SVCStatSummary.prototype.genrow=function(stat,itm)
{
	this.cnt++;
/*	// Old style
	document.write("<b>"+itm.cnt+"</b> case"+(itm.cnt>0?"s":"")+" in <a style=font-weight:bold href=\""+request.webroot+this.lnk+stat+"&"+request.mtoken+"\">"+itm.desc+"</a>"+
		(itm.supp>0?" / <b>"+itm.supp+"</b> suppl":"")+"</br>"); */
	document.write("<tr class=\""+((this.cnt%2)==0?"clsDetail4":"clsDetail5")+"\">");
	for(x in this.cols)
	{
		coltype=this.cols[x];
		if(coltype=="cnt")
			document.write("<td style=text-align:center;width:6ex class=\"clsCaseCnt\">"+(itm.cnt>0?itm.cnt:"")+"</td>")
		else if(coltype=="supp")
			document.write("<td style=text-align:center;width:6ex class=\"clsCaseCnt2\">"+(itm.supp>0?itm.supp:"")+"</td>")
		else if(coltype=="desc")
			document.write("<td width=100% style=padding-left:3px><a style=font-weight:bold href=\""+request.webroot+this.lnk+stat+"&"+request.mtoken+"\">"+itm.desc+"</a></td>");
	}
	document.write("</tr>");
	this.tot+=itm.cnt;
}
SVCStatSummary.prototype.gen=function(notitle)
{
	var x,itm;
	// Header
	document.write("<table cellpadding=\"2\" cellspacing=\"0\" class=\"clsMainTable\" border=1 width=100%>");
	if(notitle==null)
		if(this.itms.length==0)
			notitle=1
		else notitle=0;
	if(notitle==0)
	{
		document.write("<tr class=\"header\">");
		for(x in this.coltitles)
			document.write("<td align=center>"+this.coltitles[x]+"</td>");
		document.write("</tr>");
	}
	if(this.order!=null)
	{
		for(x in this.order)
		{
			itm=this.itms[this.order[x]];
			if(itm!=null)
			{
				this.genrow(this.order[x],itm);
				this.itms[this.order[x]]=null;
			}
		}
	}
	for(x in this.itms)
	{
		if(this.itms[x]!=null)
			this.genrow(x,this.itms[x]);
	}
	if(this.totstr!=null)
		document.write("<tr><td colspan="+this.cols.length+" style=font-weight:bold;font-size:140%>"+this.tot+" "+this.totstr+"</td></tr>");
	document.write("</table>");
}
SVCconfirmPrompt=function(varname,event,action,confirmtext,callback) {
	this.varname=varname;
	this.action=action;
	this.confirmtext=confirmtext;
	this.callback=callback;
	
	this.pp=new JSVCpopup("pp",null,"pp_CTXMENU");
	this.vf=this.pp.ctxname+"_verify";

	this.pp.width=300;
	this.pp.title="CONFIRMATION";
	if(this.confirmtext==null) {
		this.pp.msg=action;
		this.pp.exfields=null;
	} else {
		this.pp.msg=JSVClang("Are you sure you want to {0}?\nType {1} to confirm.",5019,0,this.action,this.confirmtext);
		this.pp.exfields=[[null,"<input CHKREQUIRED CHKNAME='"+this.confirmtext+"' id="+this.vf+" onblur=DoReq(this) onkeypress=\"if(event.keyCode==13){"+this.varname+".fnOK()}else if(event.keyCode==27){"+this.varname+".fnCancel()}\">"]];
	}
	this.pp.fnOK=this.varname+".fnOK";
	this.pp.fnCancel=this.varname+".fnCancel";
	this.pp.gen();
	this.pp.show(event);
	var o=document.getElementById(this.vf);
	if(o) o.focus();
}
SVCconfirmPrompt.prototype.fnOK=function() {
	var cb=false;
	if(this.confirmtext==null) {
		cb=true;
		this.pp.hide();
	} else {
		var txt=document.getElementById(this.vf).value;
		if(Trim(txt.toUpperCase())==this.confirmtext) {
			this.pp.hide();
			cb=true;
		} else {
			this.pp.hide();
			SVCalert(JSVClang("You didn't "+"{0}"+". "+"{1}"+" cancelled.",5020,0,this.confirmtext,this.action));
		}
	}
	if(cb) {
		if(typeof(this.callback)=="function")
			this.callback(this.action);
		else
			eval(this.callback+"('"+this.action+"')");
	}
}
SVCconfirmPrompt.prototype.fnCancel=function() {
	this.pp.hide();
}
SVCalert=function(msg) {
	var alert_popup=new JSVCpopup("alert_popup",null,"alert_popup_CTXMENU");
	alert_popup.width=300;
	alert_popup.title="ALERT";
	alert_popup.msg=msg;
	alert_popup.btnFlag=1;
	alert_popup.gen();
	alert_popup.show(window.event);
}
SVCconfirm=function(msg,callback) {
	oSVCconfirm=new SVCconfirmPrompt("oSVCconfirm",window.event,msg,null,callback);
}
SVCprompt=function(action,confirmtext,callback) {
	oSVCprompt=new SVCconfirmPrompt("oSVCprompt",window.event,action,confirmtext,callback);
}
