/*
The following class names associate with different actions

PhoneField			tools_PhoneFieldFocus, tools_PhoneFieldBlur
DateField				tools_DateFieldFocus, tools_DateFieldBlur
PostalField			tools_PostalFieldFocus, tools_PostalFieldBlur
CurrencyField		tools_CurrencyFieldFocus, tools_CurrencyFieldBlur
*/

var tools_AttachOnloadEvent;
try
{
	if(tools_AttachOnloadEvent==undefined) tools_AttachOnloadEvent=true;
}
catch(e)
{
	tools_AttachOnloadEvent=true;
}

var WhenFocus=0,WhenBlur=1,DateFormat="mm/dd/yyyy",TimeFormat="a/p",LocalLanguage="E";
var isClosing=false,insideDoc=true,tabPressed=false,shiftPressed=false,focusTimes=0,
		lastActiveObject=null,isWindowClosing=true;
var	pageElementAry=null;
var	tools_DocLoadedPtr=null;
var tbWithoutBorder=0,tbWithBorder=1

var GridInitialCallback=null;

var GridHeadInitTop=new Array(2);
GridHeadInitTop[0]=new Array();
GridHeadInitTop[1]=new Array();

var CalendarStyleFile="";

var SeekByText=0,SeekByHTML=1,SeekByName=2,SeekByClassName=3,SeekByID=4,SeekPartial=0x1000 // The definition of the SeekWay.
var FindFirst=0,FindAll=1;  // The definition of the findOption of function findObject.

if(isFrenchVersion()) LocalLanguage="F";

if(tools_AttachOnloadEvent)
{
	if(isIE5())
		window.attachEvent('onload',tools_DocLoaded);
	else
		tools_DocLoadedPtr=tools_DocLoaded;
}

function isFrenchVersion()
{
	var DocumentLocation=document.location.href.toLowerCase();
	if((DocumentLocation.indexOf("french")>0)||(DocumentLocation.indexOf("_fr")>0))
		return true;
	else
		return false;
}

function isIE()
{
	var name=navigator.appName.toLowerCase(),index=name.indexOf("microsoft");
	
	if(index>=0)
		return true;
	else
		return false;
}

function isIE5()
{
	var version=navigator.appVersion.toLowerCase(),index=version.indexOf("msie");
	
	if(index>=0)
	{
		var verNo=new Number(version.substr(index+5,1));
		if(verNo>=5)
			return true;
		else
			return false;
	}
	else
		return false;
}

function tools_CancelMouseover()
{
	try
	{
		focusTimes=0;
		isClosing=true;
		lastActiveObject=document.activeElement;
	}
	catch(e)
	{
	}
}

function tools_CancelMouseout()
{
	try
	{
		isClosing=false;
	}
	catch(e)
	{
	}
}

function tools_DocLoaded()
{
	if(pageElementAry!=null) changePageElementsHeight();
	
	if(isIE5())
	{
		document.attachEvent('onkeydown',tools_DocKeydown);
		document.attachEvent('onkeyup',tools_DocKeyup);
		document.attachEvent('onmouseover',tools_DocMouseover);
		document.attachEvent('onmouseout',tools_DocMouseout);
		document.attachEvent('onclick',tools_DocClick);
//		document.attachEvent('onselectstart',tools_DocSelectStart);
	}
	else
	{
		if(document.onkeydown==null)
			document.onkeydown=tools_DocKeydown;
		if(document.onkeyup==null)
			document.onkeyup=tools_DocKeyup;
		if(document.onmouseover==null)
			document.onmouseover=tools_DocMouseover;
		if(document.onmouseout==null)
			document.onmouseout=tools_DocMouseout;
		if(document.onclick==null)
			document.onclick=tools_DocClick;
/*
		if(document.onselectstart==null)
			document.onclick=tools_DocSelectStart;
*/
	}

	var objArray=new Array(3);
	objArray[0]=document.getElementsByTagName("INPUT");
	objArray[1]=document.getElementsByTagName("TABLE");
	objArray[2]=document.getElementsByTagName("TD");

	for(var i=0;i<objArray.length;i++)
	{
		for(var j=0;j<objArray[i].length;j++)
		{
			var obj=objArray[i][j];

			if(obj.tagName.toLowerCase()=="input")
			{
				if((obj.type=="button")&&((obj.value.toLowerCase()=="cancel")||(obj.value.toLowerCase()=="reset")))
				{
					if(isIE5())
					{
						if(obj.onmouseover==null)
							obj.attachEvent('onmouseover',tools_CancelMouseover);
						if(obj.onmouseout==null)
							obj.attachEvent('onmouseout',tools_CancelMouseout);
					}
					else
					{
						if(obj.onmouseover==null)
							obj.onmouseover=tools_CancelMouseover;
						if(obj.onmouseout==null)
							obj.onmouseout=tools_CancelMouseout;
					}
				}
				else if(obj.type=="text")
					obj.autocomplete="off";
			}

			switch(obj.className.toLowerCase())
			{
				case "cancelbutton":
				case "cancelconstraint":
					if(isIE5())
					{
						if(obj.onmouseover==null)
							obj.attachEvent('onmouseover',tools_CancelMouseover);
						if(obj.onmouseout==null)
							obj.attachEvent('onmouseout',tools_CancelMouseout);
					}
					else
					{
						if(obj.onmouseover==null)
							obj.onmouseover=tools_CancelMouseover;
						if(obj.onmouseout==null)
							obj.onmouseout=tools_CancelMouseout;
					}
					break;
			
				case "phonefield":
					if(isIE5())
					{
						if(obj.onfocus==null)
							obj.attachEvent('onfocus',tools_PhoneFieldFocus);
						if(obj.onblur==null)
							obj.attachEvent('onblur',tools_PhoneFieldBlur);
					}
					else
					{
						if(obj.onfocus==null)
							obj.onfocus=tools_PhoneFieldFocus;
						if(obj.onblur==null)
							obj.onblur=tools_PhoneFieldBlur;
					}
					break;

				case "timefield":
					if(isIE5())
					{
						if(obj.onfocus==null)
							obj.attachEvent('onfocus',tools_TimeFieldFocus);
						if(obj.onblur==null)
							obj.attachEvent('onblur',tools_TimeFieldBlur);
					}
					else
					{
						if(obj.onfocus==null)
							obj.onfocus=tools_TimeFieldFocus;
						if(obj.onblur==null)
							obj.onblur=tools_TimeFieldBlur;
					}
					break;

				case "datefield":
					if(isIE5())
					{
						if(obj.onfocus==null)
							obj.attachEvent('onfocus',tools_DateFieldFocus);
						if(obj.onblur==null)
							obj.attachEvent('onblur',tools_DateFieldBlur);
					}
					else
					{
						if(obj.onfocus==null)
							obj.onfocus=tools_DateFieldFocus;
						if(obj.onblur==null)
							obj.onblur=tools_DateFieldBlur;
					}
					break;

				case "postalfield":
					if(isIE5())
					{
						if(obj.onfocus==null)
							obj.attachEvent('onfocus',tools_PostalFieldFocus);
						if(obj.onblur==null)
							obj.attachEvent('onblur',tools_PostalFieldBlur);
					}
					else
					{
						if(obj.onfocus==null)
							obj.onfocus=tools_PostalFieldFocus;
						if(obj.onblur==null)
							obj.onblur=tools_PostalFieldBlur;
					}
					break;

				case "sinfield":
					if(isIE5())
					{
						if(obj.onfocus==null)
							obj.attachEvent('onfocus',tools_SINFieldFocus);
						if(obj.onblur==null)
							obj.attachEvent('onblur',tools_SINFieldBlur);
					}
					else
					{
						if(obj.onfocus==null)
							obj.onfocus=tools_SINFieldFocus;
						if(obj.onblur==null)
							obj.onblur=tools_SINFieldBlur;
					}
					break;

				case "currencyfield":
					if(isIE5())
					{
						if(obj.onfocus==null)
							obj.attachEvent('onfocus',tools_CurrencyFieldFocus);
						if(obj.onblur==null)
							obj.attachEvent('onblur',tools_CurrencyFieldBlur);
					}
					else
					{
						if(obj.onfocus==null)
							obj.onfocus=tools_CurrencyFieldFocus;
						if(obj.onblur==null)
							obj.onblur=tools_CurrencyFieldBlur;
					}
					break;

				case "gridbody":
					if(isIE5())
					{
						if(obj.onkeydown==null)
							obj.attachEvent('onkeydown',tools_GridBodyKeydown);
						if(window.onfocus==null)
							window.attachEvent('onfocus',tools_GridBodyDocFocus);
					}
					else
					{
						if(obj.onkeydown==null)
							obj.onkeydown=tools_GridBodyKeydown;
						if(window.onfocus==null)
							window.onfocus=tools_GridBodyDocFocus;
					}

	//				RefreshGridBody(obj);
					break;
				
				case "gridhead":
					if(isIE5())
					{
						if(onscroll==null)
							attachEvent('onscroll',tools_DocScroll);
					}
					else
					{
						if(onscroll==null)
							onscroll=tools_DocScroll;
					}

					GridHeadInitTop[0][GridHeadInitTop[0].length++]=obj.id;
					GridHeadInitTop[1][GridHeadInitTop[1].length++]=obj.offsetTop;

					if(GridInitialCallback!=null)
						GridInitialCallback();
					break;

				case "titleemptycellwithoutrightborder":
					/*********************************************************************************************************/
					/*	In the 'onload' event, if you call the reoccurring 'findObject' function, this function would				 */
					/*	be called forever, it should be the bug of IE. It is the reason why to use the 'setTimeout' to			 */
					/*	call the other function 'setTitleEmptyCellWidth' to achieve the width setting of the titleEmptyCell. */
					/*********************************************************************************************************/

					TitleEmptyCellArray[TitleEmptyCellArray.length]=obj;
					setTimeout("setTitleEmptyCellWidth()",100);
					break;
			}
		}
	}
}

var TitleEmptyCellArray=new Array();
function setTitleEmptyCellWidth()
{
	var theTitleEmptyCellArray;
	if(arguments.length>0)
		theTitleEmptyCellArray=new Array(arguments[0]);
	else
		theTitleEmptyCellArray=TitleEmptyCellArray;

	for(var i=0;i<theTitleEmptyCellArray.length;i++)
	{
		var obj=theTitleEmptyCellArray[i],parentTable=getParentTable(obj),
				titleObjAry=findObject(parentTable,"titleContentCell",SeekByClassName|SeekPartial,FindAll),
				titleWidth=0;

		for(var i=0;i<titleObjAry.length;i++)
			titleWidth+=titleObjAry[i].offsetWidth;

		obj.style.width=parentTable.offsetWidth-titleWidth;
	}
}

function tools_DocKeydown()
{
	try
	{
		if(event.keyCode==9)
		{
			tabPressed=true;
			lastActiveObject=document.activeElement;
		}
		else
			tabPressed=false;

		if(event.shiftKey)
			shiftPressed=true;
		else
			shiftPressed=false;
	}
	catch(e)
	{
	}
}

function tools_DocKeyup()
{
	try
	{
		lastActiveObject=document.activeElement;
	}
	catch(e)
	{
	}
}

function tools_DocMouseover()
{
	try
	{
		insideDoc=true;
	}
	catch(e)
	{
	}
}

function tools_DocMouseout()
{
	try
	{
		focusTimes=0;
		insideDoc=false;
		lastActiveObject=document.activeElement;
	}
	catch(e)
	{
	}
}

function tools_DocClick()
{
	try
	{
		tabPressed=false;
		shiftPressed=false;
		lastActiveObject=document.activeElement;
	}
	catch(e)
	{
	}
}

function isTabElement(tagName)
{
	var result;
	
	switch(tagName.toUpperCase())
	{
		case "A":
		case "BODY":
		case "BUTTON":
		case "FRAME":
		case "IFRAME":
		case "INPUT":
		case "ISINDEX":
		case "OBJECT":
		case "SELECT":
		case "TEXTAREA":
			result=true;
			break;
			
		default:
			result=false;
	}
	
	return result;
}

/*
function tools_DocSelectStart()
{
	event.returnValue=false;
}
*/

function findPreviousObject()
{
	var docObjects=document.all,oElement=event.srcElement,iIndex=oElement.sourceIndex;

  if(iIndex-1>0)
  {
		for(var i=iIndex-1;i>=0;i--)
		{
	    var sTagName=docObjects[i].tagName;
	    if(isTabElement(sTagName))
				return docObjects[i];
		}
  }

	return null;
}  

function findNextObject()
{
	var docObjects=document.all,oElement=event.srcElement,iIndex=oElement.sourceIndex;

  if(iIndex+1<docObjects.length)
  {
		for(var i=iIndex+1;i<docObjects.length;i++)
		{
      var sTagName=docObjects[i].tagName;
	    if(isTabElement(sTagName))
				return docObjects[i];
		}
  }
   
  return null;
}

function isSpecialField(direction)
{
	var obj;
	if(direction!=shiftPressed)
		obj=findPreviousObject();
	else
		obj=findNextObject();

	result=false;
	if(obj!=null)
	{
		switch(obj.className.toLowerCase())
		{
			case "phonefield":
			case "datefield":
			case "postalfield":
				result=true;
				break;
		}
	}
	
	return result;
}

function compactCurrency(value)
{
	if(value!="")
	{
		while(value.charAt(0)=='$')
			value=value.substring(1,value.length);

		if(value!="")
		{
			var i,part=value.split(",");
	
			value="";
			for(i=0;i<part.length;i++)
				value+=part[i];
	
			return value;
		}
		else
			return "";
	}
	else
		return "";
}

function composeCurrency(value)
{
	if(value!="")
	{
		var index=value.indexOf(".");
		if(index==-1)
			value+=".";
			
		var part=value.split(".");
		if(part[0]=="")
			part[0]="0";

		var partLen1=part[0].length,partLen2=part[1].length;
		var i=Math.floor(partLen1/3),j=partLen1%3;
		var leading=part[0].substr(0,j);
		part[0]=part[0].substr(j,partLen1-j);
	
		var k,newPart=new Array(i);
		for(k=0;k<i;k++)
			newPart[k]=part[0].substr(k*3,3);
	
		if(leading=="")
			part[0]="";
		else
			part[0]=leading;
		
		for(k=0;k<i;k++)
		{
			if(part[0]!="")
				part[0]+=",";
			part[0]+=newPart[k];
		}

		for(k=0;k<2-partLen2;k++)
			part[1]+="0";

		if((part[1]=="00")&&(arguments.length==2)&&(!arguments[1]))
			return "$"+part[0];
		else
			return "$"+part[0]+"."+part[1];
	}
	else
		return "";
}

