
//PCHG! 13-Oct-03
//	Now selecting the content of text box and not leaving it if data is invalid
//
IE4 = (document.all && !document.getElementById) ? true : false;
NS4 = (document.layers) ? true : false;
IE5 = (document.all && document.getElementById) ? true : false;
NS6 = (!document.all && document.getElementById) ? true : false;

//trim - removes white spaces
function trim(str)
{
	return( (""+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}
	
//getGridRowObj
//	@gridname
//	@row
//	@fieldname
//
function getGridRowObj(gridname, row, fieldname)
{
	return getObject(gridname + '__ctl' + String(row) + '_' + fieldname);
}

//findGrid - PADD! 13-oct-03
//
function findGrid()
{
	var indx;
	
	var totfrm=document.forms.length;
	for(fcnt = 0; fcnt < document.forms.length; fcnt++)
	{
		for(i = 0; i < document.forms[fcnt].elements.length; i++)
		{
			var elm = document.forms[fcnt].elements[i];
			if(elm.id.indexOf("dgAdd") == 0 || elm.id.indexOf("dgChange") == 0)
			{
				indx = elm.id.indexOf("_");
				return document.getElementById(elm.id.substr(0, indx));	
			}//if
		}//for
	}
}//findGrid

//findReviewGrid - SADD! 06-Nov-03
//
function findReviewGrid()
{
	var indx;
	var totfrm=document.forms.length;
	for(fcnt = 0; fcnt < document.forms.length; fcnt++)
	{
		for(i = 0; i < document.forms[fcnt].elements.length; i++)
		{
			var elm = document.forms[fcnt].elements[i];
			if(elm.id.indexOf("dgReview") == 0)
			{
				indx = elm.id.indexOf("_");
				return document.getElementById(elm.id.substr(0, indx));	
			}//if
		}//for
	}
}//findReviewGrid
	
//define global arrays to store default values for segment validations
// the values generated out of the segment validation table will override this
var arrSegNames = new Array();
var arrMinLens = new Array();
var arrMaxLens = new Array();
var arrDataTypes = new Array();

//setValidations -- PADD! Oct-10-2003
//	@codetype - FND/CLS etc.
//	@codename - Fund/Class etc.
//	@minLen - minimum length of code
//	@maxLen - maximum length of code
//	@dataType - allowable data type
//
function setValidations(codetype, codename, minLen, maxLen, dataType)
{
	arrSegNames[codetype] = codename;
	arrMinLens[codetype] = minLen;
	arrMaxLens[codetype] = maxLen;
	arrDataTypes[codetype] = dataType;
}//setValidations

//initSegCodes -- PADD! Oct-10-2003
//	this should be called to initialize the default values from segment 
//	code setup pages
//
function initSegCodes()
{
	//call this so that this is initialized only once.
	if (arrSegNames.length > 0)
		return;
	//following loads the default validation sets in the internal arrays
	setValidations("FND", "Fund", 2, 2, "N");
	setValidations("FUN", "Function", 3, 3, "N");
	setValidations("CLS", "Class",  3, 3, "N");
	setValidations("OBJ", "Object", 4, 4, "N");
	setValidations("STA", "State",  3, 3, "N");
	setValidations("SFX", "Suffix", 4, 4, "N");
	setValidations("PGM", "Program", 3, 3, "N");
}//initSegCodes

//HasValidChars -- PADD! Oct-10-2003
//	@sText - text to check
//	@ValidChars - valid characters
//	This checks if the text has any invalid characters 
//
function hasValidChars(sText, ValidChars)
{
	var i;
	var c;
	for (i = 0; i < sText.length; i++) 
	{ 
		c = sText.charAt(i); 
		if (ValidChars.indexOf(c) == -1) 
		{
			return false;
		}//if
	}//for
	return true;
}//HasValidChars

//IsEmpty -- PADD! 10-Oct-03
//	@val - the value 
//	whether empty or not
//
function isEmpty(val)
{
	if(!val)
		return true;
	if(typeof val == "undefined")
		return true;
	return (trim(val).length == 0);
}//isEmpty

//IsNumeric -- PADD! Oct-10-2003
//	@sText - text to check
//
function isNumeric(sText)
{
	var ValidChars = "0123456789";
	return hasValidChars(sText, ValidChars);
}//isNumeric

//IsAlphabetic -- PADD! Oct-10-2003
//	@sText - text to check
//
function isAlphabetic(sText)
{
	var ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	return hasValidChars(sText, ValidChars);
}//isNumeric

//IsAlphaNumeric -- PADD! Oct-10-2003
//	@sText - text to check
//
function isAlphaNumeric(sText)
{
	var ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01223456789";
	return hasValidChars(sText, ValidChars);
}//isNumeric

//checkNoEmpty - PADD! 12-Jan-05
//	@field
//	@msg
function checkNoEmpty(field, msg)
{
	if(isEmpty(field.value))
	{
		alert(msg);
		field.focus();
		return false;
	}
	return true;
}//checkNoEmpty

//validCode -- PADD! Oct-10-2003
//	@codetype - code type FND/CLS etc.
//	@obj - the control whose value to check
//	@returnOnEmpty - return this if the control value is empty
//
//	Following is called to check the segment codes. It checks for the
//	globalCodeMinLen etc that should be defined dynamically by the calling page
//	but if they are not defined then default checks are made 
//
function validCode(codetype, obj, returnOnEmpty)
{
	//initialize the arrays - it happens only once
	initSegCodes();
	
	var code = obj.value;
	var minlen, maxlen, datatype;	
	var indx;
	var codename = arrSegNames[codetype];
	
	//we will return that empty codes are not valid
	if(isEmpty(code))	
		return returnOnEmpty;
		
	//load the default values if the global values are not provided.
	if(typeof globalCodeMinLen != "undefined" &&  globalCodeMinLen > 0)
		minlen = globalCodeMinLen;
	else
		minlen = arrMinLens[codetype];
		
	if (typeof globalCodeMaxLen != "undefined" && globalCodeMaxLen > 0)
		maxlen = globalCodeMaxLen;
	else
		maxlen = arrMaxLens[codetype];
	
	if (typeof globalCodeDataType != "undefined" && (globalCodeDataType == "A" || globalCodeDataType == "N" || globalCodeDataType == "X"))
		datatype = globalCodeDataType;
	else
		datatype = arrDataTypes[codetype];

	//check the code for min len and max len
	if(code.length < minlen)
		return codename + " Code must be at least " + minlen + " characters";
	if(code.length > maxlen)
		return codename + " Code must be less than " + maxlen + " characters";
	
	//check the code for data type	
	switch (datatype)
	{
		case "A":
			if(!isAlphabetic(code))
				return codename + " Code must be Alphabetic.";
			break;
			
		case "N":
			if(!isNumeric(code))
				return codename + " Code must be Numeric.";
			break;
			
		case "X":
			if(!isAlphaNumeric(code))
				return codename + " Code must be Alphanumeric."; 
			break;
	}//switch
	return true;
}//validCode

//onBlurCheck - PADD! 10-Oct-03
//	@codetype - FND/CLS etc.
//	@obj - the control
//	This is to be called when onblur of each code input box
//
function onBlurSegCode(codetype, obj)
{
	var str = validCode(codetype, obj, true);
	if(str == true)
		;
	else
	{
		alert(str);
		obj.select();
		obj.focus();
	}//else
	
	CheckDuplicates(obj);
}//onBlurCheck

//checkMaxLen - RADD! 13-Oct-03
//	checks if the pased value is valid integer or not
function validInt(value)
{
	if(isNaN(parseInt(value)))
		return false;
	else
		return true;	 
}

//checkSegType - RADD! 13-Oct-03
//	This is to be called when onblur of each SEGMENT TYPE input box
//  Validation still to be added for this input box and to be confirmed from Piyush and Joseph
function checkSegType(obj)
{
	var segtype = obj.value;
	
}//checkSegType

//checkMinLen - RADD! 13-Oct-03
//	This is to be called when onblur of each MINIMUM LENGTH input box
function checkMinLen(obj)
{
	var ret = validInt(obj.value); 
	if(ret)
	{
		var minlen = obj.value;
		if(minlen < 0 || minlen > 5)
		{
			alert(MSG_MIN_SEGLEN);
		}
	}
	else
	{
		alert(MSG_MIN_SEGLEN);
	}		
}//checkMinLen

//checkMaxLen - RADD! 13-Oct-03
//	This is to be called when onblur of each Maximum Length input box and check its value against the Minimum Length input box.
function checkMaxLen(obj,minlenfield)
{
	var ret = validInt(obj.value);
	
	if(ret)
	{
		var maxlen = obj.value;
		var objminlen = getGridObj(obj, minlenfield);
		
		if(objminlen)
			minlen = objminlen.value;
			if(maxlen < minlen || maxlen > 5)
			{
				alert(MSG_MAX_SEGLEN);
			}	
	}
	else
	{
		alert(MSG_MAX_SEGLEN);
	}		
}//checkMaxLen


//onChangeSegCode - PADD! 10-Oct-03
//	this is to be called if above is not called. Any one of this to be called and not both
//
function onChangeSegCode(codetype, obj)
{
	var str = validCode(codetype, obj, true);
	if(str == true)
		;
	else
	{
		alert(str);
		obj.select();
		obj.focus();
	}//else
}//onChangeSegCode



//checkMark - PADD! 10-Oct-03
//	@obj - the control
//	This is used to enable the check mark in the row which is updated
//
function checkMark(obj)
{
	var chkbox = getGridObj(obj, "chkSelected");
	var hdbox  = getGridObj(obj, "hdSelected");
	
	if(chkbox)
		chkbox.checked = true;
		
	if(hdbox)
		hdbox.value = 1;	
				
}//checkMark

//SADD - 20-Apr-04
//This is to uncheck the check mark
function uncheckMark(obj)
{
	var chkbox = getGridObj(obj, "chkSelected");
	var hdbox  = getGridObj(obj, "hdSelected");
	
	if(chkbox)
		chkbox.checked = false;
		
	if(hdbox)
		hdbox.value = 0;	
				
}//checkMark

//checkMark - RADD! 21-Oct-03
//	@obj - the control
//	This is used to enable the check mark in the row which is updated when lookup are used
//
function checkMarkChkBox(obj)
{
	var chkbox = getGridObject(obj, "chkSelected");
	var hdbox  = getGridObject(obj, "hdSelected");
	
	if(chkbox)
		chkbox.checked = true;
	if(hdbox)
		hdbox.value = 1;
		
		
}//checkMark

//SADD - 20-Apr-04
//This is to uncheck the check mark in case of lookup blur
function uncheckMarkChkBox(obj)
{
	var chkbox = getGridObject(obj, "chkSelected");
	var hdbox  = getGridObject(obj, "hdSelected");
	
	if(chkbox)
		chkbox.checked = false;
	if(hdbox)
		hdbox.value = 0;
		
		
}//checkMark


//checkMarkNE - SADD! 23-Apr-04
//	@obj - the control
//	This is used to enable the check mark if not empty
//
function checkMarkNE(obj)
{
	if (obj.value != '')
	{
		checkMark(obj);	
	}
}//checkMark

//checkMarkChkBoxNE - SADD! 23-Apr-04
//	@obj - the control
//	This is used to enable the check mark if not empty : for Lookup in datagrid
//
function checkMarkChkBoxNE(obj)
{
	if (obj.value != '')
	{
		checkMarkChkBox(obj);	
	}
}//checkMark

//getGridObj - PADD! 10-Oct-03
//	@obj- the control whose id is used to find
//	@fieldname - the name whose control is to be found
//
function getGridObj(obj, fieldname)
{
	return getObject(getGridID(obj, fieldname));
}//getDotNetObj

//getGridObj - RADD! 10-Oct-03
//	@obj- the control whose id is used to find
//	@fieldname - the name whose control is to be found
//
function getGridObjT(obj, fieldname)
{
	return getObject(getGridIDT(obj, fieldname));
}//getDotNetObj

function getDotNetObj(obj, fieldname)
{
	return getObject(getDotNetID(obj, fieldname));
}//getDotNetObj

//getGridID - PADD! 10-Oct-03
//	@obj -  the control whose id is used to find
//	@fieldname - whose id is created in this method
//
function getDotNetID(obj, fieldname)
{
	var str;
	var objid = obj.id;
	var indx;	
		
	indx = objid.lastIndexOf("_");	
	str = objid.substring(0, indx);	
	str = str + "_" + fieldname;
	return str;
	
}//getDotNetID

function getGridID(obj, fieldname)
{
	var str;
	var objid = obj.id;
	var indx;
	
	indx = objid.lastIndexOf("_");	
	str = objid.substring(0, indx);	
	str = str + "_" + fieldname;
	return str;
	
}//getDotNetID

//this returns id of the user control
//	@obj_id
//
function getUControlID(obj_id)
{
	var str;
	var indx;
	indx = obj_id.lastIndexOf("_");
	if (indx > 0)
		str = obj_id.substring(0, indx);
	else
		str = obj_id;
	return str;
}//getUControlID

//getGridIDT - RADD! 10-Oct-03
//	@obj -  the control whose id is used to find
//	@fieldname - whose id is created in this method
//
function getGridIDT(obj, fieldname)
{
	var str;
	var strtwo;
	var objid = obj.id;
	var indx;
	var indxtwo;
		
	indx = objid.lastIndexOf("_");	
	str = objid.substring(0, indx);
	indxtwo = str.lastIndexOf("_");
	strtwo = str.substring(0,indxtwo);
	strtwo = strtwo + "_" + fieldname;
	return strtwo;
	
}//getDotNetID

//getObject
//	@id - 
//	following will return an object with passed id
//
function getObject(id)
{
	if(IE4)	
		return document.all(id);
	else if(NS4)
		return document.layers(id);
	else 
		return document.getElementById(id);
}//getObject

function setFocus(obj)
{
	if(obj)
	{
		if(!obj.disabled)
		{
			obj.focus();
			if(typeof obj == "textbox")
				obj.select();
		}
	}
}//setFocus

//onClickCheck - PADD! 10-Oct-03
//	@obj - the check box
// This will not let user click or at least change the checkbox status
//  Dont ASK WHY - we want it...
//
function onClickCheck(obj)
{
	obj.checked = !(obj.checked);
}//onClickCheck

//needToSaveRow_Common - PADD! 11-Oct-03
//	@gridid - id of the grid to 
//	@nRow - row of the grid to check
//  Following is a common function called by each needToSaveRow() methods in each page
//	It checks for the chkSelected or hdSelected values if they are true or not
//
function needToSaveRow_Common(gridid, nRow)
{
		var chkSelected = getGridRowObj(gridid, nRow, "chkSelected");
		var hdSelected = getGridRowObj(gridid, nRow, "hdSelected");
		var bCheck;

		bCheck = false;
		if(chkSelected)
			bCheck = chkSelected.checked;
		if(hdSelected)
			bCheck = (parseInt(hdSelected.value) > 0);
		return bCheck;
}//needToSave_Common

//needToSaveRow - PADD! 11-Oct-03
//	@gridid - 
//	@nrow - 
//	This function should be overridden in each page
function needToSaveRow(gridid, nRow)
{
	return needToSaveRow_Common(gridid, nRow);
}//needToSaveRow

//askCancelChanges - PADD! 11-Oct-03
//	following is called by onCancel
//  it calls needToSaveRow which is defined in each page
//
function askCancelChanges()
{
	var objgrid = findGrid();
	if (!objgrid) return;
	for (var i=2; i < objgrid.rows.length + 1; i++)
	{
		if(needToSaveRow(objgrid.id, i) == true)
		{
			return (confirm(MSG_CONFIRM_CANCEL));
		}//if
	}//for i
	return true;
}//askCancelChanges
	
/* ---- PREMOVE! This if needed put in every page and then remove this --
function OnFIDPageUnload(bConfirm)
{
	if(typeof bConfirm == "undefined" || bConfirm == false)
		return;
	alert("You are about to unload this page: " + window.location.href);
	window.location = "javascript:void(0);";
	return false;
}//OnFIDPageUnload
------------------------------------------------------------------------- */


function OpenErrWindow(url)
{
	var oNewWindow;
	oNewWindow = window.open(url, "errwin", "height=400, width=480, top=100, left=600, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, status=no", true);
	oNewWindow.focus();
}//OpenErrWindow

function OpenLookupWindow(url)
{
	var oNewWindow;
	oNewWindow = window.open(url, "lookup", "height=410, width=350, top=100, left=600, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, status=no", true);
	oNewWindow.focus();
}//OpenLookupWindow

function popupWindow(url, title)
{
	var oNewWindow;
	oNewWindow = window.open(url, title, "height=350, width=490, top=100, left=300, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, status=no", true);
	//oNewWindow.opener.disabled = "disabled";
	oNewWindow.focus();
	return oNewWindow;
}//popupWindow

function popupWindowSized(url, title, width, height)
{
	var oNewWindow;
	oNewWindow = window.open(url, title, "height=" + height + ", width=" + width + ", top=100, left=300, resizable=yes, scrollbars=yes, toolbar=no, menubar=yes, location=no, status=no", true);
	//oNewWindow.opener.disabled = "disabled";
	oNewWindow.focus();
	return oNewWindow;
}//popupWindow

function popupHelpWindow(url, title, width)
{
	//if (this.oNewWindow) this.oNewWindow.close();
	
	var top = (window.screenTop ? window.screenTop: window.screenY);
	var left = 400;
	this.oNewWindow = window.open(url, title, "height=550, width=" + width + ", top=" + top + ", left=" + left + ", resizable=yes, scrollbars=yes, toolbar=no, menubar=yes, location=no, status=no", true);
	//oNewWindow.opener.disabled = "disabled";
	this.oNewWindow.focus();
	return this.oNewWindow;
}//popupWindow

function popupImage(url, title)
{
	var oNewWindow;
	oNewWindow = window.open(url, title, "height=350, width=490, top=100, left=300, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, status=no", true);
	oNewWindow.focus();
	return oNewWindow;
}//popupWindow

function GetCurrentRowControl(objControl, strothercontrol)
{
	//get the control name for default control or a new control in the same row
	var strbeforeval;
	var strafterval;
	var objid = objControl.id;
	var indx;
	var lControlName;
	
	indx = objid.lastIndexOf("_");
	strbeforeval = objid.substring(0, indx);	
	strafterval = objid.substring(indx+1,objid.length);	
	
	if (strothercontrol.length != 0 )
	{
		//return back the specified control
		lControlName = strbeforeval + '_' + strothercontrol;
	}
	else
	{
		//return back the default control
		lControlName = strbeforeval + '_' + strafterval;
	}
	return lControlName;
}


function CheckDuplicates(objControl)
{
	//check if Code already Exists

	if (objControl.value.length == 0)
	{
		//return if cell is empty
		return false;
	}
	
	var ctl;
	var msg="";
	var valid=true;
	var strcodes="";
	var ctr=0;
	var indx;

	var objgrid = findGrid();
	
	var lSelectedControl;
	lSelectedControl = GetCurrentRowControl(objControl, '');

	var controlname;
	indx = objControl.id.lastIndexOf("_");	
	var controlname = objControl.id.substring(indx+1, objControl.id.length);	
	
	ctl = objgrid.id;
	
	//check in each row for that column if it is a duplicate
	for ( var i=2; i<objgrid.rows.length + 1; i++ )
	{
		var objCurrentRowControl = getGridRowObj(ctl, i, controlname);

		if(objCurrentRowControl)
		{
			if (objCurrentRowControl.value.length != 0 && lSelectedControl != objCurrentRowControl.id)
			{
				if (ctr > 0)
				{
					strcodes = strcodes + ","
				}
				strcodes = strcodes + '"' + objCurrentRowControl.value + '"';
				ctr = ctr + 1;
			}
		}
	}//for
	
	var strthiscode;
	strthiscode = '"' + objControl.value + '"';
	
	if (InStr(strcodes,strthiscode) > -1)
	{
		alert(objControl.value + ' already exists in this column.');
		objControl.value = '';
		objControl.select();
		objControl.focus();
		return false;
	}
	return true;
}

function InStr(strSearch, charSearchFor)
/*
InStr(strSearch, charSearchFor) : Returns the first location a substring (SearchForStr)
						was found in the string str.  (If the character is not
						found, -1 is returned.)
	                        
Requires use of:
	Mid function
	Len function
*/
{
	for (i=0; i < strSearch.length; i++)
	{
		if (charSearchFor == Mid(strSearch, i, charSearchFor.length))
		{
			return i;
		}
	}
	return -1;
}

function Mid(str, start, len)
    /***
            IN: str - the string we are LEFTing
                start - our string's starting position (0 based!!)
                len - how many characters from start we want to get

            RETVAL: The substring from start to start+len
    ***/
    {
            // Make sure start and len are within proper bounds
            if (start < 0 || len < 0) return "";

            var iEnd, iLen = String(str).length;
            if (start + len > iLen)
                    iEnd = iLen;
            else
                    iEnd = start + len;

            return String(str).substring(start,iEnd);
    }

//validEmail - PADD! 13-Oct-03
//	@email - email value
//	@returnOnEmpty - this value is returned if the email is empty
//
function validEmail(email, returnOnEmpty)
{
	email = trim(email);		
	if(isEmpty(email))
		return returnOnEmpty;

	var email_exp = new RegExp("^[a-zA-Z0-9_\\-\\.]+[@]{1}[a-zA-Z0-9_\\-\\.]+[\.]{1}[a-zA-z]{2,4}$");
	return email_exp.test(email);
}//validEmail

function showtip(current,e,ctrl)
{
	//display tooltip
	var objCode;
	objCode=getObject(ctrl + "_hdCode");

	var objDesc;
	objDesc=getObject(ctrl + "_hdDescription");
	
	if(!objDesc)
		return;
		
	var text=objDesc.value;

	if (document.all)
	{
		thetitle=text.split('<br>')
		if (thetitle.length > 1)
		{
			thetitles=""
			for (i=0; i<thetitle.length-1; i++)
			thetitles += thetitle[i] + "\r\n"
			current.title = thetitles
		}
		else current.title = text
	}

	else if (document.layers)
	{
		document.tooltip.document.write( 
			'<layer bgColor="#FFFFE7" style="border:1px ' +
			'solid black; font-size:12px;color:#000000;">' + text + '</layer>')
		document.tooltip.document.close()
		document.tooltip.left=e.pageX+5
		document.tooltip.top=e.pageY+5
		document.tooltip.visibility="show"
	}
}

function hidetip()
{
	//hide tooltip
	if (document.layers)
		document.tooltip.visibility="hidden"
}

//ShowErrorInfoBox - SADD! 31-Mar-04
//	@errortype - E- Error, I - Information
//	@errormessage - Error message to be displayed
//display error messages during form validation in new window
function ShowErrorInfoBox(errortype, errormessage)
{
	if (errortype == 'E')
	{
		//open error window
		window.open('../include/frmErrInfoBox.aspx?ErrorType=E&Message=' + errormessage + '', 'Error', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,dependent=yes,scrollbars=no,resizable=no,width=400,height=100,top=200, left=100', '_blank');
	}
	else
	{
		//open information window
		window.open('../include/frmErrInfoBox.aspx?ErrorType=I&Message=' + errormessage + '', 'Information', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,dependent=yes,scrollbars=no,resizable=no,width=400,height=100,top=200, left=100', '_blank');
	}
}

function modalwin(url,mwidth,mheight, mtop, mleft)
{
	if (document.all&&window.print) //if ie5
	{
		eval('window.showModelessDialog(url,"","help:0;status=no;resizable:1;dialogWidth:'+mwidth+'px;dialogHeight:'+mheight+'px;dialogTop:'+mtop+'px;dialogLeft:'+mleft+'px")')
	}
	else
	{
		eval('window.open(url,"","width='+mwidth+'px,height='+mheight+'px,top='+mtop+'px,left='+mleft+'px,resizable=1,scrollbars=1")')
	}
}


function onBlurAmount(obj)
{
	var amt;
	//empty amount values are okay
	if (isEmpty(obj.value))
		return;
	obj.value = trim(obj.value);
	
	//get the float value	
	if(!isFloat(obj.value))
	{
		alert("Invalid amount value");
		obj.select();
		obj.focus();
		return;
	}//if

	amt = obj.value;
	amt = amt.replace(/,/g,"");
	
	amt = parseFloat(amt);
	
	if(checkMaxAmount(amt))
	{
		obj.value = amt;
		obj.value = formatAmountData(amt);
	}
	else
	{
		obj.select();
		obj.focus();
	}
}//onBlurAmount

function checkMaxAmount(amt)
{
	//get the amount
	if (amt > 999999999999)
	{
		alert("The amount is more than maximum value allowed");
		return false;
	}
	return true;
}//checkMaxAmount

function isFloat(sText)
{
	var ValidChars = "-0123456789.,";
	var bVal;		
	if(!hasValidChars(sText, ValidChars))
		return false;
	if(isNaN(parseFloat(sText)))
		return false;
	return true;
}//isNumeric
	
function formatAmountData(strValue)
{

	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '' + dblValue + '.' + strCents);
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr, fieldName)
{
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2099;

	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("{" + fieldName + "} The date format should be : mm/dd/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("{" + fieldName + "} Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("{" + fieldName + "} Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("{" + fieldName + "} Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("{" + fieldName + "} Please enter a valid date");
		return false;
	}
	return true;
}


//Function to compare two dates
function compareDates(varDate1,varDate2,strCompare)
{
	//Assuming the dates are in mm/dd/yyyy formate
	var dt1 = varDate1.split("/");
	var dt2 = varDate2.split("/");
	
	
	var objYear = dt1[2];
	var objMonth = dt1[0];
	var objDay = dt1[1];
	
	var objYear2 = dt2[2];
	var objMonth2 = dt2[0];
	var objDay2 = dt2[1];
	
	var dteDate1 = new Date(); 
	var dteDate2 = new Date(); 
	
	dteDate1.setMonth(objMonth -1);
	dteDate1.setDate(objDay);
	dteDate1.setFullYear(objYear);
	
	dteDate2.setMonth(objMonth2 -1);
	dteDate2.setDate(objDay2);
	dteDate2.setFullYear(objYear2);
	
	if ((strCompare == "LT") && (dteDate1 < dteDate2)) 
	{
		return true; 
	}
	else if ((strCompare == "GT") && (dteDate1 > dteDate2)) 
	{
		return true; 
	}
	else if ((strCompare == "EQ") && (dteDate1 = dteDate2)) 
	{
		return true; 
	}
	else if ((strCompare == "LTE") && (dteDate1 <= dteDate2)) 
	{
		return true; 
	}
	else if ((strCompare == "GTE") && (dteDate1 >= dteDate2)) 
	{ 
		return true; 
	}
	else 
	{
		return false; 
	}

}

function GotoPage(obj)
{
	var strId = obj.id; 
	var lIdx = strId.lastIndexOf("_txtPageNum");
	var ctrlName = strId.substring(0, lIdx);
	
	var objPageNum = getObject(obj.id);
	if (objPageNum)
	{
		//check if it is a valid page number
		var objtotrec = getObject(ctrlName + '_hdTotalRecords');
		if (objtotrec)
		{
			if (parseInt(objPageNum.value) <=0 || parseInt(objPageNum.value) > parseInt(objtotrec.value))
			{
				alert('Record number should be greater than 0 and less than the total records.')
				return false;
			}
			
			var objNewPageNum = getObject(ctrlName + '_hdNewPageNum');
			if (objNewPageNum)
			{
				objNewPageNum.value = objPageNum.value;
			}
			
			//loop through all the forms and see if the control is available there and
			//submit it
			var indx;
			
			var totfrm=document.forms.length;
			for(fcnt = 0; fcnt < document.forms.length; fcnt++)
			{
				for(i = 0; i < document.forms[fcnt].elements.length; i++)
				{
					var elm = document.forms[fcnt].elements[i];
					if(elm.id.indexOf(ctrlName + "_hdNewPageNum") == 0)
					{
						document.forms[fcnt].submit();
						return true;
					}//if
				}//for
			}
		}
		else
		{
			alert('Cannot validate current request.');
			return false;
		}
	}
}

//function to get the values from the query string
function Request_QueryString(FieldName) 
{
	var QueryString = '' 
	var FieldValue = '' 
	var Start = 0 
	var End = 0 
	// Grab the querystring 
	QueryString = window.location.search 
	// Convert field name and querystring to lowercase so that 
	// function is not case sensitive. 
	FieldName = FieldName.toLowerCase() 
	QueryString = QueryString.toLowerCase() 
	// Look for field as first item ... 
	Start = QueryString.indexOf(FieldName + '=') 
	// If field is not the first ... 
	if(Start!=1) { 
	// Search appended fields 
	Start = QueryString.indexOf('&' + FieldName + '=') 
	// If field wasn't found at all, return empty string. 
	if(Start==-1)
	{
	return(FieldValue)
	} 
	// Setup start position after equal sign 
	Start += FieldName.length + 2 
	} 
	else 
	{ 
	// Setup start position after equal sign 
	Start = FieldName.length + 2 
	} 
	// Search for beginning of next field 
	End = QueryString.indexOf('&', Start + 1) 
	// if another field was not defined, set end to length of querystring 
	if(End==-1){End=QueryString.length} 
	// Parse the field value 
	FieldValue = window.location.search.substring(Start, End) 
	// unescape special characters within the value (such as %20 = space character) 
	FieldValue = unescape(FieldValue) 
	// Return the results 
	return(FieldValue) 
} 
/* ================================================================================ Create Request Object ================================================================================ */ 
function request(){} 
	request.prototype.QueryString = Request_QueryString; 
	var Request = new request; 


//tooltip functions 
//------------------------------------------- start tooltip functions 
/*
var x,y,zInterval;
document.onmousemove = setMouseCoords;

function init() {
	for(i=0;i<document.getElementsByTagName("a").length;i++) {
		if(document.getElementsByTagName("a")[i].className == "toolLink") {
			document.getElementsByTagName("a")[i].onmouseout = hideToolTip;
		}
	}
}

function setMouseCoords(e) {
	if(document.all) {
		x = window.event.clientX;
		y = window.event.clientY;
	} else {
		x = e.pageX;
		y = e.pageY;
	}
}

function showToolTip(obj) 
{
	if (obj.value.length == 0)
		{return false;}
	var zText = checksinglequote(obj.value);
	doShowToolTip(zText);
}

function doShowToolTip(zText) 
{
	clearInterval(zInterval);
	document.getElementById("toolTip").style.top = (y+5) + "px";
	document.getElementById("toolTip").style.left = x + "px";
	document.getElementById("toolTip").innerHTML = checksinglequote(zText);
	document.getElementById("toolTip").style.display = "block";
	document.getElementById("toolTip").style.width = 250;
}

function hideToolTip() {
	document.getElementById("toolTip").style.display = "none";
	clearInterval(zInterval);
}

function checksinglequote(str)
{
	var vSingleQuote = str.indexOf("'"); 
	if (vSingleQuote > 0)
	{ 
		//there's a single quote in there somewhere 
		var vBeforeSingleQuote = str.substring(0,vSingleQuote); 
		//move just ahead of the single quote 
		vSingleQuote = (vSingleQuote + 1); 
		var vAfterSingleQuote = str.substring(vSingleQuote, (str.length)); 
		return vBeforeSingleQuote + "\'" + vAfterSingleQuote 
	} 
	return str;
}

this.onload = init;
*/
//------------------------------------------- end tooltip functions 

function hideSpanObject(obj)
{
	//hide the span
	if (obj)
	{
		obj.style.display = "none";
		obj.style.position = "absolute";
	}
}	


function showAppError(appErrPath)
{
	document.location.href=appErrPath;
}

//Next two functions set the url of the parent window based on the section id passed and sets
//the tree to that node too.
function setIndexBySec(secId)
{
	var parWindow = window.opener.parent.document;
	var objTree = parWindow.getElementById("ctlAppTreeMenu_tvReviewAppStat");
	var objTreeArray = parWindow.getElementById("ctlAppTreeMenu_hdTreeArray");
	var arrTree = objTreeArray.value.split("~@");
	var curIndex = objTree.selectedNodeIndex;

	var nset = false;
	var treeCtr = 0;

	while (!nset)
	{
		var curString = arrTree[treeCtr];

		if (curString.length > 0)
		{
			var curArrString = curString.split("^");
			
			if (secId == curArrString[1])
			{
				nset=true;
				gotoSecNew(curArrString[3], curArrString[1], curArrString[2], curArrString[6]);
			}
		}

		treeCtr = treeCtr + 1;
	}
}

function gotoSecNew(path, secid, type, index)
{
	var parWindow = window.opener.parent.document;
	var objUserMode = parWindow.getElementById("ctlAppTreeMenu_hdUserMode");

	window.close();
	
	if (InStr(path,"?") > -1)
	{
		window.opener.parent.location.href = path + "&Mode=" + objUserMode.value + "&secid=" + secid + "&type=" + type + "&index=" + index;
	}
	else
	{
		window.opener.parent.location.href = path + "?Mode=" + objUserMode.value + "&secid=" + secid + "&type=" + type + "&index=" + index;
	}
}


/********************************* TOOL TIP CODE ***********************************/
/*
var oToolTip = new Object();
oToolTip._topDivZIndex = 10000;
oToolTip._oBody = null;
oToolTip._oHelperIframe = null;
oToolTip._oToolTipDiv = null;
oToolTip._mousePos = new Object();
// Add dynamic div to the page
oToolTip._init = function()
{
	// Creating and adding dynamic iframe to the page source.
	oToolTip._oBody = document.getElementsByTagName("BODY").item(0);
	oToolTip._oHelperIframe = document.createElement("IFRAME");
	
	if (oToolTip._oHelperIframe)//sadd
	{
		oToolTip._oHelperIframe.style.border = 0;
		oToolTip._oHelperIframe.width = 0;
		oToolTip._oHelperIframe.height = 0;
		oToolTip._oHelperIframe.style.position = "absolute";
		oToolTip._oBody.appendChild(oToolTip._oHelperIframe);

		// Creating and adding dynamic DIV to the page source (for the tool-tip).
		oToolTip._oToolTipDiv = document.createElement("DIV");
		oToolTip._oToolTipDiv.style.border = 0;
		oToolTip._oToolTipDiv.width = 0;
		oToolTip._oToolTipDiv.height = 0;
		oToolTip._oToolTipDiv.style.position = "absolute";
		oToolTip._oBody.appendChild(oToolTip._oToolTipDiv);

		oToolTip._attachToEvent(document, 'onmousemove', oToolTip._mousemove);
	}
}

// Should return the div actual width.
oToolTip._getToolTipDivWidth = function()
{
	// We are checking the inner table because of a bug in NS/Mozilla with the DIV-->offsetWidth
	var tableWidth = "" + oToolTip._oToolTipDiv.getElementsByTagName("table").item(0).offsetWidth;
	if(tableWidth.indexOf('px') > -1)
	{
		return parseInt(tableWidth.substring(0, tableWidth.infexOf('px')));
	} 
	else 
	{
		return tableWidth;
	}
}

// Should return the div actual Height.
oToolTip._getToolTipDivHeight = function()
{
	// We are checking the inner table because of a bug in NS/Mozilla with the DIV-->offsetHeight
	var tableHeight = "" + oToolTip._oToolTipDiv.getElementsByTagName("table").item(0).offsetHeight;
	if(tableHeight.indexOf('px') > -1)
	{
		return parseInt(tableHeight.substring(0, tableHeight.infexOf('px')));
	} 
	else 
	{
		return tableHeight;
	}
}

oToolTip._mousemove = function(e)
{
	if(typeof(e) == 'undefined')e = event;
	oToolTip._mousePos.Y = e.clientY;
	oToolTip._mousePos.X = e.clientX;
	if(oToolTip._oToolTipDiv.style.visibility == 'visible')
	{
		oToolTip._fixTipPosition();
	}
}

// Will move the div and the helper iframe to the given X and Y position
oToolTip._fixTipPosition = function()
{
	// Set the Y position
	if(oToolTip._mousePos.Y > Math.round(oToolTip._oBody.clientHeight / 2))
	{
		// Open to top
		oToolTip._oHelperIframe.style.top = oToolTip._mousePos.Y - oToolTip._getToolTipDivHeight() + oToolTip._oBody.scrollTop; 
	} 
	else 
	{
		// Open to bottom
		oToolTip._oHelperIframe.style.top = oToolTip._mousePos.Y + oToolTip._oBody.scrollTop; 
	}

	// Set the X position
	if(oToolTip._mousePos.X > Math.round(oToolTip._oBody.clientWidth / 2))
	{
		// Open to left
		oToolTip._oHelperIframe.style.left = oToolTip._mousePos.X - oToolTip._getToolTipDivWidth() + oToolTip._oBody.scrollLeft; 
	} 
	else 
	{
		// Open to right
		oToolTip._oHelperIframe.style.left = oToolTip._mousePos.X + 5 + oToolTip._oBody.scrollLeft; 
	}

	oToolTip._oToolTipDiv.style.top = oToolTip._oHelperIframe.style.top;
	oToolTip._oToolTipDiv.style.left = oToolTip._oHelperIframe.style.left;
}

oToolTip._attachToEvent = function(obj, name, func) 
{
	name = name.toLowerCase();
	// Add the hookup for the event.
	if(typeof(obj.addEventListener) != "undefined") 
	{
		if(name.length > 2 && name.indexOf("on") == 0) name = name.substring(2, name.length);
		obj.addEventListener(name, func, false);
	} else if(typeof(obj.attachEvent) != "undefined")
	{
		obj.attachEvent(name, func);
	} 
	else 
	{
		if(eval("obj." + name) != null)
		{
			// Save whatever defined in the event
			var oldOnEvents = eval("obj." + name);
			eval("obj." + name) = function(e) 
			{
				try
				{
					func(e);
					eval(oldOnEvents);
				} catch(e){}
			};
		} 
		else 
		{
			eval("obj." + name) = func;
		}
	}
}

// Will show the div and the helper iframe.
oToolTip.showToolTip = function(toolTipMessage)
{
	if (oToolTip._oHelperIframe)
	{
		oToolTip._oHelperIframe.style.zIndex = oToolTip._topDivZIndex++;
		var divContent = "<table style='border:1px solid black; font-family:verdana,sans serrif; font-size=11px; background-color:LightGoldenrodYellow' cellspacing='0' cellpading='0'><tr><td>" + toolTipMessage + "</td></tr></table>";
		oToolTip._oToolTipDiv.innerHTML = divContent; 
		oToolTip._mousePos
		oToolTip._oToolTipDiv.style.zIndex = oToolTip._topDivZIndex++;
		oToolTip._oHelperIframe.style.top = oToolTip._oToolTipDiv.style.top;
		oToolTip._oHelperIframe.style.left = oToolTip._oToolTipDiv.style.left;
		oToolTip._oHelperIframe.width = oToolTip._getToolTipDivWidth();
		oToolTip._oHelperIframe.height = oToolTip._getToolTipDivHeight();
		oToolTip._oHelperIframe.style.visibility = 'visible';
		oToolTip._oToolTipDiv.style.visibility = 'visible';

		oToolTip._fixTipPosition();
	}
}

// Will hide the div and the helper iframe.
oToolTip.hideToolTip = function()
{
	if (oToolTip._oHelperIframe)
	{
		oToolTip._oHelperIframe.style.visibility = 'hidden';
		oToolTip._oToolTipDiv.style.visibility = 'hidden';
	}
}

// Attach to the onload event
oToolTip._attachToEvent(window, 'onload', oToolTip._init);


function showToolTip(obj) 
{
	if (obj.value.length == 0)
		{return false;}
	var zText = checksinglequote(obj.value);
	
	oToolTip.showToolTip(zText);
}

function hideToolTip() 
{
	oToolTip.hideToolTip();
}

function checksinglequote(str)
{
	var vSingleQuote = str.indexOf("'"); 
	if (vSingleQuote > 0)
	{ 
		//there's a single quote in there somewhere 
		var vBeforeSingleQuote = str.substring(0,vSingleQuote); 
		//move just ahead of the single quote 
		vSingleQuote = (vSingleQuote + 1); 
		var vAfterSingleQuote = str.substring(vSingleQuote, (str.length)); 
		return vBeforeSingleQuote + "\'" + vAfterSingleQuote 
	} 
	return str;
}
*/

//--------------------- Tool Tip - End ----------------------//

//--------------------- New Toop Tip Code - Start -------------------//

 document.write("<div id=\"PopupDiv\"  style=\"position:absolute; top:25px; left:50px; padding:4px; display:none; border:1px solid black; background-color:LightGoldenrodYellow; color:#000000; font-family:verdana,sans serrif; font-size=10px; z-index:100\"> </div>");
 document.write("<iframe id=\"DivShim\"  src=\"javascript:false;\"  scrolling=\"no\"  frameborder=\"0\"  style=\"position:absolute; top:0px; left:0px; display:none;\"> </iframe>");

  function showToolTip(obj)
  {
	if (obj.value.length == 0)
		{return false;}
    var zText = checksinglequote(obj.value);
    var DivRef = document.getElementById('PopupDiv');
    var IfrRef = document.getElementById('DivShim');
   
    if (DivRef && IfrRef)
    {
		DivRef.style.display = "block";
		DivRef.innerHTML = breakLines(40, zText);
		
		IfrRef.style.width = DivRef.offsetWidth;
		IfrRef.style.height = DivRef.offsetHeight;
    
		DivRef.style.top = findPosY(obj)+15; 
		IfrRef.style.top = findPosY(obj)+15; 
    
		DivRef.style.left = findPosX(obj)+10;
		IfrRef.style.left = findPosX(obj)+10;
		
		IfrRef.style.zIndex = DivRef.style.zIndex - 1;
		IfrRef.style.display = "block";
    
		attachToEvent(obj, 'onmousedown', hideToolTip);
	}
  }

  function hideToolTip()
  {
    var DivRef = document.getElementById('PopupDiv');
    var IfrRef = document.getElementById('DivShim');
    if (DivRef && IfrRef)
    {
		DivRef.style.display = "none";
		IfrRef.style.display = "none";
	}
  }

function checksinglequote(str)
{
	var vSingleQuote = str.indexOf("'"); 
	if (vSingleQuote > 0)
	{ 
		//there's a single quote in there somewhere 
		var vBeforeSingleQuote = str.substring(0,vSingleQuote); 
		//move just ahead of the single quote 
		vSingleQuote = (vSingleQuote + 1); 
		var vAfterSingleQuote = str.substring(vSingleQuote, (str.length)); 
		return vBeforeSingleQuote + "\'" + vAfterSingleQuote 
	} 
	return str;
}

function attachToEvent(obj, name, func) 
{
	name = name.toLowerCase();
	// Add the hookup for the event.
	if(typeof(obj.addEventListener) != "undefined") 
	{
		if(name.length > 2 && name.indexOf("on") == 0) name = name.substring(2, name.length);
		obj.addEventListener(name, func, false);
	} else if(typeof(obj.attachEvent) != "undefined")
	{
		obj.attachEvent(name, func);
	} 
	else 
	{
		if(eval("obj." + name) != null)
		{
			// Save whatever defined in the event
			var oldOnEvents = eval("obj." + name);
			eval("obj." + name) = function(e) 
			{
				try
				{
					func(e);
					eval(oldOnEvents);
				} catch(e){}
			};
		} 
		else 
		{
			eval("obj." + name) = func;
		}
	}
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	if(typeof(e) == 'undefined')
		e = event;
	if(e)
		return e.clientY - 15;

/*
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
*/

}


function breakLines(max, text) 
{
	max--;
	text = "" + text;
	var temp = "";
	var chcount = 0; 
	for (var i = 0; i < text.length; i++) // for each character ... 
	{   
		var ch = text.substring(i, i+1); // first character
		var ch2 = text.substring(i+1, i+2); // next character
		if (ch == '\n') // if character is a hard return
		{  
			temp += ch;
			chcount = 1;
		}
		else
		{
			if (chcount >= max && ch == ' ') // line has max chacters on this line
			{
				temp += '<br>' + ch; // go to next line
				chcount = 1; // reset chcount
			}
			else  // Not a newline or max characters ...
			{
				temp += ch;
				chcount++; // so add 1 to chcount
			}
		}
	}
	return (temp); // sends value of temp back
}

//---------------------- New Tool Tip Code - End ----------------------//


function Now_MMDDYYYY()
{
	//returns todays date in mm/dd/yyyy format
	var aceDate=new Date()
	var aceYear=aceDate.getYear()
	if (aceYear < 1000)
	aceYear+=1900
	var aceDay=aceDate.getDay()
	var aceMonth=aceDate.getMonth()+1
	if (aceMonth<10)
	aceMonth="0"+aceMonth
	var aceDayMonth=aceDate.getDate()
	if (aceDayMonth<10)
	aceDayMonth="0"+aceDayMonth
	return (aceMonth+"/"+aceDayMonth+"/"+aceYear);
}

//Popup window code added by Rajeev B
// Example usage:
// var win = new PopupWindow();
// win.ShowSideHelp('url', width_of_popupwindow);
function PopupWindow ()
{
	window.PopupWindowInstance = this;
	
	this.ShowSideHelp = PopupWindow_ShowSideHelp;
	this.CloseSideHelp = PopupWindow_CloseSideHelp;
	this.windowRef = null;
}

function screenLeftVal()
{
	if (typeof(window.screenLeft) == "undefined")
		return window.screenX;
	else
		return window.screenLeft;
}

function screenTopVal()
{
	if (typeof(window.screenTop) == "undefined")
		return window.screenY;
	else
		return window.screenTop;
}

function PopupWindow_ShowSideHelp (sHelpURL, cxHelpWidth)
{
	this.gHelpURL = sHelpURL;
	this.gHelpWidth = cxHelpWidth;
	
	if (typeof(window.SideHelpWindow) != "undefined" && !window.SideHelpWindow.closed)
	{
		PopupWindow_CloseSideHelp();
		window.clearInterval(SideHelpWindowCloseCheckTimer);
		window.SideHelpWindowCloseCheckTimer = null;
		window.popTimer = window.setInterval(OpenPopupWindow, 500);
	}
	else
	{
		OpenPopupWindow()
	}
	//if ((window.SideHelpWindow == null) || (window.SideHelpWindow == false))

	//else
	//	{
	//	window.open(sHelpURL, "PopupWindowHelp");
	//	}
}

function OpenPopupWindow()
{
		var sHelpURL = this.gHelpURL;
		var cxHelpWidth = this.gHelpWidth;
		
		var _tempLeft;
		var _tempTop;
		var _tempWidth;
		var _tempHeight;
		
		if (window.popTimer)
			window.clearInterval(window.popTimer);
			
		_tempLeft = screenLeftVal();
		_tempTop = screenTopVal();
		
		window.moveTo(_tempLeft, _tempTop);
		this._saveLeft = _tempLeft - (screenLeftVal() - _tempLeft);
		this._saveTop = _tempTop - (screenTopVal() - _tempTop);
		window.moveTo(this._saveLeft, this._saveTop);
		
		_tempWidth = window.document.body.clientWidth;
		_tempHeight = window.document.body.clientHeight;
		window.resizeTo(_tempWidth, _tempHeight);
		this._saveWidth = _tempWidth + (_tempWidth - window.document.body.clientWidth);
		this._saveHeight = _tempHeight + (_tempHeight - window.document.body.clientHeight);
		window.resizeTo(this._saveWidth, this._saveHeight);
		
		window.moveTo(0,0);
		window.resizeTo(screen.availWidth - cxHelpWidth, screen.availHeight);
		var params;
		params = "sl=" + this._saveLeft + "&st=" + this._saveTop + "&sw=" + this._saveWidth + "&sh=" + this._saveHeight
		window.SideHelpWindow = window.open(sHelpURL + "?" + params, "PopupWindowHelp", "scrollbars=yes, left=" + (screen.availWidth - cxHelpWidth - 5).toString() + ",top=0,width=" + cxHelpWidth.toString() + ",height=" + (screen.availHeight - 50).toString());
		window.SideHelpWindowCloseCheckTimer = window.setInterval(PopupWindow_CheckForClose, 200);
}

function PopupWindow_CheckForClose()
{
	if (window.SideHelpWindow.closed)
	{
		PopupWindow_CloseSideHelp();
		window.clearInterval(SideHelpWindowCloseCheckTimer);
		window.SideHelpWindowCloseCheckTimer = null;
	}
}

function PopupWindow_CloseSideHelp ()
{
	if (window.SideHelpWindow != null)
		{
		window.clearInterval(SideHelpWindowCloseCheckTimer);
		window.SideHelpWindowCloseCheckTimer = null;
		window.SideHelpWindow.close();
		window.SideHelpWindow = null;
		var pw = window.PopupWindowInstance;
		window.moveTo(pw._saveLeft, pw._saveTop);
		
		if (typeof(window.screenTop) == "undefined")
			window.resizeTo(pw._saveWidth, pw._saveHeight + 100);
		else
			window.resizeTo(pw._saveWidth, pw._saveHeight);
		}
}

function ParentWindow_CloseSideHelp ()
{
	opener.window.moveTo(_tempLeft, _tempTop);
	
	if (typeof(window.screenTop) == "undefined")
		opener.resizeTo(_tempWidth, _tempHeight + 100);
	else
		opener.resizeTo(_tempWidth, _tempHeight);
}

// This function can be used to trap enter key and set a button to be the default button.
// Usage:
// Add a function to the code-behind like this:
//  Private Sub SetDefaultButton(ByVal txt As TextBox, ByVal defaultButton As Button)
//		txt.Attributes.Add("onkeydown", "fnTrapKD(" + defaultButton.ClientID + ",event)")
//	End Sub
//
// In the page load, call SetDefaultButton passing the appropriate textbox and the default button.
function fnTrapKD(btn, event){

 if (document.all){

  if (event.keyCode == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if (document.getElementById){

  if (event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if(document.layers){

  if(event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

}

