﻿// 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)
{
	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
	}
	// Return array: Negative Symbol,Decimal Symbol,Default decimal-places for currency,Separator Symbol,Separator Pattern
}
function JSVCNumLOC(val,maxno,minno,decplace,decsymbol,separator)
{
	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;}
	fl=JSVCNumLOCtoDB(val,decsymbol,separator,1);
	// Perform Rounding
	if(fl==null || fl<minno || fl>maxno)
		str=""
	else
		str=JSVCNumDBtoLOC(fl,decplace,decsymbol,separator);
	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);
}
function JSVCNumDBtoLOC(fl,decplace,decsymbol,separator)
{
	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 "";
	}
	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].length>0)
	{	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;
	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)
{
	return JSVCNumLOC(val,maxno,minno);
}
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);
}
/*-------------------- 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;
	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");
	if(ver!=null)
	{
		if(ver!="")
		{
			// Dependency
			if(eval(ver)==true && val=="")
				return JSVClang("should be specified.",5005);
		} else
		{
			if(val=="")
				return JSVClang("should be specified.",5005);
		}
	}
	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(!val.match(re)) {
			var sample=obj.getAttribute("CHKRESAMPLE");
			if(sample!=null && sample.length>0)
				return JSVClang("incorrect. For example: {0}",0,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 JSVCSetDisabledList(list,chk)
{
	var obj2,listarr,abc,obj3;
	listarr=list.split(",");
	for(abc in listarr) {	
		obj2=JSVCall(listarr[abc]);
		if(obj2!=null) {
			obj2.disabled=(chk?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=(chk?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=(chk?true:false);
					DoReq(j);
				}
			}
			obj3=obj2.getElementsByTagName("SELECT");
			for(var i=0;i<obj3.length;i++) {
				var j=obj3[i];
				j.disabled=(chk?true:false);
				DoReq(j);
			}
			obj3=obj2.getElementsByTagName("TEXTAREA");
			for(var i=0;i<obj3.length;i++) {
				var j=obj3[i];
				j.disabled=(chk?true:false);
				DoReq(j);
			}
		}
	}
}
function MRMPreprocessFormItem(obj,doreqonly)
{
	var str,sid,o;
	// Preprocess 1: Check for required highlighting
	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);
						}
//	obj.onkeydown=new Function("CalScrollKey(\""+sid+"\");");
//						obj.onkeyup=new Function("CalScrollKey(\""+sid+"\");");
					}
					o=document.createElement("span");
					o.innerHTML="&nbsp;"+CalGenScript(sid,1);
					obj.parentNode.insertBefore(o,obj.nextSibling);
					//obj.insertAdjacentHTML("afterEnd","&nbsp;"+CalGenScript(sid,1));
				}
			}
		}
		// Preprocess 3: MRMOBJ=TEXTAREA
		else if(str=="TEXTAREA")
		{	if(obj.onblur==null)
				obj.onblur=new Function("ObjText(this);");
		}
	}
	}
}
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)
{
	var tgname,col,len,obj2,bkcolor,str;
	if(obj==null)return;
	tgname=obj.tagName;
	if(tgname=="FORM")
	{
		col=obj.elements;
		len=col.length;
		if(len!=null)
		{
			for(var t=0;t<len;t++)
			{
				obj2=col[t];
				if(obj2.type!="checkbox" && obj2.type!="radio")
					if(obj2.disabled==false && !(obj.style.backgroundColor=='#f2cccc'||obj.style.backgroundColor=="rgb(242, 204, 204)"))
						{	str=FormObjVerify(obj2);
							if(str!="")
							{	if(doprompt)alert("Field "+str);
								obj2.setAttribute("BKGROUND",obj2.style.backgroundColor);
								obj2.style.backgroundColor='#f2cccc';
							}
						}
			}
		}
	} else
	{
		bkcolor=obj.getAttribute("BKGROUND");
		if(obj.type!="checkbox" && obj.type!="radio")
		{
			str=FormObjVerify(obj);
			if(str=="" || obj.disabled==true)
			{
				bkcolor=obj.getAttribute("BKGROUND");
				if(bkcolor!=null)
				{
					obj.style.backgroundColor=bkcolor;
					obj.removeAttribute("BKGROUND");
				}
			}
			else 
			{	if(doprompt && str!="")
					alert("Field "+str);
			if(!(obj.style.backgroundColor=='#f2cccc'||obj.style.backgroundColor=="rgb(242, 204, 204)"))
			{
				obj.setAttribute("BKGROUND",obj.style.backgroundColor);
				obj.style.backgroundColor='#f2cccc';
			}}
		}
	}
}
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 Trim(val)
{
	if(val==null)
		return "";
	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)|(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;
	// 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;
//		obj.style.posLeft=document.body.scrollLeft + posX;
//		obj.style.posTop=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;
//			obj.style.posTop=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;
//		obj.style.posLeft=document.body.scrollLeft+event.clientX-event.offsetX;
//		obj.style.posTop=document.body.scrollTop+event.clientY-event.offsetY;
		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;
//			obj.style.posTop=pos;
		}
	} else if (pos==2)
	{
		// Center of screen
//		alert("document.body.scrollLeft:"+document.body.scrollLeft);
//		alert("document.body.clientWidth:"+document.body.clientWidth);
		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;
//		obj.style.posLeft=document.body.scrollLeft+(document.body.clientWidth-obj.clientWidth)/2;
//		obj.style.posTop=document.body.scrollTop+(document.body.clientHeight-obj.clientHeight)/2;
		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;
//			obj.style.posTop=pos;
		}
	} else if(pos!=-1)
	{
		// At Mouse location
		obj.style.left=document.body.scrollLeft+event.clientX;
//		obj.style.posLeft=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;
//		obj.style.posTop=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.posTop=pos;
			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)
{
	var e=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
	if(itm.doFunction != null)
		eval(itm.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,chkDOB,idDOB)
{	// idtyp: 1=Main ID, 2=Sec ID (cannot be both)
	var o,t,itm,musttyp,genstr,chkformat,maxl,chkreq;
	o=jSVCidstr.split("|");
	if(val==null)val="";
	if(chkDOB==null) chkDOB=0;
	if(idDOB==null) idDOB="";	
	genstr="";
	chkformat="";
	chkreq=req;
	if(sel==null)
		sel=-1;
	if(chkreq==2)
		if(sel==null || sel<=0)chkreq=0;
	if(idtyp!=2 && o[0].length>0)
		genstr+="<input URLVAR CHKNAME=\"ID type\" id=\"_"+nm+"0cel\" name=\""+nm+"cel\""+(sel==1?" CHECKED":"")+(dis==1||sel!=1?" DISABLED":"")+" type=radio value=1 onclick=\"JSVCIDChk('"+nm+"')\"><label for=\"_"+nm+"0cel\"> "+o[0]+"</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("~");
			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==t+1)?" CHECKED":"")+" type=radio"+(itm.length>1&&itm[1].length>0?" DOCHKFORMAT=\""+itm[1]+"\"":"")+" value=\""+(t+1)+"\" onclick=\"JSVCIDChk('"+nm+"');\"><label for=\"_"+nm+t+"sel\"> "+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!="")
		genstr+="<br><input URLVAR "+(req>0?"CHKREQUIRED ":"")+"name=\""+nm+"\""+" id=\""+nm+"\""+(chkformat==""?"":" CHKFORMAT=\""+chkformat+"\"")+" maxlength="+maxl+" size=30 style=text-transform:uppercase "+(chkDOB?"chkDOB=1":"")+" VALUE=\""+(val!=null?val:"")+"\" onblur=\"JSVCIDChk(this);"+(idDOB!=''?'JSVCSetDOB(\''+nm+'\',\''+idDOB+'\')':'')+"\""+(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);
		if (yyyy.substr(0,1) == '0') yyyy = '20' + yyyy; // please take note that this will break in the next century.
		else yyyy = '19' + yyyy;
		if (JSVCIsDate(dd+'/'+mm+'/'+yyyy)) 
			return (ret?(dd+'/'+mm+'/'+yyyy):true);
	}	
	return (ret?"":false);
}
function JSVCSetDOB(src,tgt) {
	var sobj=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);
	}
}
function JSVCIDChkMyIC(obj)
{
	if(obj==null)return "";
	str=obj.value.replace(/[^0-9]/g,"");
	if(str.length==12 && (obj.getAttribute("chkDOB")==null || (obj.getAttribute("chkDOB")!=null && obj.getAttribute("chkDOB") && 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,chkDOB,idDOB)
{	// 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
	// chkDOB: chk for valid date of birth in Malaysian IC
	// idDOB: update obj.id value with Malaysian IC DOB value
	var spclist,genstr,fnlstr;
	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;
	if(chkDOB==null) chkDOB=0;
	if(idDOB==null) idDOB="";
	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+=(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,chkDOB,idDOB);
		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);
		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) {
	var r,re,rx;
	Despace(obj);
	r=obj.value;
	if(type==null) type=0;
	if(r.length>0) {
		if(type==1)
			rx="^([0-9a-zA-Z_\.\-]{2,20}@[0-9a-zA-Z_\.\-]{2,30})|([0-9a-zA-Z_]{3,20})$";
		else
			rx="^([0-9a-zA-Z_\.\-]{2,20}@[0-9a-zA-Z_\.\-]{2,30})$";
		re=new RegExp(rx);
		if(!r.match(re)) {
			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 "";	
}
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!=''")+"\" 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+"\" 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)
{
    rgexp=new RegExp("([&\?])("+str+")[=][^&]*","gi");
    result=url.replace(rgexp,"$1");
    result=result.replace(/&$/,""); // remove at ending
    result=result.replace(/([&\?])&/gi,"$1");
    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);
	}
}
/////////////////////////////////////////////////////////////////////////////////////////
// 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;
			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'"; 
			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'"; 
			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
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;
	}
	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;
	}
}

/*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
 */