function tools_CurrencyFieldFocus()
{
	var obj=event.srcElement;

	if(obj.value!="")
	{
		obj.value=compactCurrency(obj.value);
		fieldSelectedWhenTextFieldFocused(obj);
	}
}

function tools_CurrencyFieldBlur()
{
	var obj=event.srcElement;

	if(obj.value!="")
	{
		if(eval(document.all(obj.name)))
		{
			if(eval(document.all(obj.name+"LowRange"))||eval(document.all(obj.name+"HighRange")))
			{
				if(eval(document.all(obj.name+"LowRange")))
				{
					var lowRange=new Number(document.all(obj.name+"LowRange").value);
					if(lowRange>=Math.ceil(new Number(obj.value)))
					{
						obj.focus();

						if(LocalLanguage=="E")
							alert("The valid value should be greater than "+lowRange+", please reenter.");
						else
							alert("Donnée non valide – montant doit être plus de "+lowRange+", SVP entrer de nouveau.");

						fieldSetCaretWhenTextFieldFocused(obj);
						return;
					}
				}

				if(eval(document.all(obj.name+"HighRange")))
				{
					var highRange=new Number(document.all(obj.name+"HighRange").value);
					if(highRange<=Math.floor(new Number(obj.value)))
					{
						obj.focus();

						if(LocalLanguage=="E")
							alert("The valid value should be less than "+highRange+", please reenter.");
						else
							alert("Donnée non valide – montant doit être moins de "+highRange+", SVP entrer de nouveau.");

						fieldSetCaretWhenTextFieldFocused(obj);
						return;
					}
				}

				obj.value=composeCurrency(obj.value);
			}
			else
				obj.value=composeCurrency(obj.value);
		}
		else
			obj.value=composeCurrency(obj.value);
	}

/*
	Since the currency field will not cause any error message displayed when the blur event occurs,
	the 'fieldSetCaretWhenTextFieldFocused' method must not be called.
*/
//		fieldSetCaretWhenTextFieldFocused(obj);
}

function compactPhone(phoneNo)
{
	var str="";
	
	if(phoneNo!="")
	{
		var i,j,checkChar=new Array("(",")","-","/"," ");
	
		str=phoneNo;
		for(i=0;i<checkChar.length;i++)
		{
			var	phoneParts=str.split(checkChar[i]);
			if(phoneParts.length>0)
			{
				str="";
				for(j=0;j<phoneParts.length;j++)
					str+=phoneParts[j];
			}
		}
	}

	return str;
}

function composePhone(phoneNo)
{
	if(phoneNo!="")
	{
		var phoneParts=getSubStrs(phoneNo,"/"),phoneLen=phoneParts[0].length;
	
		if(phoneLen==7)
			phoneParts[0]=phoneParts[0].substr(0,3)+"-"+phoneParts[0].substr(3,4);
		else if(phoneLen==10)
			phoneParts[0]="("+phoneParts[0].substr(0,3)+")"+phoneParts[0].substr(3,3)+"-"+phoneParts[0].substr(6,4);
		else if(phoneLen>10)
		{
			if(phoneParts[0].substr(0,2)=="18")
				phoneParts[0]=phoneParts[0].substr(0,1)+"-"+phoneParts[0].substr(1,3)+"-"+phoneParts[0].substr(4,3)+"-"+phoneParts[0].substr(7,4);
			else
				phoneParts[0]="("+phoneParts[0].substr(0,3)+")"+phoneParts[0].substr(3,3)+"-"+phoneParts[0].substr(6,4)+"/"+phoneParts[0].substr(10,phoneLen-10);
		}
		
		return (phoneParts.length==1)?phoneParts[0]:(phoneParts[0]+"/"+phoneParts[1]);
	}
	else
		return "";
}

function parsePhone(option)
{
	var canParse=true;
	if(!tabPressed)
		canParse=((!isClosing)&&insideDoc)

	if(canParse)
	{
		var obj=event.srcElement;
		if(option==WhenBlur)
		{
			if(obj.value!="")
			{
				if(obj.value.length<10)
				{
					obj.focus();

					if(LocalLanguage=="E")
						alert("The valid phone number should be 10 digits or more, please reenter.");
					else
						alert("Donnée non valide – le numéro de téléphone doit être de 10 chiffres ou plus, SVP entrer de nouveau.");

					fieldSetCaretWhenTextFieldFocused(obj);
				}
				else
					obj.value=composePhone(obj.value);
			}
		}
		else
		{
			if(isSpecialField(shiftPressed))
			{
				if(focusTimes==0)
					focusTimes++;
				else
				{
					focusTimes=0;
					tabPressed=false;
				}
			}
			else
			{
				focusTimes=0;
				tabPressed=false;
			}

			if(obj.value!="")
			{
				obj.value=compactPhone(obj.value);
				fieldSelectedWhenTextFieldFocused(obj);
			}
		}
	}
}

function tools_PhoneFieldFocus()
{
	parsePhone(WhenFocus);
}

function tools_PhoneFieldBlur()
{
	parsePhone(WhenBlur);
}

function compactTime(theTime)
{
	var str="";
	
	if(theTime!="")
	{
		var i,j,checkChar=new Array(":"," ");
	
		str=theTime;
		for(i=0;i<checkChar.length;i++)
		{
			var	timeParts=str.split(checkChar[i]);
			if(timeParts.length>0)
			{
				str="";
				for(j=0;j<timeParts.length;j++)
					str+=timeParts[j];
			}
		}
	}

	return str;
}

function composeTime(theTime)
{
	var varType=typeof(theTime);
	if(varType=="string")
	{
		if(theTime!="")
		{
			if(theTime.indexOf(":")==-1)
			{
				var timeStr=theTime.substr(0,2)+":"+theTime.substr(2,2);

				if(theTime.length==6)
					timeStr=timeStr+":"+theTime.substr(4,2);

				return timeStr;
			}
			else
				return theTime;
		}
	}
	else if(varType=="object")
	{
		var iHour,iMinute,iSecond,sFormat=(arguments.length==2?arguments[1].toLowerCase():"hh:nn:ss");

		if(TimeFormat=="a/p")
		{
			var sTime=theTime.toLocaleTimeString(),index=sTime.indexOf(" "),sAMPM=sTime.substring(index+1,sTime.length),
					sTime=sTime.substring(0,index),timeArray=sTime.split(":");

			iHour=new Number(timeArray[0]).valueOf();
			iMinute=new Number(timeArray[1]).valueOf();
			iSecond=new Number(timeArray[2]).valueOf();
		}
		else
		{
			iHour=theTime.getHours();
			iMinute=theTime.getMinutes();
			iSecond=theTime.getSeconds();
		}

		var value=(iHour<10?("0"+iHour):iHour)+":"+(iMinute<10?("0"+iMinute):iMinute);
		if(sFormat=="hh:nn:ss")
			value+=":"+(iSecond<10?("0"+iSecond):iSecond);
		if(TimeFormat=="a/p")
			value+=" "+sAMPM;

		return value;
	}

	return "";
}

function getInternatinalFormatTimeStr(timeStr)
{
	if(timeStr!="")
	{
		var dValue=new Date("January 1, 2000 "+timeStr),timeParts=timeStr.split(":");

		if(timeParts.length==3)
			return (dValue.getHours()<10?("0"+dValue.getHours()):dValue.getHours())+":"+
						 (dValue.getMinutes()<10?("0"+dValue.getMinutes()):dValue.getMinutes())+":"+
						 (dValue.getSeconds()<10?("0"+dValue.getSeconds()):dValue.getSeconds());
		else
			return (dValue.getHours()<10?("0"+dValue.getHours()):dValue.getHours())+":"+
						 (dValue.getMinutes()<10?("0"+dValue.getMinutes()):dValue.getMinutes());
	}

	return "";
}

function parseTime(option)
{
	var canParse=true;
	if(!tabPressed)
		canParse=((!isClosing)&&insideDoc)

	if(canParse)
	{
		var obj=event.srcElement;
		if(option==WhenBlur)
		{
			if(obj.value!="")
			{
				if((obj.value.length<4)||(obj.value.length==5))
				{
					obj.focus();

					if(LocalLanguage=="E")
						alert("The valid time format should be 'HHNN' or 'HHNNSS', please reenter.");
					else
						alert("The valid time format should be 'HHNN' or 'HHNNSS', please reenter.");

					fieldSetCaretWhenTextFieldFocused(obj);
				}
				else
				{
					var iHour=new Number(obj.value.substr(0,2));
					var iMinute=new Number(obj.value.substr(2,2));

					if(TimeFormat.toLowerCase()=="a/p")
					{
						if((iHour<1)||(iHour>12))
						{
							if(LocalLanguage=="E")
								alert("The valid hour range should be between 1 and 12, please reenter.");
							else
								alert("The valid hour range should be between 1 and 12, please reenter.");

							fieldSetCaretWhenTextFieldFocused(obj);
							return;
						}
					}
					else
					{
						if(iHour>23)
						{
							if(LocalLanguage=="E")
								alert("The valid hour range should be between 0 and 23, please reenter.");
							else
								alert("The valid hour range should be between 0 and 23, please reenter.");

							fieldSetCaretWhenTextFieldFocused(obj);
							return;
						}
					}

					if(iMinute>59)
					{
						if(LocalLanguage=="E")
							alert("The valid minute range should be between 0 and 59, please reenter.");
						else
							alert("The valid minute range should be between 0 and 59, please reenter.");

						fieldSetCaretWhenTextFieldFocused(obj);
					}
					else
					{
						if(obj.value.length>4)
						{
							var iSecond=new Number(obj.value.substr(4,2));

							if(iSecond>59)
							{
								if(LocalLanguage=="E")
									alert("The valid second range should be between 0 and 59, please reenter.");
								else
									alert("The valid second range should be between 0 and 59, please reenter.");

								fieldSetCaretWhenTextFieldFocused(obj);
							}
							else
								obj.value=composeTime(obj.value);
						}
						else
							obj.value=composeTime(obj.value);
					}
				}
			}
		}
		else
		{
			if(isSpecialField(shiftPressed))
			{
				if(focusTimes==0)
					focusTimes++;
				else
				{
					focusTimes=0;
					tabPressed=false;
				}
			}
			else
			{
				focusTimes=0;
				tabPressed=false;
			}

			if(obj.value!="")
			{
				obj.value=compactTime(obj.value);
				fieldSelectedWhenTextFieldFocused(obj);
			}
		}
	}
}

function tools_TimeFieldFocus()
{
	parseTime(WhenFocus);
}

function tools_TimeFieldBlur()
{
	parseTime(WhenBlur);
}

function compactDate(theDate)
{
	var str="";
	
	if(theDate!="")
	{
		var i,j,checkChar=new Array("/");
	
		var str=theDate;
		for(i=0;i<checkChar.length;i++)
		{
			var	dateParts=str.split(checkChar[i]);
			if(dateParts.length>0)
			{
				str="";
				for(j=0;j<dateParts.length;j++)
					str+=dateParts[j];
			}
		}
	}

	return str;
}

function composeDate(theDate)
{
	var varType=typeof(theDate);
	if(varType=="string")
	{
		if(theDate.length>=8)
		{
			if(theDate.indexOf("/")==-1)
			{
				switch(DateFormat.toLowerCase())
				{
					case "yyyy/mm/dd":
					case "yyyy/dd/mm":
						return theDate.substr(0,4)+"/"+theDate.substr(4,2)+"/"+theDate.substr(6,2);
						break;
						
					case "mm/dd/yyyy":
					case "dd/mm/yyyy":
						return theDate.substr(0,2)+"/"+theDate.substr(2,2)+"/"+theDate.substr(4,4);
				}
			}
			else
				return theDate;
		}
		else
			return theDate;
	}
	else if(varType=="object")
	{
		var sYear=theDate.getFullYear().toString(),sMonth=(theDate.getMonth()+1).toString(),
				sDay=theDate.getDate().toString();

		sMonth=(sMonth.length==1?("0"+sMonth):sMonth);
		sDay=(sDay.length==1?("0"+sDay):sDay);

		switch(DateFormat.toLowerCase())
		{
			case "yyyy/mm/dd":
				return sYear+"/"+sMonth+"/"+sDay;
				break;

			case "yyyy/dd/mm":
				return sYear+"/"+sDay+"/"+sMonth;
				break;

			case "mm/dd/yyyy":
				return sMonth+"/"+sDay+"/"+sYear;
				break;

			case "dd/mm/yyyy":
				return sDay+"/"+sMonth+"/"+sYear;
		}				
	}
}

