

var main = new Object();
main.currtab = ''; //current tab

function displayLoginUserInfo(userinfo)
{
    document.write(userinfo);
}


function AddOnloadCode(strload,fpm)/*SVC*/
{
	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 DoBackWarning()
{
	AddOnloadCode("var obj=document.all('PARSEONCE'); if(obj.value=='1') { document.all('backwarningblock').style.display='block'; } else { obj.value='1'; };");
}

/*--------------------For Tabs--------------------*/
function TabClick(clicktab)
{
	if(clicktab != main.currtab)
	{
		var tab;
		if(main.currtab != '')
		{
			tab=document.all("TAB"+main.currtab);
			tab.className="clsTab";
			document.all("TABLE" + main.currtab).style.display = "none";
		}
		tab=document.all("TAB"+clicktab);
		tab.className="clsTabSelected";
		document.all("TABLE" + clicktab).style.display = "block";
		//alert('@'+document.all("TABLE" + clicktab).id+'@');
		//alert('@'+document.all("TABLE" + clicktab).innerHTML+'@');
		main.currtab = clicktab;
	}
}
/*--------------------------------------------*/


function Trim(val)/*SVC*/
{
	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)/*SVC(M)*/
{
	var target = "";
	var ct;
	for(ct=0;ct<str.length;ct++)
		if(str.charAt(ct) != " ")
			target = target + str.charAt(ct);
	return target;
}

function ObjAlphaNum(obj, minlen, maxlen)/*SVC*/
{
	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)/*SVC*/
{
	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+"Only alphanumeric characters (A-Z, 0-9 or _) are allowed in this field. ";
	if(val!="" && val.length<minlen)
		msg=msg+"Minimum length for this field is " + minlen + " characters. ";
	else if (val!="" && val.length>maxlen && maxlen!=-1)
		msg=msg+"Maximum length for this field is " + maxlen + " characters. ";
	return msg;
}

function ObjPc(obj)
{		
	ObjInt(obj,0,100);
	DoReq(obj);
}

function Obj1DP(obj,maxno)
{
	var alertfocus; 
	if (Trim(obj.value)!==""){alertfocus=obj;} else {alertfocus=0;}
	obj.value=Make1DP(obj.value,maxno,alertfocus);
	DoReq(obj);
}

function Make1DP(val,maxno,obj)
{
	var ret,fl,b;
	ret = "";
	if(maxno==null || maxno==0)
		maxno=10000000
	else if(maxno==-1)
		maxno=1000
	else if(maxno==-2)
		maxno=100;
	val=val.toString().replace(/[^0-9.]/g,"");
	fl = (Math.round(parseFloat(val) * 10) / 10).toString();
	if (isNaN(fl) || fl < 0 || fl > maxno)
		{
			if (obj!==0)
			{
				alert("You have entered an invalid value. Please reenter.");
				obj.focus();
			}
		return "";
		}
	b = fl.lastIndexOf(".");
	if (b == -1)
		return fl+".0"
	else
		return fl;
}

//Makes obj.value int. If obj.value is not "", then will alert and focus if not a number entered.
function ObjInt(obj,minval,maxval)
{
	var alertfocus; 
	if (Trim(obj.value)!==""){alertfocus=obj;} else {alertfocus=0;}
	obj.value=MakeInt(obj.value,minval,maxval,alertfocus);
	DoReq(obj);
}

//Returns an integer (by flooring it). 
//If not a number, then if obj not 0 will return "" else alerts and switch focus to obj.
function MakeInt(val,minval,maxval,obj)
{
	var ival=parseInt(val,10);
	if(isNaN(ival) || (minval!=null && ival < minval) || (maxval!=null && ival > maxval))
		{
		if (obj!==0)
		{
			alert("You have entered an invalid value. Please reenter.");
			obj.focus();
		}
		return "";		
		}
	return ival;
}

//Makes obj.value 2DP. If obj.value is not "", then will alert and focus if not a number entered.
function Obj2DP(obj)
{
var alertfocus; 
if (Trim(obj.value)!==""){alertfocus=obj;} else {alertfocus=0;}
obj.value = AddThousandsSeparator(Make2DP(obj.value, alertfocus));
DoReq(obj);
}

//Returns a number with 2DP accuracy. If not a number will return "", and also alerts and switch focus to obj if the parameter obj is not set to 0.
function Make2DP(val, obj)
{
	if (obj==null) obj=0;
	var ret = "";
	val=val.toString().replace(/,/g,"");
	var fl = (Math.round(parseFloat(val) * 100) / 100).toString();
	if (isNaN(fl) || (fl < 0)) // || (fl >= 9999999999999) - removed upper bound
		{
		if (obj!==0)
		{
			alert("You have entered an invalid value. Please reenter.");
			obj.focus();
		}
		return "";
		}
	var b = fl.lastIndexOf(".");
	if (b == -1)
		ret = fl + ".00"
	else
	{
		b = fl.length - b - 1;
		if (b == 0) 
			ret = fl + "00"
		else if (b == 1) 
			ret = fl + "0"
		else
			ret = fl;
	}	
	return ret;
}

function ObjText(obj)
{
	var maxchar=obj.getAttribute("MAXCHAR");
	if(maxchar!=null && maxchar!="")
	{
		if (obj.innerText.length>parseInt(maxchar))
		{	
			alert("You have entered a total of " + obj.innerText.length + " characters, which is greater than the maximum allowed (" + maxchar + " characters). Please shorten your description/comment.");
			obj.focus();
		}		
	}
}

function AddThousandsSeparator(val)
{
	var temp1, temp2;
	var split=6;
	do
	{
		temp1=val.substr(0,val.length-split);
		temp2=val.substr(val.length-split);
		val=temp1+(temp1==""?"":",")+temp2;
		split+=(temp1==""?3:4);
	}
	while (temp1!="");
	return val;
}

//Returns a number to the nearest dollar, expects a number or string representing a number, for instance the output of Make2DP
function RoundtoDollar(val)
{
var afterdot = (val*100)%100;
var beforedot = parseInt(val);
if (afterdot > 0) {beforedot +=1} 
val = beforedot.toString() + ".00";
return val;
}

function MakeNumberWords(val)
{
	var no = new Array("","one","two","three","four","five","six","seven","eight","nine","ten",
	"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen",
	"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety","","thousand","million","billion","trillion");
	var str="",ct=0,neg=0;
	var valwithcents=val;
	var val=parseInt(valwithcents);
	if (val < 0)
		{	val = Math.abs(val); neg=1; }
	while(val > 0) 
	{
		str=((val%1000)>99?no[parseInt(val/100%10)]+" hundred"+(val%100?" and ":""):"")+
			(val%100<20?no[val%100]:no[20+parseInt((val%100)/10)-2]+(val%10?" ":"")+
			no[val%10])+(val%1000?" "+no[28+ct]+(str!=""?" ":""):"")+str;
		val = parseInt(val/1000); ct++; 
	}
	str = str + (valwithcents*100%100==0?"":("and cents " + MakeNumberWords(valwithcents*100%100))); 
	return (neg==1?"minus ":"")+str;
}

/*------------------Date Checking and Calendar--------------------*/
function ObjDate(obj,doNotPrompt)
{
	var dtformat,dt,dtmin,dtmax;
	dtformat=obj.DTFORMAT;
	if(dtformat=="" || dtformat==null)
		dtformat="dd/mm/yyyy";
	if(doNotPrompt==null)
		doNotPrompt=obj.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 CalConstructDate(d,m,y,sTmp)
{
	var	mthName =	new	Array("January","February","March","April","May","June","July","August","September","October","November","December");
	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])
	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("Minimum date allowed is "+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("Maximum date allowed is "+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="dd/mm/yyyy";
	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;
}



/////////////////////////////////////////////////////////////////////////////////////////
// To Toggle one image to another. The image files should be named *1.* and *2.* and
// located in the same directory. 
//  
////////////////////////////////////////////////////////////////////////////////////////
function ToggleIcon(obj)
{
	var pos=obj.src.search(/2.gif|1.gif|2.jpg|1.jpg|2.jpeg|1.jpeg/i);
	var icontype=obj.src.slice(pos);
	var icon=obj.src.charAt(pos);
    if (icon==1) icon=2; else icon=1;
    icontype=icontype.replace(/2|1/, icon);
	obj.src=obj.src.substring(0,pos)+icontype;
}

/////////////////////////////////////////////////////////////////////////////////////////
// To Toggle display from "none" to "block" and vice-versa. 
// Pass in the unique id of the object that we are toggling 
////////////////////////////////////////////////////////////////////////////////////////
function ToggleDisplay(id)
{
if (document.all(id).style.display=='none')  document.all(id).style.display='block';
else document.all(id).style.display='none';
}

/////////////////////////////////////////////////////////////////////////////////////////
// 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 openWindow(src, cascade, menubar, awidth, aheight, returnwin, wintype, toolbar )
{
	if (cascade == null) cascade = 0;
	if (menubar == null) menubar = "no";
	if (returnwin==null) returnwin = false;
	if (wintype==null) wintype = "window";
	if (toolbar == null) toolbar = "no";

	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;	
	switch (wintype)
	{
		case "window": 
		{
			aStr = "left=" + x_offset + ",height=" + win_height + ",top=" + y_offset + ",width=" + win_width + ",scrollbars=yes,resizable=yes,menubar="+menubar+",toolbar="+toolbar;
			window.open(src, '', aStr );
			break;
		}
		case "modeless":
		{
		 	aStr = "dialogLeft:" + x_offset + "px; dialogHeight:" + win_height + "px; dialogTop:" + y_offset + "px; dialogWidth:" + win_width + "px; resizable:'yes'; status:'no'"; 
			window.showModelessDialog(src, null, 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, null, aStr);
			break;
		}
	}
	if (returnwin) return newwin; 	
}

// Find an object's offsetTop and offsetLeft relative to the BODY tag, returns an array of length 2.
function FindObjPos(obj)
{
 	var objLeft   = obj.offsetLeft;
 	var objTop    = obj.offsetTop;
 	var objParent = obj.offsetParent;
 	while( objParent.tagName.toUpperCase() != "BODY" )
 	{
	   	objLeft  += objParent.offsetLeft;
	   	objTop   += objParent.offsetTop;
	   	objParent = objParent.offsetParent;
	}
	var objPos = new Array(objLeft, objTop);
	return objPos;
}

/*----------------Drag and Drop-----------------------------------------*/
// To use, you must have an abosultely-positioned visibility:hidden div on the page.
// attach StartDrag to the onmousedown event of the object you want to drag.
// attach StartDrop to the onmouseup event of same object.
// attach FollowMouse to the onmousemove event of the same object.
// the object to be drag must also have the following attributes: eventoffsetX='-999' eventoffsetY='-999' backgroundcolor='' cursorstyle=''
// for example, see custom tag CF_ManageLists

// obj: object to be drag
// bgcolor: background color of dragged object when active
// followobj: a mirror of the dragged object that will follow mouse
// followHTML: innerHTML of followobj
function StartDrag(obj, bgcolor, followobj, followHTML)
{
		obj.setCapture(true);
		obj.backgroundcolor = obj.style.backgroundColor;
		obj.cursorstyle = document.body.style.cursor;
		var srcoffset=new Array(0,0); // to store the offset of event.srcElement from obj; event.offset is measured to the parent container (eg div, button, img)
		if (event.srcElement!=obj && (event.srcElement.tagName=="DIV" || event.srcElement.tagName=="IMG"))
			srcoffset=FindObjPos(event.srcElement,obj.tagName); //this may not work for nested tags (eg div within a div within a div)
		obj.eventoffsetX=event.offsetX+srcoffset[0];
		obj.eventoffsetY=event.offsetY+srcoffset[1];;
		obj.style.backgroundColor = bgcolor;
		if (request.appversion >= 6) document.body.style.cursor = 'move';
		var objPos = FindObjPos(obj);		
		followobj.style.posTop=objPos[1];
		followobj.style.posLeft=objPos[0];
		followobj.innerHTML=followHTML;
		followobj.style.visibility="visible";
//document.all("test").innerHTML="offsetparent="+event.srcElement.offsetParent.tagName+";display="+event.srcElement.currentStyle.display+"; tag="+event.srcElement.tagName+"; scrollLeft="+document.body.scrollLeft+"; clientX="+event.clientX+"; eventoffsetX="+obj.eventoffsetX+";offsetParentX="+event.srcElement.offsetLeft; 
}
function StartDrop(obj, followobj)
{
	if (obj.eventoffsetX!='-999')
	{
		obj.releaseCapture();
		obj.style.backgroundColor = obj.backgroundcolor;
		document.body.style.cursor=obj.cursorstyle; 
		followobj.style.visibility="hidden";
		followobj.style.posLeft=0;
		followobj.style.posTop=0;
		obj.cursorstyle='';
		obj.backgroundcolor = '';
		obj.eventoffsetX='-999';
		eventoffsetY='-999';
	}
}
function FollowMouse(obj, followobj)
{
if (obj.eventoffsetX!='-999')
	{
	//document.all("test").innerHTML="scrollLeft="+document.body.scrollLeft+"; clientX="+event.clientX+"; eventoffsetX="+obj.eventoffsetX; 
	followobj.style.posLeft=document.body.scrollLeft+event.clientX-obj.eventoffsetX;
	followobj.style.posTop=document.body.scrollTop+event.clientY-obj.eventoffsetY; 
	}
}
/*-----------------------------------------------------------------------*/


/*----------------Context Menu------------------------------------------*/
function showCtxMenu(objname,ctxval,pos,nocap)
{
	/* POS:1 - At Object, POS:2 - Center of screen, else: - At Mouse */
	var obj=document.getElementById(objname);
	obj.ctxVal = ctxval;
	obj.ctxSel = null;
	obj.style.display="block";
	if(pos==1)
	{
		// At source obj position
		obj.style.left=obj.style.left;//document.body.scrollLeft+event.clientX-event.offsetX;
		obj.style.top=obj.style.top;//document.body.scrollTop+event.clientY-event.offsetY;
		if(obj.style.top-document.body.scrollTop+obj.clientHeight > document.body.clientHeight)
			obj.style.top=document.body.clientHeight-obj.clientHeight+document.body.scrollTop-2;
	} else if (pos==2)
	{
		// Center of screen
		obj.style.left=document.body.scrollLeft+(document.body.clientWidth-obj.clientWidth)/2;
		obj.style.top=document.body.scrollTop+(document.body.clientHeight-obj.clientHeight)/2;
		if(obj.style.top-document.body.scrollTop+obj.clientHeight > document.body.clientHeight)
			obj.style.top=document.body.clientHeight-obj.clientHeight+document.body.scrollTop-2;
	
	} else
	{
		// At Mouse location
		if(!window.event && arguments.length==5) event=arguments[4]; // for ff compatibility, pass in the event 
		obj.style.left = document.body.scrollLeft + event.clientX;
		obj.style.top = document.body.scrollTop + event.clientY;
		if (event.clientY + obj.clientHeight > document.body.clientHeight) 
			obj.style.top = document.body.clientHeight - obj.clientHeight + document.body.scrollTop - 4;
		if (event.clientX + obj.clientWidth > document.body.clientWidth) 
			obj.style.left = document.body.clientWidth - obj.clientWidth + document.body.scrollLeft - 4;
	}
	if(nocap!=1)
		obj.setCapture();
	// useful if there is any onkeypress events needed to be coded (i.e. press escape to close popup)
	if(window.keyPressHandler){
		obj.onkeypress=window.keyPressHandler;
		obj.focus();
	}
	return false;
}
function toggleCtxMenu(obj)
{
	var e = (window.event)? event.srcElement:obj.id; 
	while(e!=null)
	{
		switch(e.className)
		{
			case "clsCtxMenuItem": e.className="clsCtxMenuHlight"; obj.ctxSel=e; return;
			case "clsCtxMenuItem2": e.className="clsCtxMenuHlight2"; obj.ctxSel=e; return;
			case "clsCtxMenuHlight": e.className="clsCtxMenuItem"; if(obj.ctxSel==e) obj.ctxSel=null; return;
			case "clsCtxMenuHlight2": e.className="clsCtxMenuItem2"; if(obj.ctxSel==e) obj.ctxSel=null; return;
			default:
				e=e.parentElement;
		}
	}
}
function clickCtxMenu(obj,itm)
{
	closeCtxMenu(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 closeCtxMenu(obj)
{
	if(typeof(obj)=="string")
		obj=document.getElementById(obj);
	obj.style.display="none";
	if (obj.releaseCapture)
		obj.releaseCapture();
}

/*----------------Countdown------------------------------------------*/
var CountdownIntervalID;
function SetCountdown(isRearrange)
{
clearInterval(CountdownIntervalID);
Countdown();
CountdownIntervalID=setInterval('Countdown(false)',60*1000);
}

function Countdown(isRearrange)
{
if (isRearrange !==null)
	if (isRearrange == false)
	{
	var len=Row.length;
	for (n=0; n<len; n++) Row[n].countdown -= 1;
	}
var countdown=document.all("countdown");
var countdownminutes=document.all("countdownminutes");
if(countdown!==null)
	{
	var lenA=countdown.length;
	var lenB=countdownminutes.length;
	if (lenA == null){lenA=1; lenB=1; countdown[0]=countdown; countdownminutes[0]=countdownminutes;}
	if (countdown[0] !== null)
		{
		for (n=0; n<lenA; n++) 
			{
			if (countdownminutes[n].value < 2)
				countdown[n].innerHTML = "soon";
			else
				countdown[n].innerHTML = (parseInt(countdownminutes[n].value/(24*60))>0?(parseInt(countdownminutes[n].value/(24*60))+"&nbspd "):"") + (parseInt((countdownminutes[n].value%(24*60))/60)>0?(parseInt(((countdownminutes[n].value%(24*60))/60))+"&nbsph "):"") + ((countdownminutes[n].value%(24*60))%60)+"&nbspmin ";
			countdownminutes[n].value -= 1;
			}
		}
	}
}

/*----------Clock----------------------------------------------*/

var timerID = null;
var stat = false;
var seconds;
var minutes;
var hours;

function GetSysTime(now)
{
seconds = now.getSeconds();
minutes = now.getMinutes();
hours = now.getHours();
}

function clock() 
{
var ampm; 
var tmp;
  if (seconds>=59){
    seconds=0
    if (minutes>=59){
	  minutes=0
	  if (hours>=23){hours=0}else{hours++}
	}
	else {
	  minutes++
	}
  }
  else {
	seconds++
  }
  if (hours > 12)
  	{tmp = hours - 12; ampm = "PM";}
  else {ampm = (hours==12?"PM":"AM"); tmp = (hours==0?12:hours);} 
  tmp += ((minutes < 10) ? ":0" : ":") + minutes;
  tmp += ((seconds < 10) ? ":0" : ":") + seconds + " " + ampm;
  document.all("clock").innerHTML = tmp;
}

function startClock() 
{
  clock();
  setInterval('clock()', 1000);
}

/*-----------Form Validation etc---------------------------------------------------*/


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="";
	// Obtain val for all sort of form objs
	if(obj.type=="radio")
	{
		var objlist=document.all(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 "should be specified.";
		} else 
		{
			if(val=="")
				return "should be specified.";
		}
	}
	if(val=="")
		return "";
	// Otherwise check if compliant to other flags
	var ival=parseInt(val,10);
	ver=obj.getAttribute("CHKINT");
	if (ver!=null)
		if(Trim(val)!=ival.toString())
			return "should be an integer.";
	ver=obj.getAttribute("CHKMIN");
	if (ver!=null)
		if(ival<parseInt(ver,10))
			return "should be more than "+ver+".";
	ver=obj.getAttribute("CHKMAX");
	if (ver!=null)
		if(ival>parseInt(ver,10))
			return "should be less than "+ver+".";
	ver=obj.getAttribute("CHKDATE");
	if (ver!=null)
	{
		var dt=ParseDate(val);
		if(dt!=null)
		{
			if(ver=="TODAY" && sysdt!=null && dt>sysdt)
				return "should be a valid date not later than today.";
		} else
			return "should be a valid date.";
	}
	return "";
}

function FormVerify(form)
{
	var col=form.elements;
	var nm,ret,obj;
	
	if(col!==null)
	{
		var len=col.length;
		if(len!==null)
		{
			for(var t=0;t<len;t++)
			{
				obj=col[t];
				if(obj.disabled || IsDisplayed(obj)==false || obj.type=="")
					continue;
				ret=FormObjVerify(obj);
				if(ret!=="")
				{
					nm=obj.CHKNAME;
					if(nm==null)
					{
						// Check for preceding text first
						nm=obj.getAdjacentText("beforeBegin");
						if(nm!=null)
							nm=Trim(nm);
						if(nm==null||nm=="")
						{
							var ptd=obj.parentElement;
							if(ptd.tagName=="TD")
							{
								var ptd=ptd.previousSibling;
								if(ptd!=null && ptd.tagName=="TD")
									nm=ptd.innerText;
							}
						}
					}
					if(nm==null) nm="Value highlighted";
					obj.focus();
					alert(nm+" "+ret);
					if((obj.tagName=="INPUT" && obj.type=="text") ||
						obj.tagName=="TEXTAREA")
						obj.select();
					return false;
				}
			}
		}
	}
	return true;
}

function MrmPreprocessFormInner(frm,doreqonly)/*SVC*/
{
	// Inner routine for preprocessing forms
	var col,len,t,obj2,str;
	if(frm.onreset==null)
		frm.onreset=new Function("event.returnValue=false;");
	col=frm.elements;
	len=col.length;
	if(len!=null)
		for(t=0;t<len;t++)
		{
			obj2=col[t];
			// Preprocess 1: Check for required highlighting
			if(obj2.type!="checkbox" && obj2.type!="radio" && obj2.type!="")
				if(FormObjVerify(obj2)!="" && obj2.disabled!=true && obj2.style.backgroundColor!='#f2cccc')
				{
					obj2.setAttribute("BKGROUND",obj2.style.backgroundColor);
					obj2.style.backgroundColor='#f2cccc';
				}
			if(doreqonly!=1)
			{
			str=obj2.getAttribute("MRMOBJ");
			if(str!=null && str!="")
			{
				str=str.toUpperCase();
				// Preprocess 2: MRMOBJ=DATE or CALDATE
				if(str=="DATE" || str=="CALDATE")
				{
					if(obj2.onblur==null)
						obj2.onblur=new Function("ObjDate(this);");
					if(obj2.maxLength=="" || obj2.maxLength==null || obj2.maxLength>1000)
						obj2.maxLength=10;
					if(str=="CALDATE")
					{
						sid=obj2.name; 
						if(sid==null || sid=="")
							sid=obj2.id;
						if(sid!=null && sid!="")
						{
							if(obj2.onkeydown==null && obj2.onkeyup==null)
							{
								obj2.onkeydown=new Function("CalScrollKey(\""+sid+"\");");
								obj2.onkeyup=new Function("CalScrollKey(\""+sid+"\");");
							}
							obj2.insertAdjacentHTML("afterEnd","&nbsp;"+CalGenScript(sid,1));
						}
					}
				}
				// Preprocess 3: MRMOBJ=TEXTAREA
				if(str=="TEXTAREA")
				{
					if(obj2.onblur==null)
						obj2.onblur=new Function("ObjText(this);");
				} 
			}
			}
		}
}
function MrmPreprocessForm(frm)/*SVC*/
{
	// 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);
	
}
function DoReq(obj)/*SVC*/
{
	var tgname,col,len,obj2,bkcolor;
	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(FormObjVerify(obj2)!="" && obj2.disabled!=true && obj2.style.backgroundColor!='#f2cccc')
					{
						obj2.setAttribute("BKGROUND",obj2.style.backgroundColor);
						obj2.style.backgroundColor='#f2cccc';
					}
			}
		}
	} else
	{
		bkcolor=obj.BKGROUND;
		if(obj.type!="checkbox" && obj.type!="radio")
		{
			if(FormObjVerify(obj)=="" || obj.disabled==true)
			{
				bkcolor=obj.BKGROUND;
				if(bkcolor!=null)
				{
					obj.style.backgroundColor=bkcolor;
					obj.removeAttribute("BKGROUND");
				}
			}
			else if(obj.style.backgroundColor!='#f2cccc')
			{				
				obj.setAttribute("BKGROUND",obj.style.backgroundColor);
				obj.style.backgroundColor='#f2cccc';
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
// SubmitEntry
//  aForm - any form
//  url - the ACTION value in the form. If you do not specify the url, the default 
//        ACTION defined in the form will be used. When you specify the URL, you do not 
//        need to include CFID, CFTOKEN and other stuff. It will be added to it automatically
////////////////////////////////////////////////////////////////////////////////////////
function SubmitEntry(aForm, url)
{   
    if(FormVerify(aForm))
    {
        if ( url == null)
        {
            // use the original 
        }
        else
        {
            // url=url + '&' + urltoken;
            url=url ;
            aForm.action = url;
        }    
        //alert(url);
		aForm.submit();
    }
}


/////////////////////////////////////////////////////////////////////////////////////////
// ReloadParent
//  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 ReloadParent(Win)
{
	if (Win==null) Win=window.self;
	var ParWin = Win.opener; 
	if (ParWin != null)
		{
		ParWin.location.reload(true);
		ReloadParent(ParWin);
		}			
}

/////////////////////////////////////////////////////////////////////////////////////////
// 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);
		}			
}


/////////////////////////////////////////////////////////////////////////////////////////
// CheckAll
//  The Object ID will be used to select all the rest of the objects wth the same id
//      If a button has an ID=ABCD
//          All checkbox with ID=abcd will be checked
////////////////////////////////////////////////////////////////////////////////////////
function CheckAll(str)
{
    var all = document.all(str.id);
    if (str.value == "Uncheck")
    {
        setting = 0;
        str.value = "Check";
    }
    else
    {
        setting = 1;
        str.value = "Uncheck";
    }    
    if (all != null)
    {
        len = all.length;
        if (len==null)
            len=1;
        for (var i=0; i<len; i++)
        {   
            obj=(len==1?all:all[i]);
            obj.checked=setting;
        }
    }
}    
/*-------------------------------------------------------------------------*/
/////////////////////////////////////////////////////////////////////////////////////////
// gotoURL
//  Direct the browser to the specific page
////////////////////////////////////////////////////////////////////////////////////////
function gotoURL(str)
{
    if (str!=null)
        window.location=str;
}
function MM_Highlight(row, highlightclass)
{
	if (highlightclass==null) highlightclass='clsHighlight1';
    row.className=highlightclass;   
}
function MM_Dehighlight(row, name)
{
    row.className=name;   
}





//to hide applets and select elements which always show on top of absolutely positioned objects, an internet explorer bug
function StartHide(id, exception)
{
	var obj=document.getElementById(id);
	if(obj!=null && (obj.style.visibility=="show" || obj.style.visibility=="visible" || obj.style.display=="block"))
	{
		HideElements('SELECT', obj, exception);
		HideElements('APPLET', obj, exception);
	}
}

function ShowElements(tagname)
{
var element;
	for( i = 0; i < document.all.tags(tagname).length; i++ )
	{
		element = document.all.tags(tagname)[i];
		if( !element || !element.offsetParent )
			continue;
		element.style.visibility = "";
	}
}

/* hides elements that overlaps with obj*/
function HideElements(tagname, obj, exception)
{
var element, elementPos, elementHeight, elementWidth;
	for( i = 0; i < document.all.tags(tagname).length; i++ )
    {
	  element = document.all.tags(tagname)[i];
	  if( !element || !element.offsetParent || (exception!=null && element.name==exception) || (exception!=null && element.id==exception))
      {
        continue;
      }
	  elementPos=FindObjPos(element);		  	    
      elementHeight = element.offsetHeight;
      elementWidth = element.offsetWidth;

      if(( obj.offsetLeft + obj.offsetWidth ) <= elementPos[0] );
      else if(( obj.offsetTop + obj.offsetHeight ) <= elementPos[1] );
      else if( obj.offsetTop >= ( elementPos[1] + elementHeight ));
      else if( obj.offsetLeft >= ( elementPos[0] + elementWidth ));
      else
      {
		element.style.visibility = "hidden";
      }
    }
}

// Find an object's offsetTop and offsetLeft relative to the a certain parent tag (defaults to BODY tag), returns an array of length 2.
function FindObjPos(obj, parenttag)
{
 	if (parenttag==null) parenttag="BODY";
	var objLeft   = obj.offsetLeft;
 	var objTop    = obj.offsetTop;
 	var objParent = obj.offsetParent;
 	while( objParent.tagName.toUpperCase() != parenttag )
 	{
	   	objLeft  += objParent.offsetLeft;
	   	objTop   += objParent.offsetTop;
	   	objParent = objParent.offsetParent;
	}
	var objPos = new Array(objLeft, objTop);
	return objPos;
}

/////////////////////////////////////////////////////////////////////////////////////////
// THIS SECTION IS TO POLULATE NEXT LEVEL OF SELECT BOXES FOR THE MULTI LEVEL SELECT  //
// added by hiewming 24/3/2004														  //
/////////////////////////////////////////////////////////////////////////////////////////
// create hierarchical array
function cSelectNew(name, id) {
   this.name = name;
   this.id = id;
   this.child = new Array();   
}
//NOTE: the parameter 'ArrName' is reguired only for the first level,
// the parameter, 'Nnextobj' is the another level below nextobj, if exist, should be sent.

function CSSelectChange(me,nextobj,Nnextobj,ArrName) 
{   
   	var curIndex = me.selectedIndex;	
	if (me.selectedIndex == 0 && nextobj && Nnextobj) {	
		CSDeleteSelect(nextobj);
		CSDeleteSelect(Nnextobj);
	}
	else
	{		
	    if (ArrName)  {			//check if arrname is passed in, if yes, means first level
			me.setArr=ArrName;		
			curArr=eval(me.setArr+'['+curIndex+'].child');	  // get the current array being used	
						//if (ArrName=='Ports') alert(Nnextobj);
		}
		else  {				//if no, means the next level
			curArr=me.setArr[curIndex].child;   //get the current array being used				
		}	
		nextobj.setArr=curArr;	//set the current obj to the next obj			
		nextobj.options.length = 1;			
		
	    for (var i=0; i<curArr.length; ++i) {				
	        nextobj.options[i] = new Option(curArr[i].name, curArr[i].id);				
	    }	
		if (nextobj.length == 2)		//check if the next level have only one option
		{
			nextobj.options[1].selected = true;		
			if (nextobj.selectedIndex == 1 && Nnextobj)    //if only one option and
				CSSelectChange(nextobj,Nnextobj);		   //there is a level after that
		}	
		else
		{
		    nextobj.options[0].selected = true;  		
		}		
		if (nextobj.selectedIndex == 0 && Nnextobj)      //delete all options for 
			CSDeleteSelect(Nnextobj);		             //next level after nextobj
	}	
}

function CSDeleteSelect(me) 
{	
	for (var i=0; i<me.options.length; ++i) {				
        me.options[i] = new Option();
    }	
}


/* Check the date format if loss date is selected */
function checkoption()
{	
	var selected = document.all("SearchType");	
	var textfield = document.all("SearchTxt");
	if (selected.options[selected.selectedIndex].value == 5)
	{
		ObjDate(textfield);
	}	
}


/*------------------------------------------------------------------
This function is a wrapper to make an http get request 
-------------------------------------------------------------------*/
main.objhttp = new Array(); 
function HTTPRequest(url, async, readyfunction, arrname)
{
	try
	{
		main.objhttp[arrname] = new ActiveXObject("Microsoft.xmlhttp");
	}
	catch (exception)
	{
		if (exception.number & 0x7FFFFFFF == 0x000A01AD)
			alert("A required ActiveX object (XMLHTTP) that comes default with MSIE5.0 and above is not installed.\nPlease reinstall Internet Explorer for this to work before proceeding.");
		else
	    	// it wasn't the error we thought it was, pass it up the chain
			alert("You seemed to have disabled the use of ActiveX objects.\nPlease turn it back on from\nTools/Internet Options/Security/Custom Level\nand refresh this page.");
		return;
	}
	main.objhttp[arrname].onreadystatechange=getHTTPRequestHandler(arrname, readyfunction);
	main.objhttp[arrname].open("GET", url, async);
	main.objhttp[arrname].send();
	
}
/*------------------------------------------------------------------
This function will call the handling function (readyfunction) so that the http object name (arrname) could be passed over
* HTTP object name was previously hardcoded in its local handling function, which will not work properly if
  there are more than one request called simultaneously using the same handling function but on different objects.
* Handling function does not need to check for ready state anymore.
-------------------------------------------------------------------*/
function getHTTPRequestHandler(arrname, readyfunction){
	return function(){
		if(main.objhttp[arrname] != null){
	    	if(main.objhttp[arrname].readyState == 4){
  	    		if(main.objhttp[arrname].status == 200)
					readyfunction(arrname);
      			else
					alert("Transmission Error\nPossible reasons for failure:\n- The Internet line is slow or congested and the request has timed-out.\n-The Internet connection was broken or timed-out during sending.\nPlease reload the page to retry.\nPlease take note that any unsaved data will be discarded.");
  	  		}
		}
	}
}


/* allan 4/4/2008 : script based on NM - check validity of hand phone no */
function DoHPhone(obj)
{
	var r,re;
	Despace(obj);
	r=obj.value.toUpperCase();
	if(r.length>0)
	{
		re=/[0-9][0-9][0-9][0-9][0-9][0-9][0-9]/
		if(r.search(re)<0 || r=="0000000")
		{
			alert("Invalid handphone number - must be 7 numerical digits.");
			obj.value="";
			obj.select();
		}
	}
}