function JSVCCompareDate(firstdate,seconddate,firstdatename,seconddatename,type,num,range)
{
	if(firstdate==null)firstdate = '';
	if(seconddate==null)seconddate = '';
	if(range==null||range=='')range = 0;
	if (firstdate != '' && seconddate != '') {
		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 != '' && 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()}]
	];
	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 */
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[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 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) {
	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);
}
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+">");
	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"):JSVClang("Add"))+" >>' onclick='var result="+this.id+".addMore(this);if(result){JSVChide(this.parentNode)}'></div>");
	}
	else
		this.gen2(cols,null);
	if(!/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-1 && (i%this.columns)==0)
			str+="<tr>";
		str+="<td>"+(cols[i]?cols[i][1]:"")+"</td>"+"<td>"+this.getCol(cols[i],index)+"</td>";
	}
	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) {
			document.write("<tr><td class=header colspan="+2*this.columns+" valign=bottom><div style=float:left>"+this.title+(index>0?" "+(index+1):"")+"</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>")
	}
	str="<tbody id=TAB"+this.id+index+"BODY>"+str+"</tbody>";
	document.write(str);
	if(this.type=="TABLE") {
		document.write("</table>");
	}
	document.write("<input type=hidden name="+this.id+"_"+this.queryPK+" value='"+(rowid==null?0:rowid)+"'>");
}
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
		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":"")+">";
	}
	else if(col[0]=="CALDATE") {
		// 5:dtmin,6:dtmax
		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)>";
	}
	else if(col[0]=="MONEY") {
		str="<input type=text name="+name+(col[3]==1?" CHKREQUIRED":"")+" value=\""+jFormat(1,value)+"\" maxlength=12 size=20 onblur=JSVCCurr(this)>";
	}
	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
		var maxchar=(col[5]==null?1024:col[5]);
		var rows=(col[6]==null?5:col[6]);
		str="<textarea WRAP=SOFT MRMOBJ=TEXTAREA MAXCHAR="+maxchar+" ROWS="+rows+" name="+name+(col[3]==1?" CHKREQUIRED":"")+" style=width:100% 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];
	}
	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;
	}
}
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"):JSVClang("Add"))+" >>"
	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+";");
		}
	}
}
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(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);
	}
	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=\""+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 (!val.match(regex)||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>"
	}
	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>";
	var prev=null;
	var subtot=[],subcnt=[];
	var grdtot=[],grdcnt=[];
	// generate data rows
	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+"&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+"&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("\{([a-z0-9]+)\}","gi"); // 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=javascript:JSVCopenWin('"+url+"&nolayout=1')>"+(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=this.getData(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)
			return JSVCCurr(this.getData(col[2],index));
	}
	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 "";
}
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("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
============================================= */
function JSVCgenMultiRows(varname,parentid,formname,valuelist,valuelistsep,onblur) {
	this.varname=varname;
	this.parentid=JSVCall(parentid);
	this.formname=formname;
	this.valuelist=valuelist.split(valuelistsep);
	this.onblur=onblur;
}
JSVCgenMultiRows.prototype.gen=function() {
	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()>";
	if(this.valuelist!=null)
		for(var i=1;i<this.valuelist.length;i++) {
			htm+="<br>"+this.elemT(this.formname,this.valuelist[i]);
		}
	document.write(htm);
}
JSVCgenMultiRows.prototype.addRow=function() {
	var o=this.parentid;
	o.innerHTML+="<br>"+this.elemT(this.formname,"");
}
JSVCgenMultiRows.prototype.elemT=function(name,value) {
	return "<input name="+name+" maxlength=100 size=40 value=\""+value+"\" onblur="+this.onblur+">";
}
/* ======= 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-1];
	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.svcroot+"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;
}
/* JS remarks popup class */
function JSVCremarksPop(varname,formname,ctxname,msgname,title,width,fnOK) {
	this.varname=varname;
	this.formname=formname;
	this.formobj=JSVCall(formname);
	this.title=title;
	this.width=width;
	this.msgheader=this.ctxname+"_MSG";
	this.msgname=msgname;
	this.ctxname=ctxname;
	this.ctxframe=JSVCall(this.ctxname);
	this.fnOK=fnOK; // function name
	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><span id="+this.msgheader+"></span></td></tr><tr><td><textarea CHKREQUIRED CHKNAME='Remarks' name="+this.msgname+" WRAP=SOFT COLS=70 ROWS=5 MRMOBJ=TEXTAREA MAXCHAR=1024 style=width:100% onblur=ObjText(this)></textarea></td></tr><tr><td align=right><input type=button class=clsSVCButton value='Save' onclick='"+this.fnOK+"()'>&nbsp;<input type=button class=clsSVCButton value='Cancel' onclick=JSVCcloseCtxMenu('"+this.ctxname+"')></td></tr></table>";
	JSVCCtxMenuContent(this.ctxframe,html);
	DoReq(this.formobj);
}
JSVCremarksPop.prototype.setMsg=function(msg) {
	var o=JSVCall(this.msgheader);
	o.innerHTML=msg;
}
JSVCremarksPop.prototype.show=function(event) {
	JSVCshowCtxMenuEv(event,this.ctxframe,null,2,2);
}
JSVCremarksPop.prototype.showChk=function(event,fnChk) {
	if(fnChk(this)==true)
		this.show(event);
	else
		JSVCcloseCtxMenu(this.ctxname);
}
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");
	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");
	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");

	// 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");

	return JSVClang("is invalid");
}

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;
		} 
	}
}