function parseDate(option)
{
	function getValidDateFormatMsg()
	{
		var msg="";
		if(LocalLanguage=="E")
			msg="The valid date format should be ";
		else
			msg="Utiliser le format ";

		switch(DateFormat.toLowerCase())
		{
			case "yyyy/mm/dd":
				if(LocalLanguage=="E")
					msg+="'YYYYMMDD'";
				else
					msg+="« AAAAMMJJ »";
				break;

			case "yyyy/dd/mm":
				if(LocalLanguage=="E")
					msg+="'YYYYDDMM'";
				else
					msg+="« AAAAJJMM »";
				break;

			case "mm/dd/yyyy":
				if(LocalLanguage=="E")
					msg+="'MMDDYYYY'";
				else
					msg+="« MMJJAAAA »";
				break;

			case "dd/mm/yyyy":
				if(LocalLanguage=="E")
					msg+="'DDMMYYYY'";
				else
					msg+="« JJMMAAAA »";
		}

		return msg;
	}

	var canParse=true;
	if(!tabPressed)
		canParse=((!isClosing)&&insideDoc)

	if(canParse)
	{
		var obj=event.srcElement;
		if(option==WhenBlur)
		{
			if(obj.value!="")
			{
				if(obj.value.length<8)
				{
					obj.focus();

					if(LocalLanguage=="E")
						alert("Incorrect date format. "+getValidDateFormatMsg()+", please reenter.");
					else
						alert("Format de date non valide. "+getValidDateFormatMsg()+", SVP entrer de nouveau.");

					fieldSetCaretWhenTextFieldFocused(obj);
				}
				else
				{
					var iYear,iMonth,iDay,gaMonthDays;

					switch(DateFormat.toLowerCase())
					{
						case "yyyy/mm/dd":
							iYear=new Number(obj.value.substr(0,4));
							iMonth=new Number(obj.value.substr(4,2));
							iDay=new Number(obj.value.substr(6,2));
							break;

						case "yyyy/dd/mm":
							iYear=new Number(obj.value.substr(0,4));
							iMonth=new Number(obj.value.substr(6,2));
							iDay=new Number(obj.value.substr(4,2));
							break;

						case "mm/dd/yyyy":
							iYear=new Number(obj.value.substr(4,4));
							iMonth=new Number(obj.value.substr(0,2));
							iDay=new Number(obj.value.substr(2,2));
							break;

						case "dd/mm/yyyy":
							iYear=new Number(obj.value.substr(4,4));
							iMonth=new Number(obj.value.substr(2,2));
							iDay=new Number(obj.value.substr(0,2));
					}

					gaMonthDays=new Array(/* Jan */ 31, /* Feb */ 29, /* Mar */ 31, /* Apr */ 30,
																/* May */ 31, /* Jun */ 30, /* Jul */ 31, /* Aug */ 31,
																/* Sep */ 30, /* Oct */ 31, /* Nov */ 30, /* Dec */ 31 );
				  gaMonthDays[1]=(((!(iYear % 4))&&(iYear % 100))||(!(iYear % 400)))?29:28;

					if(iYear<1900)
					{
						obj.focus();

						if(LocalLanguage=="E")
							alert(getValidDateFormatMsg()+" and the year should be greater than 1900, please reenter.");
						else
							alert(getValidDateFormatMsg()+". L’année doit être ultérieure à 1900, SVP entrer de nouveau.");

						fieldSetCaretWhenTextFieldFocused(obj);
					}
					else if((iMonth<1)||(iMonth>12))
					{
						obj.focus();

						if(LocalLanguage=="E")
							alert(getValidDateFormatMsg()+" and the valid month range should be from 1 to 12, please reenter.");
						else
							alert(getValidDateFormatMsg()+". Inscrire un chiffre entre 1 et 12, SVP entrer de nouveau.");

						fieldSetCaretWhenTextFieldFocused(obj);
					}
					else if((iDay<1)||(iDay>gaMonthDays[iMonth-1]))
					{
						obj.focus();

						if(LocalLanguage=="E")
							alert(getValidDateFormatMsg()+" and the valid day range should be from 1 to "+gaMonthDays[iMonth-1]+", please reenter.");
						else
							alert(getValidDateFormatMsg()+". Inscrire un chiffre entre 1 et "+gaMonthDays[iMonth-1]+", SVP entrer de nouveau.");

						fieldSetCaretWhenTextFieldFocused(obj);
					}
					else
						obj.value=composeDate(obj.value);
				}
			}
		}
		else
		{
			if(isSpecialField(shiftPressed))
			{
				if(focusTimes==0)
					focusTimes++;
				else
				{
					focusTimes=0;
					tabPressed=false;
				}
			}
			else
			{
				focusTimes=0;
				tabPressed=false;
			}

			if(obj.value!="")
			{
				obj.value=compactDate(obj.value);
				fieldSelectedWhenTextFieldFocused(obj);
			}
		}
	}
}

function tools_DateFieldFocus()
{
	parseDate(WhenFocus);
}

function tools_DateFieldBlur()
{
	parseDate(WhenBlur);
}

function parsePostal()
{
	var canParse=true;
	if(!tabPressed)
		canParse=((!isClosing)&&insideDoc)

	if(canParse)
	{
		var i,obj=event.srcElement,isPostal=false,ch;
		if(obj.value!="")
		{
			for(i=0;i<obj.value.length;i++)
			{
				ch=obj.value.toUpperCase().charAt(i);
				if((ch>='A')&&(ch<='Z'))
				{
					isPostal=true;
					break;
				}
			}
		
			if(isPostal)
			{
				if(obj.value.length!=6)
				{
					obj.focus();

					if(LocalLanguage=="E")
						alert("Incorrect postal code format, please reenter.");
					else
						alert("Format du code postal non valide, SVP entrer de nouveau.");

					fieldSetCaretWhenTextFieldFocused(obj);
				}
				else
				{
					for(i=0;i<obj.value.length;i++)
					{
						ch=obj.value.toUpperCase().charAt(i);
						if(i%2==0)
						{
							if((ch<'A')||(ch>'Z'))
							{
								obj.focus();

								if(LocalLanguage=="E")
									alert("Incorrect postal code format, please reenter.");
								else
									alert("Format du code postal non valide, SVP entrer de nouveau.");

								fieldSetCaretWhenTextFieldFocused(obj);
								break;
							}
						}
						else
						{
							if((ch<'0')||(ch>'9'))
							{
								obj.focus();

								if(LocalLanguage=="E")
									alert("Incorrect postal code format, please reenter.");
								else
									alert("Format du code postal non valide, SVP entrer de nouveau.");

								fieldSetCaretWhenTextFieldFocused(obj);
								break;
							}
						}
					}
				}
			}
			else
			{
				if((obj.value.length!=5)&&(obj.value.length!=9))
				{
					obj.focus();

					if(LocalLanguage=="E")
						alert("Incorrect zip format, please reenter.");
					else
						alert("Format du code zip non valide, SVP entrer de nouveau.");

					fieldSetCaretWhenTextFieldFocused(obj);
				}
	/*			
				else
				{
					for(i=0;i<obj.value.length;i++)
					{
						ch=obj.value.charAt(i);
						if((ch<'0')||(ch>'9'))
						{
							obj.focus();

							if(LocalLanguage=="E")
								alert("Incorrect zip format, please reenter.");
							else
								alert("Format du code zip non valide, SVP entrer de nouveau.");

							fieldSetCaretWhenTextFieldFocused(obj);
							break;
						}
					}
				}
	*/
			}
		}
	}
}

function tools_PostalFieldFocus()
{
	if(isSpecialField(shiftPressed))
	{
		if(focusTimes==0)
			focusTimes++;
		else
		{
			focusTimes=0;
			tabPressed=false;
		}
	}
	else
	{
		focusTimes=0;
		tabPressed=false;
	}

	var obj=event.srcElement;
	if(obj.value!="")
		fieldSelectedWhenTextFieldFocused(obj);
}

function tools_PostalFieldBlur()
{
	parsePostal();
}

function parseSIN()
{
	var canParse=true;
	if(!tabPressed)
		canParse=((!isClosing)&&insideDoc)

	if(canParse)
	{
		var obj=event.srcElement,SIN_value=obj.value,evenSum,oddSum,sCheck;

		if(SIN_value!="")
		{
			if(SIN_value.length!=9)
			{
				obj.focus();

				if(LocalLanguage=="E")
					alert("Invalid SIN, please reenter.");
				else
					alert("NAS non valide, SVP entrer de nouveau.");

				fieldSetCaretWhenTextFieldFocused(obj);
				return;
			}

			evenSum=new Number(SIN_value.charAt(0))+new Number(SIN_value.charAt(2))+
							new Number(SIN_value.charAt(4))+new Number(SIN_value.charAt(6))+
							new Number(SIN_value.charAt(8));
			oddSum=0;

			for(var i=0;i<4;i++)
			{
			  var j=2*new Number(SIN_value.charAt(2*i+1));
			  sCheck=j.toString(10);

			  var k=0;
			  while(k<sCheck.length)
			  {
			    oddSum=oddSum+new Number(sCheck.charAt(k));
			    k++;
			  }
			}

			sCheck=(evenSum+oddSum).toString(10);
			if(sCheck.charAt(sCheck.length-1)!='0')
			{
				obj.focus();

				if(LocalLanguage=="E")
					alert("Invalid SIN, please reenter.");
				else
					alert("NAS non valide, SVP entrer de nouveau.");

				fieldSetCaretWhenTextFieldFocused(obj);
			}
		}
	}
}

function tools_SINFieldFocus()
{
	tools_PostalFieldFocus();
}

function tools_SINFieldBlur()
{
	parseSIN();
}

/*************** The followings are the public functions can be called by any javascript **********/
var TableSortCallback=null;

function RegExpReplace(expression,pattern,replacewith)
{
	var regEx,Match;
	regEx=new RegExp(pattern);
	Match=regEx.exec(expression);
	
	var str="";
	while(Match!=null)
	{
		str+=expression.substr(0,Match.index)+replacewith;
		expression=expression.substr(Match.lastIndex,expression.length-Match.lastIndex);
		Match=regEx.exec(expression);
	}
	
	str+=expression;
	return str;
}

function makeAddressMeaningful(aStr)
{
	var i,removeStr=new Array(",");

	aStr=trim(aStr);
	for(i=0;i<removeStr.length;i++)
	{
		while(aStr.substr(0,1)==removeStr[i])
			aStr=trim(aStr.substr(1,aStr.length-1));

		while(aStr.substr(aStr.length-1,1)==removeStr[i])
			aStr=trim(aStr.substr(0,aStr.length-1));
	}

	aStr=removeExcessWhitespace(aStr);
	aStr=RegExpReplace(aStr," ,",",");
	aStr=RegExpReplace(aStr,",{2,}",",");
	aStr=RegExpReplace(aStr,", OA,",",");   // In the address string, the OA always means the province is 'Out of Area'

	if(aStr.substr(0,3)=="OA,")
	{
		aStr=aStr.substr(3,aString.length-3);
		aStr=trim(aStr);
	}

	return aStr;
}

function removeExcessEndReturns(aStr)
{
	aStr=trim(aStr);
	while(aStr.substring(aStr.length-2,aStr.length)=="\r\n")
		aStr=trim(aStr.substring(0,aStr.length-2));

	return aStr;
}

function removeExcessWhitespace(aStr)
{
	return RegExpReplace(aStr," {2,}"," ");
}

function getSubStrs(value,separator)
{
	var SubAry=new Array(),pos,i=0;
	
	pos=value.indexOf(separator);
	while(pos!=-1)
	{
		SubAry[i]=value.substr(0,pos);
		value=value.substring(pos+separator.length,value.length);
		i++;
		pos=value.indexOf(separator);
	}
	
	SubAry[i]=value;
	i++;
	SubAry.length=i;
	return SubAry;
}

function replicateStr(len,chr)
{
	var value="";

	for(var i=0;i<len;i++)
		value+=chr.toString();

	return value;
}

function setTableAlign(TableName,Align)
{
	document.all(TableName).align=Align;
}

function setTableWidth(TableName,Width)
{
	document.all(TableName).style.width=Width;
}

function setTableColor(TableName,Color)
{
	document.all(TableName).style.color=Color;
}

function setTableBackgroundColor(TableName,Color)
{
	document.all(TableName).style.backgroundColor=Color;
}

function setTableBorderWidth(TableName,Border)
{
	document.all(TableName).style.borderWidth=Border;
}

function setTableBorderColor(TableName,Color)
{
	document.all(TableName).style.borderColor=Color;
}

function setTableRowColor(TableName,RowNumber,Color)
{
	document.all(TableName).rows[RowNumber].style.color=Color;
}

function setTableRowBackgroundColor(TableName,RowNumber,Color)
{
	document.all(TableName).rows[RowNumber].style.backgroundColor=Color;
}

function setTableColumnColor(TableName,ColumnNumber,Color)
{
	var table=document.all(TableName);
	for(i=0;i<table.rows.length;i++)
	{
		var cell=table.rows[i].cells[ColumnNumber];
		if(cell!=null)
			cell.style.color=Color;
	}
}

function setTableColumnBackgroundColor(TableName,ColumnNumber,Color)
{
	var table=document.all(TableName);
	for(i=0;i<table.rows.length;i++)
	{
		var cell=table.rows[i].cells[ColumnNumber];
		if(cell!=null)
			cell.style.backgroundColor=Color;
	}
}

function setTableHeader(TableName,Headers)
{
	var oldHeaders=document.all.item(TableName+"_Header");
	for(var i=0;i<Math.min(oldHeaders.length,Headers.length);i++)
		oldHeaders[i].innerText=Headers[i];
}

var AscSort=1,DescSort=2;  // The definition of the SortWay

function ExchangeTableRow(aTable,Row1,Row2,StartCol,EndCol)
{
	for(var i=StartCol;i<=EndCol;i++)
	{
		with(aTable)
		{
			var str;
			if(rows[Row1].cells[i].innerHTML!=rows[Row1].cells[i].innerText)
			{
				str=rows[Row1].cells[i].innerHTML;
				rows[Row1].cells[i].innerHTML=rows[Row2].cells[i].innerHTML;
				rows[Row2].cells[i].innerHTML=str;
			}
			else
			{
				str=rows[Row1].cells[i].innerText;
				rows[Row1].cells[i].innerText=rows[Row2].cells[i].innerText;
				rows[Row2].cells[i].innerText=str;
			}

			str=rows[Row1].cells[i].name;
			rows[Row1].cells[i].name=rows[Row2].cells[i].name;
			rows[Row2].cells[i].name=str;
		}
	}
}

function TableBubbleSort(aTable,SortCol,SortWay,StartRow,EndRow,StartCol,EndCol)
{
	var CmpResult,isNumber=false,Value,str,rowVal,limitVal,limitRow;

	for(var i=StartRow;i<EndRow;i++)
	{
		str=trim(aTable.rows[i].cells[SortCol].innerText);
		if(str.indexOf("$")>=0)
		{
			isNumber=true;
			Value=new Number(str.substring(1,str.length));
		}
		else
			Value=str;

		for(var j=i+1;j<=EndRow;j++)
		{
			str=trim(aTable.rows[j].cells[SortCol].innerText);

			if(j==(i+1))
			{
				limitVal=isNumber?new Number(str.substring(1,str.length)):str;
				limitRow=j;
			}
			else
			{
				rowVal=isNumber?new Number(str.substring(1,str.length)):str;

				if(SortWay==AscSort)
				{
					if(rowVal<limitVal)
					{
						limitVal=rowVal;
						limitRow=j;
					}
				}
				else
				{
					if(rowVal>limitVal)
					{
						limitVal=rowVal;
						limitRow=j;
					}
				}
			}
		}

		if(SortWay==AscSort)
			CmpResult=(limitVal>=Value);
		else
			CmpResult=(limitVal<=Value);

		if(!CmpResult)
			ExchangeTableRow(aTable,i,limitRow,StartCol,EndCol);
	}

	if(TableSortCallback!=null)
		TableSortCallback();
}

function TableQuickSort(aTable,SortCol,SortWay,StartRow,EndRow,StartCol,EndCol)
{
	function TableQuickPass(aTable,SortCol,SortWay,StartRow,EndRow,StartCol,EndCol)
	{
		var Lo=StartRow,Hi=EndRow,CmpResult,isNumber=false,Value,str;
		
		str=trim(aTable.rows[Lo].cells[SortCol].innerText);
		if(str.indexOf("$")>=0)
		{
			isNumber=true;
			Value=new Number(str.substring(1,str.length));
		}
		else
			Value=str;

		do
		{
			str=trim(aTable.rows[Hi].cells[SortCol].innerText);
			if(SortWay==AscSort)
				CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
			else
				CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);

			while(CmpResult&&(Lo<Hi))
			{
				str=trim(aTable.rows[--Hi].cells[SortCol].innerText);
				if(SortWay==AscSort)
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
				else
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);
			}
			
			if(Lo<Hi)
			{
				ExchangeTableRow(aTable,Lo,Hi,StartCol,EndCol);
				str=trim(aTable.rows[++Lo].cells[SortCol].innerText);
				if(SortWay==AscSort)
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);
				else
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
				
				while(CmpResult&&(Lo<Hi))
				{
					str=trim(aTable.rows[++Lo].cells[SortCol].innerText);
					if(SortWay==AscSort)
						CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);
					else
						CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
				}
				
				if(Lo<Hi)
				{
					ExchangeTableRow(aTable,Lo,Hi,StartCol,EndCol);
					--Hi;
				}
			}
		} while(Lo<Hi)
		
		return Lo;
	}

	if(StartRow<EndRow)
	{
		var Mi=TableQuickPass(aTable,SortCol,SortWay,StartRow,EndRow,StartCol,EndCol);
		TableQuickSort(aTable,SortCol,SortWay,StartRow,Mi-1,StartCol,EndCol);
		TableQuickSort(aTable,SortCol,SortWay,Mi+1,EndRow,StartCol,EndCol);
	}

	if(TableSortCallback!=null)
		TableSortCallback();
}

function ListQuickSort(aList,SortWay,StartRow,EndRow)
{
	function ExchangeListRow(aList,Row1,Row2)
	{
		var Lo=Math.min(Row1,Row2),Hi=Math.max(Row1,Row2);
		var opt1=aList.options[Lo],opt2=aList.options[Hi];

		aList.options.remove(Hi);
		aList.options.remove(Lo);
		aList.options.add(opt2,Lo);
		aList.options.add(opt1,Hi);
	}

	function ListQuickPass(aList,SortWay,StartRow,EndRow)
	{
		var Lo=StartRow,Hi=EndRow,CmpResult,isNumber=false,Value,str;
		
		str=trim(aList.options[Lo].text);
		if(str.indexOf("$")>=0)
		{
			isNumber=true;
			Value=new Number(str.substring(1,str.length));
		}
		else
			Value=str;

		do
		{
			str=trim(aList.options[Hi].text);
			if(SortWay==AscSort)
				CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
			else
				CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);

			while(CmpResult&&(Lo<Hi))
			{
				str=trim(aList.options[--Hi].text);
				if(SortWay==AscSort)
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
				else
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);
			}
			
			if(Lo<Hi)
			{
				ExchangeListRow(aList,Lo,Hi);
				str=trim(aList.options[++Lo].text);
				if(SortWay==AscSort)
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);
				else
					CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
				
				while(CmpResult&&(Lo<Hi))
				{
					str=trim(aList.options[++Lo].text);
					if(SortWay==AscSort)
						CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)<=Value);
					else
						CmpResult=((isNumber?new Number(str.substring(1,str.length)):str)>=Value);
				}
				
				if(Lo<Hi)
				{
					ExchangeListRow(aList,Lo,Hi);
					--Hi;
				}
			}
		} while(Lo<Hi)
		
		return Lo;
	}
	
	if(StartRow<EndRow)
	{
		var Mi=ListQuickPass(aList,SortWay,StartRow,EndRow);
		ListQuickSort(aList,SortWay,StartRow,Mi-1);
		ListQuickSort(aList,SortWay,Mi+1,EndRow);
	}
}

function GetCellRowIndex(aTable,value,SeekWay)
{
	with(aTable)
	{
		for(var i=0;i<rows.length;i++)
		{
			var aRow=rows[i]
			for(var j=0;j<aRow.cells.length;j++)
			{
				var aCell=aRow.cells[j],cellValue;

				if(SeekWay==SeekByText)
					cellValue=aCell.innerText;
				else if(SeekWay==SeekByHTML)
					cellValue=aCell.innerHTML;
				else if(SeekWay==SeekByName)
					cellValue=aCell.name;
				else if(SeekWay==SeekByClassName)
					cellValue=aCell.className;
				else
					cellValue=aCell.id;

				if(cellValue==value)
					return i;
			}
		}
	}

	return -1;
}

function ResizeToWholeScreen()
{
	window.moveTo(0,0);
	resizeTo(screen.availWidth,screen.availHeight);
}

function getPerfectLeft(ObjectWidth)
{
	if(eval(event))
	{
		var left=((arguments.length==2)?arguments[1]:event.screenX)+30;

		if((left+ObjectWidth)>screen.availWidth)
			if(left-ObjectWidth>=0)
				left-=ObjectWidth+30;

		return (left>0)?left:0;
	}
	else
		return Math.floor((screen.availWidth-ObjectWidth)/2);
}

function getPerfectTop(ObjectHeight)
{
	var top=(screen.availHeight-ObjectHeight)/2*0.618;
	
	return (top>0)?top:0;
}

function showDateDialog(setDate,minDate,maxDate)
{
	var i,today,day,month,year,chkDate;
	
	for(i=0;i<3;i++)
	{
		if(i==0)
			chkDate=setDate;
		else if(i==1)
			chkDate=minDate;
		else
			chkDate=maxDate;
			
		if(chkDate!="")
		{
			if(DateFormat.toLowerCase()!="mm/dd/yyyy")
			{
				if(DateFormat.toLowerCase()=="yyyy/mm/dd")
				{
					year=chkDate.substr(0,4);
					month=chkDate.substr(5,2);
					day=chkDate.substr(8,2);
				}
				else if(DateFormat.toLowerCase()=="yyyy/dd/mm")
				{
					year=chkDate.substr(0,4);
					day=chkDate.substr(5,2);
					month=chkDate.substr(8,2);
				}
				else if(DateFormat.toLowerCase()=="dd/mm/year")
				{
					day=chkDate.substr(0,2);
					month=chkDate.substr(3,2);
					year=chkDate.substr(6,4);
				}
				
				chkDate=month+"/"+day+"/"+year;
				if(i==0)
					setDate=chkDate;
				else if(i==1)
					minDate=chkDate;
				else
					maxDate=chkDate;
			}
		}
	}
	
	if(setDate=="")
	{
		today=new Date();
		day=today.getDate().toString();
		month=(today.getMonth()+1).toString();
		year=(today.getFullYear()).toString();
		setDate=((month.length==1)?("0"+month):month)+"/"+((day.length==1)?("0"+day):day)+"/"+year;
	}

	if((minDate!="")&&(new Date(setDate)<new Date(minDate)))
		setDate=minDate;

	if((maxDate!="")&&(new Date(setDate)>new Date(maxDate)))
		setDate=maxDate;

	var arg=new Array(setDate,minDate,maxDate);
	var value=window.showModalDialog("/tools/calendar.asp?CalendarStyle="+URLEncode(CalendarStyleFile),arg,"dialogWidth:309px;dialogHeight:347px;dialogLeft:"+getPerfectLeft(309)+";dialogTop:"+getPerfectTop(347)+";scroll:no;help:no;status:no");
	
	if(value==null)
		value="";
	
	if(value!="")
	{
		if(DateFormat.toLowerCase()!="mm/dd/yyyy")
		{
			month=value.substr(0,2);
			day=value.substr(3,2);
			year=value.substr(6,4);

			if(DateFormat.toLowerCase()=="yyyy/mm/dd")
				value=year+"/"+month+"/"+day;
			else if(DateFormat.toLowerCase()=="yyyy/dd/mm")
				value=year+"/"+day+"/"+month;
			else if(DateFormat.toLowerCase()=="dd/mm/year")
				value=day+"/"+month+"/"+year;
		}
	}
	
	return value;
}

function clearTextArea(obj)
{
	while(obj.value.indexOf("\t")!=-1)
		obj.value=obj.value.replace("\t","");
}

function fieldSelectedWhenTextFieldFocused(obj)
{
	obj.focus();

	var range=obj.createTextRange();
	range.select();
}

function fieldSetCaretWhenTextFieldFocused(obj)
{
	obj.focus();

	var range=obj.createTextRange();
	range.move("character",obj.value.length);
	range.select();
}

function setClass(objID,newClass)
{
	document.all(objID).className=newClass;
}

function sqlParse(value)
{
	var fStr=new Array();
	fStr[0]="'";
/*
	fStr[1]="`";  // Now, I only deal with the char "'" and omit the char "`".
							  // If you want to process more chars, you can redefine the fStr array.
*/
	fStr.length=1;

	var i,pos,lStr,rStr;
	lStr="";
	rStr=value;
	for(i=0;i<fStr.length;i++)
	{
		pos=(new String(rStr)).indexOf(fStr[i]);
		while(pos>0)
		{
			lStr+=rStr.substr(0,pos)+"'"+fStr[i];
			rStr=rStr.substr(pos+1,rStr.length-pos-1);
			pos=rStr.indexOf(fStr[i]);
		}
		
		rStr=lStr+rStr;
		lStr="";
	}
	
	return rStr;
}

function format(fmtStr,value)
{
// Now format function accept two data types: String -- %s and TimeStamp -- %t	

	var i,pos,ch,lStr,rStr;
	lStr="";
	rStr=fmtStr;

	i=0;
	pos=rStr.indexOf("%");
	while(pos>=0)
	{
		if(i>=value.length)
			break;
	
		ch=rStr.substr(pos+1,1).toLowerCase();
		switch(ch)
		{
			case "s":
				lStr+=rStr.substr(0,pos)+sqlParse(value[i]);
				rStr=rStr.substr(pos+2,rStr.length-pos-2);
				i++;
				break;
					
			case "t":
				if(value[i].toLowerCase()=="null")
					lStr+=rStr.substr(0,pos)+sqlParse(value[i]);
				else
					lStr+=rStr.substr(0,pos)+"'"+sqlParse(value[i])+"'";
				rStr=rStr.substr(pos+2,rStr.length-pos-2);
				i++;
				break;
				
			default:
				lStr+=rStr.substr(0,pos+1);
				rStr=rStr.substr(pos+1,rStr.length-pos-1);
		}

		pos=rStr.indexOf("%");
	}
	
	return lStr+rStr;
}

function getTopFrame()
{
	if((frames)&&(parent!=self))
	{
		var obj=parent;
		
		while(obj.parent!=obj)
			obj=obj.parent;

		return obj;
	}
	else
		return self;
}

var siObverseDirect=0,siReverseDirect=1;  // The enumeration values of the Direction of the StrToInt method

function StrToInt(value,Direction)
{
	var aStr=value.toString(),fromEnd,toEnd;
	
	fromEnd=(Direction==siObverseDirect)?0:aStr.length-1;
	toEnd=(Direction==siObverseDirect)?aStr.length-1:0;

	for(var i=fromEnd;((Direction==siObverseDirect)?(i<=toEnd):(i>=toEnd));((Direction==siObverseDirect)?i++:i--))
		if((aStr.charAt(i)<'0')||(aStr.charAt(i)>'9'))
			break;

	if(((Direction==siObverseDirect)?(aStr.substring(0,i)!=""):(aStr.substring(i+1,aStr.length)!="")))
		return new Number(((Direction==siObverseDirect)?aStr.substring(0,i):aStr.substring(i+1,aStr.length)));
	else
		return null;
}

function setDialogSize(elementAry)	// setDialogSize is used for the back compatibility.
{
	setDialogHeight(elementAry);
}

function setDialogHeight(elementAry)
{
	var i,height=0,
			valHeight=StrToInt(dialogHeight.toString(),siObverseDirect)-document.body.clientHeight;  // valHeight is the window's head bar height.

	for(i=0;i<elementAry.length;i++)
		height+=elementAry[i].offsetHeight;
	height+=valHeight;	// The true height of the window.
	
	if(height>(0.9*screen.availHeight))
	{
		document.body.scroll="auto";
		height=(0.9*screen.availHeight);
	}
	
	if(document.body.scroll=="no")
		dialogHeight=(height-1)+"px";
	else
		dialogHeight=height+"px";
	dialogTop=getPerfectTop(height)+"px";
}

var PresetLeft="";

function setDialogWidth(elementAry)
{
	var i,valWidth,width=0;

	for(i=0;i<elementAry.length;i++)
		width=Math.max(width,elementAry[i].offsetWidth);

	if(width>(0.9*screen.availWidth))
	{
		document.body.scroll="auto";
		width=(0.9*screen.availWidth);
	}
		
	valWidth=StrToInt(dialogWidth.toString(),siObverseDirect)-document.body.clientWidth;
	width+=valWidth;

	if(document.body.scroll=="no")
		dialogWidth=(width-1)+"px";
	else
		dialogWidth=width+"px";

	if(PresetLeft=="")
	{
		if(arguments.length==2)
			dialogLeft=getPerfectLeft(width,arguments[1])+"px";
		else
			dialogLeft=getPerfectLeft(width)+"px";
	}
	else
		dialogLeft=PresetLeft;
}

function changePageElementsHeight()
{
	var i,height=0;
	
	for(i=0;i<pageElementAry.length;i++)
		height+=pageElementAry[i].offsetHeight;

	if(height<document.body.clientHeight)
	{
		var focusedObj=document.activeElement;

		pageElementAry[pageElementAry.length-1].style.display="none";
		pageElementAry[pageElementAry.length-1].style.display="inline";
		pageElementAry[pageElementAry.length-1].style.height=pageElementAry[pageElementAry.length-1].offsetHeight+(document.body.clientHeight-height);

		if(focusedObj) focusedObj.focus();
	}

/*
	with(document)
	{
		body.style.zIndex=0;
		for(i=0;i<all.length;i++)
		{
			if(all[i].className.toLowerCase()=="tabheadcell")
			{
				all[i].style.display="none";
				all[i].style.zIndex=10;
				all[i].style.display="inline";
			}
		}
	}
*/
}

function setPageHeight(elementAry)
{
	pageElementAry=elementAry;
}