function JSVCSplitCols(tableid,tbodyid) { /* use this to split the columns from 2 to 4. */
	var i;
	//tableid,tbodyid,oldnumcols,newnumcols
	tblobj=document.getElementById(tableid);
	if (tblobj==null)return false;
	rowobj=tblobj.rows;
	// for the cols.
 	colobj=tblobj.getElementsByTagName("col");
	var clone = colobj[0].cloneNode(true);
	var clone2 = colobj[1].cloneNode(true);
	colobj[0].parentNode.insertBefore(clone,colobj[0]);
	colobj[2].parentNode.insertBefore(clone2,colobj[1]);
	
	if(tbodyid==null) { // no tbody, split the entire table rather than just the tbody.
		begin=-1;end=rowobj.length-1;
		for(i=rowobj.length-1;i>=0;i--) {
			cellobj=rowobj[i].cells;
			for(j=0;j<cellobj.length;j++) { // cell loop
				if (cellobj[j].className=='header') {
					if (end==-1) { 
						end=i-1;
					}
					else if (begin==-1) { 
						
						begin=i+1;
						oldrowlen=end-begin+1;
						newrowlen=Math.ceil(oldrowlen/2)+begin;
						midrow=Math.floor(oldrowlen/2)+begin;
	
						count=begin;
	
						for(k=newrowlen;k<end+1;k++){ 
							y=rowobj[count];
							var x=rowobj[k].cells[0].cloneNode(true);
								/* MS bug 829907 : selected attribute missing from cloned object */
								var p=rowobj[k].cells[1].getElementsByTagName("SELECT"); 
							var z=rowobj[k].cells[1].cloneNode(true);
								if (p.length != 0) {
									p = p[0].options.selectedIndex;
									z.getElementsByTagName("SELECT")[0].options.selectedIndex=p;
								}
							y.appendChild(x);
							y.appendChild(z);
							count++;
						}
						for(k=end;k>=newrowlen;k--) {
							rowobj[k].parentNode.removeChild(rowobj[k]);
						}
						if(midrow!=newrowlen) { 
							y=rowobj[newrowlen-1];
							pad=y.insertCell(2);
							pad.innerHTML="&nbsp;";
							pad=y.insertCell(3);
							pad.innerHTML="&nbsp;";
						}
						end=-1;begin=-1; 
						if(i!=0) i=i+1;
					}
				} 
			}		
		}
		for(var j=0;j<rowobj.length;j++) // for the colspan.
		{
			cellobj=rowobj[j].cells;
			for(var k=0;k<cellobj.length;k++) {
				if (cellobj[k].colSpan == 2) cellobj[k].colSpan = 4;
			}
		}
	} else {	
		tbodyobj=document.getElementById(tbodyid);
		oldrowlen=tbodyobj.rows.length;
		newrowlen=Math.ceil(oldrowlen/2);
		midrow=Math.floor(oldrowlen/2);
		count=0;
			for(i=midrow;i<oldrowlen;i++){
				y=tbodyobj.rows[count];
				x=tbodyobj.rows[i].cells[0].cloneNode(true);
				z=tbodyobj.rows[i].cells[1].cloneNode(true);
				y.appendChild(x);
				y.appendChild(z);
				count++;
			}
			for (i=oldrowlen-1;i>=midrow;i--) {
				tbodyobj.removeChild(tbodyobj.rows[i]);
			}
			if(midrow!=newrowlen) { 
				y=tbodyobj.rows[newrowlen-1];
				pad=y.insertCell(2);
				pad.innerHTML="&nbsp;";
				pad=y.insertCell(3);
				pad.innerHTML="&nbsp;";
			}
			for(var j=0;j<rowobj.length;j++) // for the colspan.
			{
				cellobj=rowobj[j].cells;
				for(var k=0;k<cellobj.length;k++) {
					if (cellobj[k].colSpan == 2) cellobj[k].colSpan = 4;
					else if (k==cellobj.length-1 && cellobj.length == 2 && cellobj[cellobj.length-1].colSpan == 1) cellobj[cellobj.length-1].colSpan = 3;
				}
			}
	}	
	for(i=0;i<rowobj.length;i++) {
		for(j=0;j<rowobj[i].cells.length;j++)
			rowobj[i].cells[j].vAlign='top';
	}

}