function itemIndex(ary,item)
{
	for(var i=0;i<ary.length;i++)
		if(ary[i]==item)
			return i;

	return -1;
}

function StringToArray(aStr)
{
	var rtnAry=new Array();
		
	if(aStr!=null)
	{
		var tempAry1=aStr.split("\\^");

		if(tempAry1.length>0)
		{
			for(var i=0;i<tempAry1.length;i++)
			{
				var tempAry2=tempAry1[i].split("\\~");
					
				for(var j=0;j<tempAry2.length;j++)
					if(tempAry2[j].indexOf("null")!=-1)
						tempAry2[j]="";

				rtnAry[i]=tempAry2;
			}
				
			rtnAry.length=i;
		}
	}
	
	return rtnAry;
}
	
function ArrayToString(aAry)
{
	var rtnStr="";
		
	if(aAry!=null)
	{
		for(var i=0;i<aAry.length;i++)
		{
			if(rtnStr!="")
				rtnStr+="\\^";
				
			for(var j=0;j<aAry[i].length;j++)
			{
				if((j!=0)&&(rtnStr!=""))
					rtnStr+="\\~";
					
				rtnStr+=aAry[i][j];
			}
		}
	}
		
	return rtnStr;
}

function drawDBTable(TableName,RsArray,BorderOption)
{
	if(BorderOption==tbWithBorder)
		document.write("<table id="+TableName+" name="+TableName+" border=1"+" align=center>");
	else
		document.write("<table id="+TableName+" name="+TableName+" align=center>");

	document.write("	<thead>");
	document.write("		<tr>");

	for(var i=0;i<RsArray.length;i++)
		document.write("			<th id="+TableName+"_Header"+" name="+TableName+"_Header>"+RsArray[i][0]+"</th>");

	document.write("		</tr>");
	document.write("	</thead>");
		
	if(RsArray[0].length>1)
	{
		document.write("	<tbody>");

		for(var j=1;j<RsArray[0].length;j++)
		{
			document.write("		<tr>")

			for(var i=0;i<RsArray.length;i++)
				document.write("			<td>"+((rTrim(RsArray[i][j])=="")?"&nbsp;":rTrim(RsArray[i][j]))+"</td>");

			document.write("		</tr>");
		}
		
		document.write("	</tbody>");
	}

	document.write("</table>");
}

function getRelativeOffsetLeft(obj)
{
	var theOffsetLeft=0,theOffsetParent;
	theOffsetParent=obj.offsetParent;
	while(theOffsetParent)
	{
		theOffsetLeft+=theOffsetParent.offsetLeft;
		theOffsetParent=theOffsetParent.offsetParent;
	}
	
	return theOffsetLeft;
}

function getRelativeOffsetTop(obj)
{
	var theOffsetTop=0,theOffsetParent;
	theOffsetParent=obj.offsetParent;
	while(theOffsetParent)
	{
		theOffsetTop+=theOffsetParent.offsetTop;
		theOffsetParent=theOffsetParent.offsetParent;
	}
	
	return theOffsetTop;
}

function getAbsoluteOffsetLeft(obj)
{
	if(obj!=null)
		return obj.offsetLeft+getRelativeOffsetLeft(obj);

	return 0;
}

function getAbsoluteOffsetTop(obj)
{
	if(obj!=null)
		return obj.offsetTop+getRelativeOffsetTop(obj);

	return 0;
}

function lTrim(aStr)
{
	while(aStr.charAt(0)==" ")
		aStr=aStr.substring(1,aStr.length);

	return aStr;
}

function rTrim(aStr)
{
	while(aStr.charAt(aStr.length-1)==" ")
		aStr=aStr.substring(0,aStr.length-1);

	return aStr;
}

function trim(aStr)
{
	aStr=lTrim(aStr);
	aStr=rTrim(aStr);

	return aStr;
}

function indexOf(ArrayObj,Value)
{
	for(var i=0;i<ArrayObj.length;i++)
		if(ArrayObj[i].toString().toLowerCase()==Value.toString().toLowerCase())
			return i;

	return -1;
}

function indexOf2(ArrayObj,ColAry,ValAry)
{
	for(var i=0;i<ArrayObj.length;i++)
	{
		for(var j=0;j<ColAry.length;j++)
			if(ArrayObj[i][j].toString().toLowerCase()!=ValAry[j].toString().toLowerCase())
				break;

		if(j==ColAry.length)
			return i;
	}

	return -1;
}

function deleteAt(ArrayObj,index)
{
	if(ArrayObj.length>0)
	{
		for(var i=index;i<ArrayObj.length-1;i++)
			ArrayObj[i]=ArrayObj[i+1];

		ArrayObj.length--;
	}

	return ArrayObj;
}

function removeDupRows(ArrayObj)
{
	var i=0;
	while(i<ArrayObj.length-1)
	{
		var j=i+1;
		while(j<ArrayObj.length)
		{
			if(ArrayObj[i]==ArrayObj[j])
				deleteAt(ArrayObj,j);
			else
				j++;
		}

		i++;
	}

	return ArrayObj;
}

function removeDupRows2(ArrayObj,ColAry)
{
	var i=0;
	while(i<ArrayObj.length-1)
	{
		var j=i+1;
		while(j<ArrayObj.length)
		{
			for(var k=0;k<ColAry.length;k++)
				if(ArrayObj[i][k]!=ArrayObj[j][k])
					break;

			if(k==ColAry.length)
				deleteAt(ArrayObj,j);
			else
				j++;
		}

		i++;
	}

	return ArrayObj;
}

function objectArrayIndexOf(ArrayObj,Obj)
{
	for(var i=0;i<ArrayObj.length;i++)
		if(ArrayObj[i]==Obj)
			return i;

	return -1;
}

function concatArrays(ArrayObj1,ArrayObj2)
{
	var i,ArrayLen1=ArrayObj1.length,ArrayLen2=ArrayObj2.length,RetArray=new Array(ArrayLen1+ArrayLen2);

	for(i=0;i<ArrayLen1;i++)
		RetArray[i]=ArrayObj1[i];

	for(i=0;i<ArrayLen2;i++)
		RetArray[ArrayLen1+i]=ArrayObj2[i];

	return RetArray;
}

function joinArray(ArrayObj,Delimitater)
{
	var RetStr="";

	for(var i=0;i<ArrayObj.length;i++)
	{
		if(i>0) RetStr+=Delimitater;
		RetStr+=ArrayObj[i].toString();
	}

	return RetStr;
}

function copyArray(SrcArray)
{
	var DestArray=new Array(SrcArray.length);

	for(var i=0;i<SrcArray.length;i++)
		DestArray[i]=SrcArray[i];

	return DestArray;
}

function twoDimArrayToOneDim(ArrayObj,Delimitator)
{
	var RetArray=copyArray(ArrayObj);

	for(var i=0;i<RetArray.length;i++)
		RetArray[i]=joinArray(RetArray[i],Delimitator);

	return RetArray;
}

function getOptionIndex(SelectObj,Value)
{
	for(var i=0;i<SelectObj.options.length;i++)
		if(SelectObj.options[i].text.toLowerCase()==Value.toLowerCase())
			return i;

	return -1;
}

function getOptionIndexByValue(SelectObj,Value)
{
	for(var i=0;i<SelectObj.options.length;i++)
		if(SelectObj.options[i].value.toString().toLowerCase()==Value.toString().toLowerCase())
			return i;

	return -1;
}

function getOptionIndexByLabel(SelectObj,Value)
{
	for(var i=0;i<SelectObj.options.length;i++)
		if(SelectObj.options[i].label.toString().toLowerCase()==Value.toString().toLowerCase())
			return i;

	return -1;
}

function setSelectedOption(SelectObj,Value)
{
	var index=getOptionIndex(SelectObj,Value);
	SelectObj.selectedIndex=(index==-1)?0:index;
}

function setSelectedOptionByValue(SelectObj,Value)
{
	var index=getOptionIndexByValue(SelectObj,Value);
	SelectObj.selectedIndex=(index==-1)?0:index;
}

function setSelectedOptionByLabel(SelectObj,Value)
{
	var index=getOptionIndexByLabel(SelectObj,Value);
	SelectObj.selectedIndex=(index==-1)?0:index;
}

function setStreetPart(StreetName,PartList)
{
	if(StreetName!="")
	{
		for(var i=0;i<PartList.options.length;i++)
		{
/*
			var index=StreetName.toLowerCase().lastIndexOf(" "+PartList.options[i].text.toLowerCase()+" ");
			if(index>=0)
			{
				PartList.selectedIndex=i;
				return StreetName.substring(0,index)+StreetName.substring(index+PartList.options[i].text.length+1,StreetName.length);
			}
*/

			var index=StreetName.toLowerCase().lastIndexOf(" "+PartList.options[i].text.toLowerCase());
			if((index>=0)&&((index+PartList.options[i].text.length+1)==StreetName.length))
			{
				PartList.selectedIndex=i;
				return StreetName.substring(0,index);
			}
			else
				PartList.selectedIndex=0;
		}

		return StreetName;
	}
	
	return "";
}

function IsSpecialChar(ch)
{
	if((ch=="\a")||(ch=="\b")||(ch=="\f")||(ch=="\n")||(ch=="\r")||(ch=="\t")||(ch=="\v"))
		return true;
	else
		return false;
}

function URLEncode(aStr)
{
	var i=0,value="";
	
	while(i<aStr.length)
	{
		var ch=aStr.substr(i,1);
		
		if(!(((ch>="0")&&(ch<="9"))||((ch>="a")&&(ch<="z"))||((ch>="A")&&(ch<="Z"))))
		{
			if(ch==" ")
				ch="+";
			else
			{
				hexVal=ch.charCodeAt(0).toString(16);
				for(var j=0;j<(2-hexVal.length);j++)
					hexVal="0"+hexVal;
				ch="%"+hexVal;
			}
		}
		value+=ch;
		
		i++;
	}
	
	return value;
}

function URLDecode(aStr)
{
	aStr=RegExpReplace(aStr,"[+]"," ");
	
	var index=aStr.indexOf("%"),value="";
	while(index>=0)
	{
		value+=aStr.substring(0,index)+String.fromCharCode(new Number("0x"+aStr.substr(index+1,2)));
		aStr=aStr.substring(index+3,aStr.length);
		index=aStr.indexOf("%");
	}
	value+=aStr;

	return value;
}

function HTMLEncode(value)
{
	var OrigStrs=new Array("&","<",">","\""," "),ReplStrs=new Array("&amp;","&lt;","&gt;","&quot;","&nbsp;");

	for(var i=0;i<OrigStrs.length;i++)
		value=RegExpReplace(value,OrigStrs[i],ReplStrs[i]);

	return value;
}

function HTMLDecode(value)
{
	var OrigStrs=new Array("&amp;","&lt;","&gt;","&quot;","&nbsp;"),ReplStrs=new Array("&","<",">","\""," ");

	for(var i=0;i<OrigStrs.length;i++)
		value=RegExpReplace(value,OrigStrs[i],ReplStrs[i]);

	return value;
}

function CStyleEncode(value)
{
	value=RegExpReplace(value,"\\[^abfnrtv\'\"\\\?|$|\\[abfnrtv\'\"\?]","\\");
	value=RegExpReplace(value,"\'","\\\'");
	value=RegExpReplace(value,"\"","\\\"");
	return value;
}

function RemoveCtrlChars(value)
{
	var i,index,pattern1=new Array("\\F","\\N","\\R","\\T","\\V","\\f","\\n","\\r","\\t","\\v"),pattern2="[\\f\\n\\r\\t\\v]+",pattern3="[ ]+";

	for(i=0;i<pattern1.length;i++)
	{
		index=value.indexOf(pattern1[i]);
		while(index>=0)
		{
			value=value.substring(0,index)+" "+value.substring(index+pattern1[i].length,value.length);
			index=value.indexOf(pattern1[i]);
		}
	}
	
	value=RegExpReplace(value,pattern2," ");
	value=RegExpReplace(value,pattern3," ");
	
	return value;
}

function today()
{
	var d=new Date(),day=d.getDate().toString(),month=(d.getMonth()+1).toString(),year=(d.getFullYear()).toString();
	
	if(DateFormat.toLowerCase()=="mm/dd/yyyy")
		return ((month.length==1)?("0"+month):month)+"/"+((day.length==1)?("0"+day):day)+"/"+year;
	else if(DateFormat.toLowerCase()=="yyyy/mm/dd")
		return year+"/"+((month.length==1)?("0"+month):month)+"/"+((day.length==1)?("0"+day):day);
	else if(DateFormat.toLowerCase()=="yyyy/dd/mm")
		return year+"/"+((day.length==1)?("0"+day):day)+"/"+((month.length==1)?("0"+month):month);
	else if(DateFormat.toLowerCase()=="dd/mm/year")
		return ((day.length==1)?("0"+day):day)+"/"+((month.length==1)?("0"+month):month)+"/"+year;
}

function getMouseAbsPosition()
{
	var value=new Array(event.clientX+document.body.scrollLeft,event.clientY+document.body.scrollTop);
	return value;
}

function mouseInObjectRange(obj)
{
	var mousePosition=getMouseAbsPosition(),mouseX=mousePosition[0],mouseY=mousePosition[1],
			objLeft=obj.offsetLeft+getRelativeOffsetLeft(obj),objTop=obj.offsetTop+getRelativeOffsetTop(obj);

	if((mouseX>=objLeft)&&(mouseX<=(objLeft+obj.offsetWidth))&&(mouseY>=objTop)&&(mouseY<=(objTop+obj.offsetHeight)))
		return true;
	else
		return false;
}

function enableObject(obj,bgColor)
{
	obj.style.backgroundColor=bgColor;
	obj.readOnly=false;
	obj.tabIndex=0;
}

function disableObject(obj,bgColor)
{
	obj.style.backgroundColor=bgColor;
	obj.readOnly=true;
	obj.tabIndex=-1;
}

function disableFrameObjectEvents(frameObj)
{
	with(frameObj.document)
	{
		for(var i=0;i<all.length;i++)
		{
			if(all[i].onclick!=null)
				all[i].onclick=null;

			if(all[i].onkeypress!=null)
				all[i].onkeypress=null;

			if(all[i].onkeydown!=null)
				all[i].onkeydown=null;

			if(all[i].onkeyup!=null)
				all[i].onkeyup=null;

			if(all[i].onfocus!=null)
				all[i].onfocus=null;

			if(all[i].onblur!=null)
				all[i].onblur=null;
		}
	}
}

function getParentTable(obj)
{
	if(obj==null)
		return null;

	var tagName=obj.tagName.toLowerCase();
	while(tagName!="table")
	{
		obj=obj.parentElement;
		if(obj!=null)
			tagName=obj.tagName.toLowerCase();
		else
			return null;
	}
	
	return obj;
}

function getParentTableWithSpecailId(obj,parentId)
{
	var obj=getParentTable(obj);
	if(obj==null)
		return null;
	
	while(obj.id.toLowerCase().indexOf(parentId.toLowerCase())<0)
	{
		obj=obj.parentElement;
		if(obj!=null)
		{
			obj=getParentTable(obj);
			if(obj==null)
				return null;
		}
		else
			return null;
	}
	
	return obj;
}

function isObjectTotallyVisible(obj)
{
	var objTop=getAbsoluteOffsetTop(obj),objBottom=objTop+obj.offsetHeight,
			objLeft=getAbsoluteOffsetLeft(obj),objRight=objLeft+obj.offsetWidth,
			docVisibleTop=document.body.clientTop+document.body.scrollTop,
			docVisibleBottom=docVisibleTop+document.body.clientHeight,
			docVisibleLeft=document.body.clientLeft+document.body.scrollLeft,
			docVisibleRight=docVisibleLeft+document.body.clientWidth;

	if(((objTop>=docVisibleTop)&&(objBottom<=docVisibleBottom))&&((objLeft>=docVisibleLeft)&&(objRight<=docVisibleRight)))
		return true;
	else
		return false;
}

function makeObjectTotallyVisible(obj)
{
	if(obj!=null)
	{
		if(!isObjectTotallyVisible(obj))
		{
			if(obj.offsetHeight<document.body.clientHeight)
			{
				var objTop=getAbsoluteOffsetTop(obj),
						newTop=objTop-(document.body.clientTop+Math.round((document.body.clientHeight-obj.offsetHeight)/2));
				newTop=newTop<0?0:newTop;
				newTop=newTop>document.body.scrollHeight?document.body.scrollHeight:newTop;
				document.body.scrollTop=newTop;
			}
			else
				document.body.scrollTop=0;
		}

		if(!isObjectTotallyVisible(obj))
		{
			if(obj.offsetWidth<document.body.clientWidth)
			{
				var objLeft=getAbsoluteOffsetLeft(obj),
						newLeft=objLeft-(document.body.clientLeft+Math.round((document.body.clientWidth-obj.offsetWidth)/2));
				newLeft=newLeft<0?0:newLeft;
				newLeft=newLeft>document.body.scrollWidth?document.body.scrollWidth:newLeft;
				document.body.scrollLeft=newLeft;
			}
			else
				document.body.scrollLeft=0;
		}
	}
}

function isObjectInside(outsideObj,insideObj)
{
	var obj=insideObj;
	if(obj==null)
		return false;

	while(obj!=outsideObj)
	{
		obj=obj.parentElement;
		if(obj==null)
			return false;
	}
	
	return true;
}

function execFindObj(outsideObj,value,seekOption,findAllChildren,objArray)
{
	function isThisObject(obj,value,option)
	{
		var seekOption=option.toString(16);

		if(seekOption.length==1)
		{
			if(seekOption==SeekByText.toString(16))
				return obj.innerText.toLowerCase()==value.toLowerCase();
			else if(seekOption==SeekByHTML.toString(16))
				return obj.innerHTML.toLowerCase()==value.toLowerCase();
			else if(seekOption==SeekByName.toString(16))
				return obj.name.toLowerCase()==value.toLowerCase();
			else if(seekOption==SeekByClassName.toString(16))
				return obj.className.toLowerCase()==value.toLowerCase();
			else
				return obj.id.toLowerCase()==value.toLowerCase();
		}
		else
		{
			if(seekOption==(SeekByText|SeekPartial).toString(16))
				return obj.innerText.toLowerCase.indexOf(value.toLowerCase())>=0;
			else if(seekOption==(SeekByHTML|SeekPartial).toString(16))
				return obj.innerHTML.toLowerCase().indexOf(value.toLowerCase())>=0;
			else if(seekOption==(SeekByName|SeekPartial).toString(16))
				return obj.name.toLowerCase().indexOf(value.toLowerCase())>=0;
			else if(seekOption==(SeekByClassName|SeekPartial).toString(16))
				return obj.className.toLowerCase().indexOf(value.toLowerCase())>=0;
			else
				return obj.id.toLowerCase().indexOf(value.toLowerCase())>=0;
		}
	}


	if(isThisObject(outsideObj,value,seekOption))
	{
		objArray[objArray.length]=outsideObj;
		if(!findAllChildren)
			return;
	}

	for(var i=0;i<outsideObj.children.length;i++)
	{
		var obj=outsideObj.children[i];

		execFindObj(obj,value,seekOption,findAllChildren,objArray);
		if((!findAllChildren)&&(objArray.length>0))
			return;
	}

	return;
}

function findObject(outsideObj,value,seekOption)
{
	var findAllChildren=false;
	if((arguments.length>3)&&(arguments[3]==FindAll))
		findAllChildren=true;

	var objArray=new Array();
	execFindObj(outsideObj,value,seekOption,findAllChildren,objArray);

	if(objArray.length==0)
		return null;
	else if(!findAllChildren)
		return objArray[0];
	else
		return objArray;
}

function showModalDlgWindow(URL,Params,Width,Height)
{
	return showModalDialog(URL,Params,"status:no;scroll:no;help:no;dialogWidth:"+Width+"px;dialogHeight:"+Height+"px;dialogLeft:"+getPerfectLeft(Width)+";dialogTop:"+getPerfectTop(Height));
}

var alignTop=0,alignMiddle=1,alignBottom=2,alignLeft=3,alignCenter=4,alignRight=5;

function showHintForComponent(component,hintBlock)
{
	var componentLeft=component.offsetLeft+getRelativeOffsetLeft(component),
			componentTop=component.offsetTop+getRelativeOffsetTop(component),
			align=(arguments.length>=3)?arguments[2]:alignMiddle,
			offset=(arguments.length==4)?arguments[3]:0;

	with(hintBlock.style)
	{
		left=componentLeft+component.offsetWidth;

		switch(align)
		{
			case alignTop:
				top=componentTop+offset;
				break;

			case alignMiddle:
				top=componentTop+(component.offsetHeight/2)-hintBlock.offsetHeight/2+offset;
				break;

			case alignBottom:
				top=componentTop+component.offsetHeight-hintBlock.offsetHeight+offset;
		}

		visibility='visible';
	}
}

function showHintForComponentEx(component,parentFrame,hintFrame,margin)
{
	function setHintPosition(hintLeft,hintTop,component,hintFrame,alignMode)
	{
		with(hintFrame.style)
		{
			switch(alignMode)
			{
				case alignLeft:
				case alignTop:
					left=hintLeft;
					top=hintTop;
					break;

				case alignCenter:
					left=hintLeft+(component.offsetWidth/2)-hintFrame.offsetWidth/2;;
					top=hintTop;
					break;

				case alignRight:
					left=hintLeft+component.offsetWidth-hintFrame.offsetWidth;;
					top=hintTop;
					break;

				case alignMiddle:
					left=hintLeft;
					top=hintTop+(component.offsetHeight/2)-hintFrame.offsetHeight/2;
					break;

				case alignBottom:
					left=hintLeft;
					top=hintTop+component.offsetHeight-hintFrame.offsetHeight;
			}

			visibility='visible';
		}
	}

	var	offset=(arguments.length>4)?arguments[4]:0,alignMode=(arguments.length>5)?arguments[5]:alignMiddle,
			componentWindowX=(arguments.length>6)?arguments[6]:0,componentWindowY=(arguments.length>7)?arguments[7]:0,
			objLeft=getAbsoluteOffsetLeft(component)+componentWindowX,objTop=getAbsoluteOffsetTop(component)+componentWindowY;

	if(((objLeft+component.offsetWidth+hintFrame.offsetWidth+margin)<=parentFrame.offsetWidth)||((objLeft-hintFrame.offsetWidth-margin)>=0))
	{
		if((alignMode!=alignTop)&&(alignMode!=alignMiddle)&&(alignMode!=alignBottom))
			alignMode=alignMiddle;

		if(((objTop+hintFrame.offsetHeight+offset)>parentFrame.offsetHeight)&&(alignMode==alignTop))
			alignMode=alignMiddle;

		if(((objTop+(component.offsetHeight/2)+hintFrame.offsetHeight/2+offset)>parentFrame.offsetHeight)&&(alignMode==alignMiddle))
			alignMode=alignBottom;

		if((objLeft+component.offsetWidth+hintFrame.offsetWidth+margin)<=parentFrame.offsetWidth)
			objLeft+=component.offsetWidth+margin;
		else
			objLeft-=hintFrame.offsetWidth+margin;
		objTop+=offset;

		setHintPosition(objLeft,objTop,component,hintFrame,alignMode);
	}
	else if(((objTop+component.offsetHeight+hintFrame.offsetHeight+margin)<=parentFrame.offsetHeight)||((objTop-hintFrame.offsetHeight-margin)>=0))
	{
		if((alignMode!=alignLeft)&&(alignMode!=alignCenter)&&(alignMode!=alignRight))
			alignMode=alignCenter;

		if(((objLeft+hintFrame.offsetWidth+offset)>parentFrame.offsetWidth)&&(alignMode==alignLeft))
			alignMode=alignCenter;

		if(((objLeft+(component.offsetWidth/2)+hintFrame.offsetWidth/2+offset)>parentFrame.offsetWidth)&&(alignMode==alignCenter))
			alignMode=alignRight;

		objLeft+=offset;
		if((objTop+component.offsetHeight+hintFrame.offsetHeight+margin)<=parentFrame.offsetHeight)
			objTop+=component.offsetHeight+margin;
		else
			objTop-=hintFrame.offsetHeight+margin;

		setHintPosition(objLeft,objTop,component,hintFrame,alignMode);
	}
}

function getDateDiff(interval,date1,date2)
{
	return VB_GetDateDiff(interval,date1.getVarDate(),date2.getVarDate());
}

var TotalWaitTime=0;
function WaitForTimeout(WaitTime)
{
	function WaitForFunc()
	{
		if(TotalWaitTime<WaitTime)
			TotalWaitTime+=WaitTime;

		setTimeout("WaitForFunc()",WaitTime);
	}

	setTimeout("WaitForFunc()",WaitTime);
}

function cancelEventAction()
{
	event.returnValue=false;
}

function createHiddenInputField(parentObj,objName,objValue)
{
	var obj=document.createElement("input");
	obj.type="hidden";
	obj.name=objName;
	obj.value=objValue;
	parentObj.appendChild(obj);
}

function getFramePageValue(frameName)
{
	var frame=(frameName==""?this:frames(frameName)),framePageValues=new Array(),lastActiveObjectIndex=-1;

	with(frame.document)
	{
		for(var i=0;i<all.length;i++)
		{
			var tagName=all[i].tagName.toLowerCase();

			switch(tagName)
			{
				case "input":
					var type=all[i].type.toLowerCase();
					if((type!="button")&&(type!="submit")&&(type!="reset")&&(type!="file")&&(type!="image"))
					{
						framePageValues.length++;
						framePageValues[framePageValues.length-1]=new Array(5);
						framePageValues[framePageValues.length-1][0]=i;

						if((type=="checkbox")||(type=="radio"))
							framePageValues[framePageValues.length-1][1]=all[i].checked;
						else
							framePageValues[framePageValues.length-1][1]=all[i].value;

						framePageValues[framePageValues.length-1][2]=all[i].id;
						framePageValues[framePageValues.length-1][3]=all[i].name;
						framePageValues[framePageValues.length-1][4]=all[i].className;
					}
					break;

				case "textarea":
					framePageValues.length++;
					framePageValues[framePageValues.length-1]=new Array(5);
					framePageValues[framePageValues.length-1][0]=i;
					framePageValues[framePageValues.length-1][1]=all[i].value;
					framePageValues[framePageValues.length-1][2]=all[i].id;
					framePageValues[framePageValues.length-1][3]=all[i].name;
					framePageValues[framePageValues.length-1][4]=all[i].className;
					break;

				case "select":
					framePageValues.length++;
					framePageValues[framePageValues.length-1]=new Array(5);
					framePageValues[framePageValues.length-1][0]=i;
					framePageValues[framePageValues.length-1][1]=all[i].selectedIndex;
					framePageValues[framePageValues.length-1][2]=all[i].id;
					framePageValues[framePageValues.length-1][3]=all[i].name;
					framePageValues[framePageValues.length-1][4]=all[i].className;
					break;
			}

			if(all[i]==frame.lastActiveObject)
				lastActiveObjectIndex=i;
		}

		framePageValues.length++;
		framePageValues[framePageValues.length-1]=lastActiveObjectIndex;
	}

	return framePageValues;
}

function setFramePageValue(frameName,framePageValues)
{
	function getFramePageValueIndex(framePageValues,index)
	{
		for(var i=0;i<framePageValues.length-1;i++)
			if(framePageValues[i][0]==index)
				return i;

		return -1;
	}

	if(framePageValues!=null)
	{
		var frame=(frameName==""?this:frames(frameName)),tagName,type,index;

		with(frame.document)
		{
			for(var i=0;i<all.length;i++)
			{
				tagName=all[i].tagName.toLowerCase();

				switch(tagName)
				{
					case "input":
						type=all[i].type.toLowerCase();
						if((type!="button")&&(type!="submit")&&(type!="reset")&&(type!="file")&&(type!="image"))
						{
							index=getFramePageValueIndex(framePageValues,i);
							if(index>=0)
							{
								if((type=="checkbox")||(type=="radio"))
									all[i].checked=framePageValues[index][1];
								else
									all[i].value=framePageValues[index][1];
							}
						}
						break;

					case "textarea":
						index=getFramePageValueIndex(framePageValues,i);
						if(index>=0) all[i].value=framePageValues[index][1];
						break;

					case "select":
						index=getFramePageValueIndex(framePageValues,i);
						if(index>=0) all[i].selectedIndex=framePageValues[index][1];
						break;
				}
			}

			var lastActiveObjectIndex=framePageValues[framePageValues.length-1];
			if(lastActiveObjectIndex>=0)
			{
				frame.lastActiveObject=all[lastActiveObjectIndex];

				try
				{
					tagName=all[lastActiveObjectIndex].tagName.toLowerCase();

					if((tagName=="input")||(tagName=="textarea"))
					{
						if(tagName=="input")
						{
							type=all[lastActiveObjectIndex].type.toLowerCase();
							if((type=="text")||(type=="password"))
								fieldSetCaretWhenTextFieldFocused(all[lastActiveObjectIndex]);
							else
								all[lastActiveObjectIndex].focus();
						}
						else
							fieldSetCaretWhenTextFieldFocused(all[lastActiveObjectIndex]);
					}
					else
						all[lastActiveObjectIndex].focus();
				}
				catch(e)
				{
				}
			}
		}
	}
}

function ReplaceScriptTag(RenderContent)
{
	var ReExpBegin=/<#scriptBegin#>/g,ReExpEnd=/<#scriptEnd#>/g;
	RenderContent=RenderContent.replace(ReExpBegin,"<script ");
	RenderContent=RenderContent.replace(ReExpEnd,"</script>");
	return RenderContent;
}

/********************************* Time zone functions *************************************/

function ProvinceTimeZone(Province,Country,TimeZone)
{
	this.Province=Province;
	this.TimeZone=TimeZone;
	this.Country=Country

	switch(TimeZone)
	{
		case "NST":
			this.GMT=-3.5;
			break;

		case "AST":
			this.GMT=-4;
			break;

		case "EST":
			this.GMT=-5;
			break;

		case "CST":
			this.GMT=-6;
			break;

		case "MST":
			this.GMT=-7;
			break;

		case "PST":
			this.GMT=-8;
			break;

		case "AKT":
			this.GMT=-9;
			break;

		case "HST":
			this.GMT=-11;
			break;
	}

	return this;
}

var TimeZoneObj,ProvinceTimeZoneList=new Array(68);

TimeZoneObj=new ProvinceTimeZone("AB","CANADA","MST");
ProvinceTimeZoneList[0]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("BC","CANADA","PST");
ProvinceTimeZoneList[1]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MB","CANADA","CST");
ProvinceTimeZoneList[2]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NB","CANADA","AST");
ProvinceTimeZoneList[3]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NF","CANADA","NST");
ProvinceTimeZoneList[4]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NS","CANADA","AST");
ProvinceTimeZoneList[5]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NT","CANADA","MST");
ProvinceTimeZoneList[6]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NU","CANADA","EST");
ProvinceTimeZoneList[7]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("ON","CANADA","EST");
ProvinceTimeZoneList[8]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("PE","CANADA","AST");
ProvinceTimeZoneList[9]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("QC","CANADA","EST");
ProvinceTimeZoneList[10]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("SK","CANADA","MST");
ProvinceTimeZoneList[11]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("YK","CANADA","PST");
ProvinceTimeZoneList[12]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("YT","CANADA","PST");
ProvinceTimeZoneList[13]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("AK","USA","AKT");
ProvinceTimeZoneList[14]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("AL","USA","CST");
ProvinceTimeZoneList[15]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("AR","USA","CST");
ProvinceTimeZoneList[16]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("AZ","USA","MST");
ProvinceTimeZoneList[17]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("CA","USA","PST");
ProvinceTimeZoneList[18]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("CO","USA","MST");
ProvinceTimeZoneList[19]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("CT","USA","EST");
ProvinceTimeZoneList[20]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("DC","USA","EST");
ProvinceTimeZoneList[21]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("DE","USA","EST");
ProvinceTimeZoneList[22]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("FL","USA","EST");
ProvinceTimeZoneList[23]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("GA","USA","EST");
ProvinceTimeZoneList[24]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("GU","USA","PST");
ProvinceTimeZoneList[25]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("HI","USA","HST");
ProvinceTimeZoneList[26]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("IA","USA","CST");
ProvinceTimeZoneList[27]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("ID","USA","MST");
ProvinceTimeZoneList[28]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("IL","USA","CST");
ProvinceTimeZoneList[29]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("IN","USA","EST");
ProvinceTimeZoneList[30]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("KS","USA","CST");
ProvinceTimeZoneList[31]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("KY","USA","EST");
ProvinceTimeZoneList[32]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("LA","USA","CST");
ProvinceTimeZoneList[33]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MA","USA","EST");
ProvinceTimeZoneList[34]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MD","USA","EST");
ProvinceTimeZoneList[35]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("ME","USA","EST");
ProvinceTimeZoneList[36]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MI","USA","EST");
ProvinceTimeZoneList[37]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MN","USA","CST");
ProvinceTimeZoneList[38]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MO","USA","CST");
ProvinceTimeZoneList[39]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MS","USA","CST");
ProvinceTimeZoneList[40]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("MT","USA","MST");
ProvinceTimeZoneList[41]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NC","USA","EST");
ProvinceTimeZoneList[42]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("ND","USA","CST");
ProvinceTimeZoneList[43]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NE","USA","CST");
ProvinceTimeZoneList[44]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NH","USA","EST");
ProvinceTimeZoneList[45]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NJ","USA","EST");
ProvinceTimeZoneList[46]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NM","USA","MST");
ProvinceTimeZoneList[47]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NV","USA","PST");
ProvinceTimeZoneList[48]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("NY","USA","EST");
ProvinceTimeZoneList[49]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("OH","USA","EST");
ProvinceTimeZoneList[50]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("OK","USA","CST");
ProvinceTimeZoneList[51]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("OR","USA","PST");
ProvinceTimeZoneList[52]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("PA","USA","EST");
ProvinceTimeZoneList[53]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("PR","USA","AST");
ProvinceTimeZoneList[54]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("RI","USA","EST");
ProvinceTimeZoneList[55]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("SC","USA","EST");
ProvinceTimeZoneList[56]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("SD","USA","CST");
ProvinceTimeZoneList[57]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("TN","USA","CST");
ProvinceTimeZoneList[58]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("TX","USA","CST");
ProvinceTimeZoneList[59]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("UT","USA","MST");
ProvinceTimeZoneList[60]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("VA","USA","EST");
ProvinceTimeZoneList[61]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("VI","USA","PST");
ProvinceTimeZoneList[62]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("VT","USA","EST");
ProvinceTimeZoneList[63]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("WA","USA","PST");
ProvinceTimeZoneList[64]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("WI","USA","CST");
ProvinceTimeZoneList[65]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("WV","USA","EST");
ProvinceTimeZoneList[66]=TimeZoneObj;

TimeZoneObj=new ProvinceTimeZone("WY","USA","MST");
ProvinceTimeZoneList[67]=TimeZoneObj;

function GetProvinceTimeZone(Province)
{
	for(var i=0;i<ProvinceTimeZoneList.length;i++)
	{
		var TimeZoneObj=ProvinceTimeZoneList[i];
		if(TimeZoneObj.Province==Province)
			return TimeZoneObj.TimeZone;
	}

	return "";
}

function GetProvinceGMT(Province)
{
	for(var i=0;i<ProvinceTimeZoneList.length;i++)
	{
		var TimeZoneObj=ProvinceTimeZoneList[i];
		if(TimeZoneObj.Province==Province)
			return TimeZoneObj.GMT;
	}

	return 0;
}

function GetTimeZoneGMT(TimeZone)
{
	for(var i=0;i<ProvinceTimeZoneList.length;i++)
	{
		var TimeZoneObj=ProvinceTimeZoneList[i];
		if(TimeZoneObj.TimeZone==TimeZone)
			return TimeZoneObj.GMT;
	}

	return 0;
}

function GetProvinceCountry(Province)
{
	for(var i=0;i<ProvinceTimeZoneList.length;i++)
	{
		var TimeZoneObj=ProvinceTimeZoneList[i];
		if(TimeZoneObj.Province==Province)
			return TimeZoneObj.Country;
	}

	return "";
}

function GetAdjustDataTime(fromDateTime,fromZone,toZone)
{
	var iZoneDiff=GetTimeZoneGMT(toZone)-GetTimeZoneGMT(fromZone),iAbsZoneDiff=Math.abs(iZoneDiff),
			iDiffHour=Math.floor(iAbsZoneDiff),iDiffMinute=Math.round((iAbsZoneDiff-iDiffHour)*60),
			iDiffTime=Date.UTC(1970,0,1,iDiffHour,iDiffMinute,0),iFromDateTime=Date.parse(fromDateTime);

	if(iZoneDiff>=0)
		return new Date(iFromDateTime+iDiffTime);
	else
		return new Date(iFromDateTime-iDiffTime);
}

function GetTimeZoneDescription(TimeZone)
{
	switch(TimeZone)
	{
		case "NST":	return "NEWFOUNDLAND";
		case "AST":	return "ATLANTIC";
		case "EST":	return "EASTERN";
		case "CST":	return "CENTRAL";
		case "MST":	return "MOUNTAIN";
		case "PST":	return "PACIFIC";
		case "AKT":	return "ALASKA";
		case "HST":	return "HAWAII";
	}

	return "";
}

/********************************* End of the public functions *************************************/


/********************** The following section is dedicated to the Grid control *********************/
// The object's offsetWidth is equal to its style.width+style.paddingLeft+style.paddingRight+style.borderLeft+style.borderRight
// In this case, the GridHead's and GridBody's padding and border are

var DefaultGridBodyObj="document.all.GridBody_01";

var GridBodySetCurrentRowCallback=null;
var GridBodyInnerSetCurrentRowCallback=null;

var GridBodyInsertRowCallback=null;
var GridBodyInsertRowCellHTMLSetCallback=null;

var GridBodyModifyRowCallback=null;
var GridBodyModifyRowCellHTMLSetCallback=null;

var GridBodyDeleteRowCallback=null;
var GridBodyCellDblClickCallback=null;

var GridBodySelectedRowIndex=-1;
var gridBodyLastSelectedRowIndexAry=new Array();

var oldGridRowBgColor,oldGridRowFgColor='black',
		newGridRowBgColor='dodgerblue',newGridRowFgColor='white';

var GridHeadCell_PaddingLeft=3,GridHeadCell_PaddingRight=3,GridHeadCell_BorderLeft=2,GridHeadCell_BorderRight=2;
var GridBodyCell_PaddingLeft=3,GridBodyCell_PaddingRight=3,GridBodyCell_BorderLeft=1,GridBodyCell_BorderRight=1;

function GetGridHeadFromGridBody(gridBody)
{
	var index=gridBody.id.lastIndexOf("_");
	return document.all("GridHead"+gridBody.id.substring(index,gridBody.id.length));
}

function GetGridBodyFromGridHead(gridHead)
{
	var index=gridHead.id.lastIndexOf("_");
	return document.all("GridBody"+gridHead.id.substring(index,gridHead.id.length));
}

function RefreshGridBody(gridBody)
{
	var gridHead=GetGridHeadFromGridBody(gridBody);

	try
	{
		if(gridBody.cells.length>0)
		{
			var l=0;
			for(var k=0;k<gridBody.rows[0].cells.length;k++)
			{
				if(gridBody.rows[0].cells[k].className.toLowerCase().lastIndexOf("gridbodycell")>=0)
				{
					if(arguments.length==2)
					{
						if(arguments[1].toLowerCase()=="resizebybody")
							gridHead.rows[0].cells[l].style.width=gridBody.rows[0].cells[k].offsetWidth-GridHeadCell_PaddingLeft-GridHeadCell_PaddingRight-GridHeadCell_BorderLeft-GridHeadCell_BorderRight;
						else
							gridBody.rows[0].cells[k].style.width=gridHead.rows[0].cells[l].offsetWidth-GridBodyCell_PaddingLeft-GridBodyCell_PaddingRight-GridBodyCell_BorderLeft-GridBodyCell_BorderRight;
					}
					else
					{
						if(gridHead.rows[0].cells[l].offsetWidth<gridBody.rows[0].cells[k].offsetWidth)
							gridHead.rows[0].cells[l].style.width=gridBody.rows[0].cells[k].offsetWidth-GridHeadCell_PaddingLeft-GridHeadCell_PaddingRight-GridHeadCell_BorderLeft-GridHeadCell_BorderRight;
						else if(gridHead.rows[0].cells[l].offsetWidth>gridBody.rows[0].cells[k].offsetWidth)
							gridBody.rows[0].cells[k].style.width=gridHead.rows[0].cells[l].offsetWidth-GridBodyCell_PaddingLeft-GridBodyCell_PaddingRight-GridBodyCell_BorderLeft-GridBodyCell_BorderRight;
					}

					l++;
				}
			}
								
			if(gridHead.offsetWidth<=gridBody.offsetWidth)
				gridHead.style.width=gridBody.offsetWidth;
			else
				gridBody.style.width=gridHead.offsetWidth;
		}
		else
			gridHead.style.width=document.body.clientWidth;

		gridHead.style.visibility='visible';
		gridBody.style.visibility='visible';
	}
	finally
	{
		gridHead.style.top=0;
		gridBody.style.top=getAbsoluteOffsetTop(gridHead)+gridHead.offsetHeight;
	}
}

function scrollDocumentBodyToTop()
{
	document.body.scrollTop=0;
}

function tools_GridBodyKeydown()
{
	var key=event.keyCode;
	
	if(!((key==38)||(key==40)||(key==33)||(key==34)||(key==35)||(key==36)))
		return;
	else
		event.returnValue=0;

	var bodyObj,obj=event.srcElement;

	switch(event.srcElement.tagName.toLowerCase())
	{
		case "table":
			bodyObj=obj;
			break;
		
		case "tr":
			bodyObj=obj.parentElement.parentElement;  // TR's parent is TBODY, as well as TBODY's parent is TABLE.
			break;
		
		default:
			bodyObj=obj.parentElement.parentElement.parentElement;
	}

	if(GridBodySetCurrentRowCallback!=null)
	{
		if(GridBodySelectedRowIndex==-1)
		{
			GridBodySelectedRowIndex=0;
			GridBodySetCurrentRowCallback(GridBodySelectedRowIndex);
		}
		else
		{
			if((key==38)||(key==40))  // The event of Up or Down pressed.
			{
				if(key==38)
				{
					if(GridBodySelectedRowIndex>0)
						GridBodySetCurrentRowCallback(--GridBodySelectedRowIndex);
				}
				else
				{
					if(GridBodySelectedRowIndex<(bodyObj.rows.length-1))
						GridBodySetCurrentRowCallback(++GridBodySelectedRowIndex);
				}
			}
			else if((key==33)||(key==34))  // The event of PageUp or PageDown pressed.
			{
				var RowsPerPage=Math.floor((document.body.clientHeight-GetGridHeadFromGridBody(bodyObj).offsetHeight)/bodyObj.rows[0].offsetHeight);

				if(key==33)
				{
					if(GridBodySelectedRowIndex>0)
					{
						GridBodySelectedRowIndex=((GridBodySelectedRowIndex-RowsPerPage)>0)?(GridBodySelectedRowIndex-RowsPerPage):0;
						GridBodySetCurrentRowCallback(GridBodySelectedRowIndex);
					}
				}
				else
				{
					if(GridBodySelectedRowIndex<(bodyObj.rows.length-1))
					{
						GridBodySelectedRowIndex=((GridBodySelectedRowIndex+RowsPerPage)<(bodyObj.rows.length-1))?(GridBodySelectedRowIndex+RowsPerPage):(bodyObj.rows.length-1);
						GridBodySetCurrentRowCallback(GridBodySelectedRowIndex);
					}
				}
			}
			else if((key==35)||(key==36))  // The event of Home or End pressed.
			{
				if(key==35)
				{
					if(GridBodySelectedRowIndex<(bodyObj.rows.length-1))
					{
						GridBodySelectedRowIndex=bodyObj.rows.length-1;
						GridBodySetCurrentRowCallback(GridBodySelectedRowIndex);
					}
				}
				else
				{
					if(GridBodySelectedRowIndex>0)
					{
						GridBodySelectedRowIndex=0;
						GridBodySetCurrentRowCallback(GridBodySelectedRowIndex);
					}
				}
			}
		}

		if(GridBodySelectedRowIndex!=-1)
		{
			var headObj=GetGridHeadFromGridBody(bodyObj),rowHeight=bodyObj.rows[0].offsetHeight,offset,curScrollTop=document.body.scrollTop;

			if((getAbsoluteOffsetTop(bodyObj.rows[GridBodySelectedRowIndex]))<(getAbsoluteOffsetTop(headObj)+headObj.offsetHeight))
			{
				offset=getAbsoluteOffsetTop(headObj)+headObj.offsetHeight-getAbsoluteOffsetTop(bodyObj.rows[GridBodySelectedRowIndex]);
				document.body.scrollTop-=offset;  // After you set the document body's scrollTop, the onscroll event will occur again, it will set the GridHead's offsetTop.
				tools_DocScroll();
			}
			else if((getAbsoluteOffsetTop(bodyObj.rows[GridBodySelectedRowIndex])+rowHeight-curScrollTop)>document.body.clientHeight)
			{
				offset=getAbsoluteOffsetTop(bodyObj.rows[GridBodySelectedRowIndex])+rowHeight-curScrollTop-document.body.clientHeight;
				document.body.scrollTop+=offset;
				tools_DocScroll();
			}
		}
	}
}

function tools_GridBodyDocFocus()
{
	try
	{
		with(document)
		{
			for(var i=0;i<all.length;i++)
			{
				if(all[i].className.toLowerCase().lastIndexOf("gridbody")>=0)
				{
					headObj=GetGridHeadFromGridBody(all[i]);
					all[i].focus();

					if(GridBodySelectedRowIndex!=-1)
						GridRowScrollIntoView(all[i].rows[GridBodySelectedRowIndex],headObj);
					
					break;
				}
			}
		}
	}
	catch(e)
	{
	}
}

function tools_DocScroll()
{
	with(document)
	{
		for(var i=0;i<GridHeadInitTop[0].length;i++)
		{
			var gridHead=all(GridHeadInitTop[0][i]),gridBody=GetGridBodyFromGridHead(gridHead);
			gridHead.style.top=GridHeadInitTop[1][i]+body.scrollTop;
			gridBody.style.top=GridHeadInitTop[1][i]+gridHead.offsetHeight;
		}
	}
}

var theScrollingRow=null,theScrollingGridHead=null;
function ScrollingGridRowIntoView()
{
	if((theScrollingRow!=null)&&(theScrollingGridHead!=null))
	{
		var curScrollTop=document.body.scrollTop;
		theScrollingRow.scrollIntoView(true);
		if(getAbsoluteOffsetTop(theScrollingRow)<(getAbsoluteOffsetTop(theScrollingGridHead)+theScrollingGridHead.offsetHeight))
			document.body.scrollTop-=getAbsoluteOffsetTop(theScrollingGridHead)+theScrollingGridHead.offsetHeight-getAbsoluteOffsetTop(theScrollingRow);
	}
}

function GridRowScrollIntoView(row,gridHead)
{
	if((row!=null)&&(gridHead!=null))
	{
		theScrollingRow=row,theScrollingGridHead=gridHead;
		setTimeout("ScrollingGridRowIntoView()",100);
	}
}

function LocateGridItem(grid,colAry,itemAry)
{
	var aryLen=Math.min(itemAry.length,colAry.length);
	
	for(var i=0;i<grid.rows.length;i++)
	{
		var row=grid.rows[i];

		for(var j=0;j<aryLen;j++)
		{
			var col=row.cells[colAry.length==1?(new Number(colAry[j])):colAry[j]];

			var colVal,itemVal,splitLen;
			if(arguments.length>3)
			{
				var delimitater=arguments[3];
				colVal=trim(col.innerText).toLowerCase().split(delimitater);
				itemVal=trim(itemAry[j]).toLowerCase().split(delimitater);
				splitLen=Math.min(colVal.length,itemVal.length);
			}
			else
			{
				colVal=new Array(trim(col.innerText).toLowerCase());
				itemVal=new Array(trim(itemAry[j]).toLowerCase());
				splitLen=1;
			}
			
			for(var k=0;k<splitLen;k++)
				if(trim(colVal[k]).lastIndexOf(trim(itemVal[k]))!=0)
					break;
			
			if(k<splitLen)
				break;
		}
		
		if(j==aryLen)
			return i;
	}
	
	return -1;
}

function getGridBodyLastSelectedRowNumber(gridBodyObj)
{
	function initializeGridBody(gridBodyObj)
	{
		gridBodyLastSelectedRowIndexAry[gridBodyLastSelectedRowIndexAry.length]=new Array(2);
		gridBodyLastSelectedRowIndexAry[gridBodyLastSelectedRowIndexAry.length-1][0]=gridBodyObj;
		gridBodyLastSelectedRowIndexAry[gridBodyLastSelectedRowIndexAry.length-1][1]=-1;
	}

	for(var i=0;i<gridBodyLastSelectedRowIndexAry.length;i++)
		if(gridBodyLastSelectedRowIndexAry[i][0]==gridBodyObj)
			return gridBodyLastSelectedRowIndexAry[i][1];

	initializeGridBody(gridBodyObj);
	return -1;
}

function setGridBodyLastSelectedRowNumber(gridBodyObj,index)
{
	for(var i=0;i<gridBodyLastSelectedRowIndexAry.length;i++)
	{
		if(gridBodyLastSelectedRowIndexAry[i][0]==gridBodyObj)
		{
			gridBodyLastSelectedRowIndexAry[i][1]=index;
			break;
		}
	}
}

function gridHighlightRowColor(gridBodyObj,index)
{
	var rowObj=gridBodyObj.rows[index];

	for(var i=0;i<rowObj.cells.length;i++)
	{
		oldGridRowBgColor=rowObj.cells[i].style.backgroundColor;
		rowObj.cells[i].style.color=newGridRowFgColor;
		rowObj.cells[i].style.backgroundColor=newGridRowBgColor;
	}
}

function gridRestoreRowColor(gridBodyObj,index)
{
	var rowObj=gridBodyObj.rows[index];

	for(var i=0;i<rowObj.cells.length;i++)
	{
		rowObj.cells[i].style.color=oldGridRowFgColor;
		rowObj.cells[i].style.backgroundColor=oldGridRowBgColor;
	}
}

function gridSetCurrentRow()
{
	var gridBodyObj,RowNo;

	if(arguments.length==1)
	{
		gridBodyObj=eval(DefaultGridBodyObj);
		RowNo=arguments[0];
	}
	else
	{
		gridBodyObj=arguments[0];
		RowNo=arguments[1];
	}

	var row=gridBodyObj.rows[RowNo],selectedRowNo=getGridBodyLastSelectedRowNumber(gridBodyObj);

	if(selectedRowNo!=RowNo)
	{
		if(selectedRowNo!=-1)
			gridRestoreRowColor(gridBodyObj,selectedRowNo);
		gridHighlightRowColor(gridBodyObj,RowNo);

		setGridBodyLastSelectedRowNumber(gridBodyObj,RowNo);
    GridBodySelectedRowIndex=RowNo;
	}

	GridBodyInnerSetCurrentRowCallback(gridBodyObj,RowNo);
}

function gridCellClick(gridBodyObj)
{
	if(gridBodyObj.toString()!="[object]")
		gridBodyObj=document.all(gridBodyObj);

	var rowsObj=gridBodyObj.rows;

	for(var i=0;i<rowsObj.length;i++)
	{
		if(event.srcElement.name==rowsObj[i].cells[0].name)
		{
			gridSetCurrentRow(gridBodyObj,i);
			break;
		}
	}
}

function gridHeadResizeExec(gridHeadObj)
{
	if(gridHeadObj.toString()!="[object]")
		gridHeadObj=document.all(gridHeadObj);
		
	var gridBodyObj=GetGridBodyFromGridHead(gridHeadObj);
	gridBodyObj.style.top=gridHeadObj.offsetHeight;
}

function gridHeadResize(gridHeadObj)
{
	setTimeout("gridHeadResizeExec("+gridHeadObj.id+")",300);
}

/*
function setCellNameOfNewRowBeginWithRule(beginWith)
{
	CellNameOfNewRowBeginWith=beginWith;
}
*/

function gridInsertRow(gridBodyObj,cellArray)
{
	if(cellArray.length>0)
	{
		var CellNameOfNewRowBeginWith="gridCellOfRow_";

		with(document.all)
		{
			var cellName,gridHeadObj=GetGridHeadFromGridBody(gridBodyObj),
					row=gridBodyObj.insertRow(),rowLen=gridBodyObj.rows.length;

			if(gridBodyObj.rows.length>1)
			{
				cellName=gridBodyObj.rows[0].cells[0].name;
				cellName=cellName.substring(0,cellName.lastIndexOf("_")+1)+(rowLen-1);
			}
			else
				cellName=CellNameOfNewRowBeginWith+(rowLen-1);

			if((rowLen-1)%2==0)
				row.id="dbEvenRow";
			else
				row.id="dbOddRow";

			for(var i=1;i<cellArray.length;i++)
			{
				var cell=row.insertCell();
				cell.style.width=gridHeadObj.rows[0].cells[i-1].offsetWidth;
				cell.className="GridBodyCell";
				cell.name=cellName;
				cell.onclick=new Function("return gridCellClick("+gridBodyObj.id+")");

				if(GridBodyCellDblClickCallback!=null)
					cell.ondblclick=new Function("return GridBodyCellDblClickCallback("+gridBodyObj.id+")");

				if(GridBodyInsertRowCellHTMLSetCallback!=null)
					cell.innerHTML=GridBodyInsertRowCellHTMLSetCallback(cellName,i,cellArray);
				else
					cell.innerHTML=cellArray[i];
			}

			var TableSortCallback_Backup=TableSortCallback,TableSortCallback=null;
			TableBubbleSort(gridBodyObj,0,AscSort,0,rowLen-1,0,gridBodyObj.rows[0].cells.length-1);
			TableSortCallback=TableSortCallback_Backup;

			var RowIndex=GetCellRowIndex(gridBodyObj,cellName,SeekByName);
			if(RowIndex>=0)
			{
				gridSetCurrentRow(gridBodyObj,RowIndex);
				RefreshGridBody(gridBodyObj);
				GridRowScrollIntoView(gridBodyObj.rows[RowIndex],gridHeadObj);

				if(GridBodyInsertRowCallback!=null)
					GridBodyInsertRowCallback(gridBodyObj,RowIndex);
			}
		}
	}
}

function gridModifyRow(gridBodyObj,cellArray)
{
	if(cellArray.length>0)
	{
		with(document.all)
		{
			var modifiedRowIndex=(arguments.length<3)?getGridBodyLastSelectedRowNumber(gridBodyObj):arguments[2],
					gridHeadObj=GetGridHeadFromGridBody(gridBodyObj),row=gridBodyObj.rows[modifiedRowIndex],
					cellName=row.cells[0].name;

			for(var i=1;i<cellArray.length;i++)
			{
				if(GridBodyModifyRowCellHTMLSetCallback!=null)
					row.cells[i-1].innerHTML=GridBodyModifyRowCellHTMLSetCallback(cellName,i,cellArray);
				else
					row.cells[i-1].innerHTML=cellArray[i];
			}

			var TableSortCallback_Backup=TableSortCallback,TableSortCallback=null;
			TableBubbleSort(gridBodyObj,0,AscSort,0,gridBodyObj.rows.length-1,0,gridBodyObj.rows[0].cells.length-1);
			TableSortCallback=TableSortCallback_Backup;

			var RowIndex=GetCellRowIndex(gridBodyObj,cellName,SeekByName);
			if(RowIndex>=0)
			{
				gridSetCurrentRow(gridBodyObj,RowIndex);
				RefreshGridBody(gridBodyObj);
				GridRowScrollIntoView(gridBodyObj.rows[RowIndex],gridHeadObj);

				if(GridBodyModifyRowCallback!=null)
					GridBodyModifyRowCallback(gridBodyObj,RowIndex);
			}
		}
	}
}

function gridDeleteRow(gridBodyObj)
{
	var RowIndex,LastSelectedRow=getGridBodyLastSelectedRowNumber(gridBodyObj),
			gridHeadObj=GetGridHeadFromGridBody(gridBodyObj);

	if(arguments.length==1)
		RowIndex=LastSelectedRow;
	else
		RowIndex=arguments[1];

	if((RowIndex>=0)&&(RowIndex<gridBodyObj.rows.length))
	{
		var row=gridBodyObj.rows[RowIndex];
		row.removeNode(true);

		if((gridBodyObj.rows.length==0)||(RowIndex!=LastSelectedRow))
		{
			RefreshGridBody(gridBodyObj);

			if((gridBodyObj.rows.length>0)&&(RowIndex!=LastSelectedRow))
				GridRowScrollIntoView(gridBodyObj.rows[LastSelectedRow],gridHeadObj);
		}

		if(RowIndex==LastSelectedRow)
			setGridBodyLastSelectedRowNumber(gridBodyObj,-1);

		if(GridBodyDeleteRowCallback!=null)
			GridBodyDeleteRowCallback(gridBodyObj,RowIndex);
	}
}
/*************************** End of the Grid section **********************************************/

