//var elements = document.getElementsByTagName('input');

var oPopup;// = window.createPopup();
var oPopBody;// = oPopup.document.body; 
var toolX;
var toolY;

function page_onload()
{
	switch(screen.width)
	{
		case 800: 
		
			/*var otblMain = document.all("tblTemplateMain")
			if(otblMain)
				otblMain.style.width="779px";
			
			var opnlMain = document.all("pnlMain")
			if(opnlMain)
				opnlMain.style.height="140px";*/
			
			break;
		default: 
			/*var otblMain = document.all("tblTemplateMain")
			if(otblMain)
				otblMain.style.width = "700px";
			
			var opnlMain = document.all("pnlMain")
			if(opnlMain)
				opnlMain.style.height="300px";
			*/
			break;
	}
}

document.onload = page_onload();
 
function confirmDelete()
{	
	//return checkKeysExists();	
	var bRet = checkKeysExists();
	
	//added this line to correct the problem
	//in resetting the form values (changes to 
	//the grids default behaviour's side effect)
	setFieldValue('hdnGridRow', '');
	//alert(frmPage.btnAction.value);
	//alert(bRet);
	if(bRet)
		return confirm("Delete the Record?");
	else
		return false;
}	

//sample for All select
function MoveBulkItem(fromObj,toObj)
{
	var TotalItem = fromObj.length ;
	
	for (i=0; i < TotalItem; i++)
	{  
         var newText = fromObj.options[0].text;
         var newValue = fromObj.options[0].value;

         var newOption = new Option(newText,newValue)

         toObj[toObj.length] = newOption;

         fromObj[0] = null;
	}
	
	//Jai added this on 10/14/2003
	//calls form changed function
	// to update the global function
	formChanged();

}

// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a 
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before 
//  submitting the form so the values will be sent to the server.
function selectAllOptions(obj) 
{
	//alert(obj.options.length);
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
		}
	}


function MoveItem(fromObj,toObj)
{
	//extended the functionality to move 
	//multiple list items - Jai 04/11/03
	
	//check if listboxes exist
	var i = 0;
	var intListCount = fromObj.length;
	if(fromObj && toObj) 
	{
		var selIndex = fromObj.selectedIndex;
		if (selIndex < 0)
		{
			//alert("Choose an item to move");
			try
			{
				//fromObj.focus();
				fieldFocus(fromObj);
			}
			catch(e)
			{
				return;
			}
			return;
		}	
		else //Jai added this on 10/14/2003
		{
			//calls form changed function
			// to update the global function
			formChanged();
		}
		
		for (i=0; i<intListCount; i++)
		{
			if (fromObj.item(i).selected)
			{
				var newText = fromObj.options[i].text;
				var newValue = fromObj.options[i].value;
				
				var newOption = new Option(newText,newValue)

				toObj[toObj.length] = newOption;
			}
		}	
		
		for(i=(intListCount-1); i>-1; --i)
		{
			if (fromObj.item(i).selected)
			{
				fromObj[i] = null;
			}
		} 
	}	   
	else if(fromObj)
	{
		for(i=(intListCount-1); i>-1; --i)
		{
			fromObj[i] = null;
		} 
	}
	
}

function makeUpper(fldObj)
{
	fldObj.value = fldObj.value.toUpperCase();
}

function openWindow(url, width, height)
{
	var Args = '';
	//alert(url);
	var Features = "dialogWidth:" + width + "px;dialogHeight:" + height +"px;center:1;status:0;scroll:1;help:0;resizable:1" ;
	return window.showModalDialog(url,Args,Features)
}

function formatTime(fld, e ) {
var key = '';
var len = 0;
var strCheck = '0123456789';
var whichCode = (window.Event) ? e.which : e.keyCode;
key = String.fromCharCode(whichCode);
if (whichCode == 13) return true;  // Enter

if (strCheck.indexOf(key) == -1) return false; 

len = fld.value.length
if (len > 4) return false;
if (len == 2 ) fld.value += ":" ;

}

	
function trim(inputString) {
	//function added by Jai - 05/05/03
	
	// Removes leading and trailing spaces from the passed string. Also removes
	// consecutive spaces and replaces it with one space. If something besides
	// a string is passed in (null, custom object, etc.) then return the input.
	
	if (typeof inputString != "string") 
	{ 
		return inputString; 
	}
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") 
	{ // Check for spaces at the beginning of the string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") 
	{ // Check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) 
	{ // Note that there are two spaces in the string - look for multiple spaces within the string
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
	}
	
	return retValue; // Return the trimmed string back to the user

} // Ends the "trim" function



function getFieldValue(field)
{
	//function added by Jai - 05/05/03
	//debugger
	//generic function which gets the field's value
	switch(field.type)
	{
		case "text" :
		case "textarea" :
		case "password" :
		case "hidden" :
		case "file" :
			return field.value;

		case "select-one" :
			var i = field.selectedIndex;
			if (i == -1)   return "";
			else   return field.options[i].value; //(field.options[i].value == "") ? field.options[i].text : field.options[i].value;

		case "select-multiple" :
			var allChecked = new Array();
			var intLength = field.options.length;
			//if (intLength < 2)
			for(i = 1; i < intLength; i++)
			if(field.options[i].selected)
				allChecked[allChecked.length] = field.options[i].value;//(field.options[i].value == "") ? field.options[i].text : field.options[i].value;
			return allChecked;

		case "button" :
		case "reset" :
		case "submit" :
			return "";

		case "radio" :
		case "checkbox" :
			if (field.checked) { return field.value; } else { return ""; }
		default :
			if (field.tagName == "TD")
			{
				return field.innerHTML;
			}
			try{
			
				if(field[0].type == "radio")
				{
				for (i = 0; i < field.length; i++)
					if (field[i].checked)
						return field[i].value;

				return "";
				}
				else if(field[0].type == "checkbox")
				{
				var allChecked = new Array();
				for(i = 0; i < field.length; i++)
					if(field[i].checked)
						allChecked[allChecked.length] = field[i].value;

				return allChecked;
				}
				else
				var str = "";
				for (x in field) { str += x + "\n"; }
				alert("I couldn't figure out what type this field is...\n\n" + field.name + ": ???\n\n\n" + str + "\n\nlength = " + field.length);
				break;
			}
			catch(e)	
			{
				if (field.tagName == "TD")
				{
					return field.innerHTML;
				}
			}
	}

	return "";
}
		

function checkValidDate(dateStr) 
{
	//function added by Jai - 05/05/03
	
	// dateStr must be of format month day year with either slashes
	// or dashes separating the parts. Some minor changes would have
	// to be made to use day month year or another format.
	// This function returns True if the date is valid.
	
	//modified this function on 08/11/03 - Jai
	//added the following line to accomodate datetime field
	//in the same form
	//debugger
	dateStr = trim(dateStr.substr(0,10)); 
	//alert(dateStr)
	var slash1 = dateStr.indexOf("/");
	if (slash1 == -1) 
	{ 
		slash1 = dateStr.indexOf("-"); 
	}
	// if no slashes or dashes, invalid date
	if (slash1 == -1) 
	{ 
		return false; 
	}
	var dateMonth = dateStr.substring(0, slash1)
	var dateMonthAndYear = dateStr.substring(slash1+1, dateStr.length);
	var slash2 = dateMonthAndYear.indexOf("/");
	if (slash2 == -1) 
	{ 
		slash2 = dateMonthAndYear.indexOf("-"); 
	}
	// if not a second slash or dash, invalid date
	if (slash2 == -1) 
	{ 
		return false; 
	}
	var dateDay = dateMonthAndYear.substring(0, slash2);
	var dateYear = dateMonthAndYear.substring(slash2+1, dateMonthAndYear.length);
	if ( (dateMonth == "") || (dateDay == "") || (dateYear == "") ) 
	{ 
		return false; 
	}
	// if any non-digits in the month, invalid date
	for (var x=0; x < dateMonth.length; x++) 
	{
		var digit = dateMonth.substring(x, x+1);
		if ((digit < "0") || (digit > "9")) { return false; }
	}
	// convert the text month to a number
	var numMonth = 0;
	for (var x=0; x < dateMonth.length; x++) 
	{
		digit = dateMonth.substring(x, x+1);
		numMonth *= 10;
		numMonth += parseInt(digit);
	}
	if ((numMonth <= 0) || (numMonth > 12)) 
	{ 
		return false;
	}
	// if any non-digits in the day, invalid date
	for (var x=0; x < dateDay.length; x++) 
	{
		digit = dateDay.substring(x, x+1);
		if ((digit < "0") || (digit > "9")) 
		{ 
			return false; 
		}
	}
	// convert the text day to a number
	var numDay = 0;
	for (var x=0; x < dateDay.length; x++) 
	{
		digit = dateDay.substring(x, x+1);
		numDay *= 10;
		numDay += parseInt(digit);
	}
	if ((numDay <= 0) || (numDay > 31)) 
	{ 
		return false; 
	}
	// February can't be greater than 29 (leap year calculation comes later)
	if ((numMonth == 2) && (numDay > 29)) 
	{ 
		return false; 
	}
	// check for months with only 30 days
	if ((numMonth == 4) || (numMonth == 6) || (numMonth == 9) || (numMonth == 11)) 
	{ 
		if (numDay > 30) 
			{ 
				return false; 
			} 
	}
	// if any non-digits in the year, invalid date
	for (var x=0; x < dateYear.length; x++) 
	{
		digit = dateYear.substring(x, x+1);
		if ((digit < "0") || (digit > "9")) 
		{ 
			return false; 
		}
	}
	// convert the text year to a number
	var numYear = 0;
	for (var x=0; x < dateYear.length; x++) 
	{
		digit = dateYear.substring(x, x+1);
		numYear *= 10;
		numYear += parseInt(digit);
	}
	// Year must be a 2-digit year or a 4-digit year
	if ( (dateYear.length != 2) && (dateYear.length != 4) ) 
	{ 
		return false; 
	}
	// if 2-digit year, use 50 as a pivot date
	if ( (numYear < 50) && (dateYear.length == 2) ) 
	{ 
		numYear += 2000; 
	}
	if ( (numYear < 100) && (dateYear.length == 2) ) 
	{ 
		numYear += 1900; 
	}
	if ((numYear <= 0) || (numYear > 9999)) 
	{ 
		return false; 
	}
	// check for leap year if the month and day is Feb 29
	if ((numMonth == 2) && (numDay == 29)) 
	{
		var div4 = numYear % 4;
		var div100 = numYear % 100;
		var div400 = numYear % 400;
		// if not divisible by 4, then not a leap year so Feb 29 is invalid
		if (div4 != 0) { return false; }
		// at this point, year is divisible by 4. So if year is divisible by
		// 100 and not 400, then it's not a leap year so Feb 29 is invalid
		if ((div100 == 0) && (div400 != 0)) { return false; }
	}
	// date is valid
	return true;
}

	
/*****************STARTS KEY DOWN EVENT HANDLER*************************/ 
//event handler added by Jai - 05/09/03
// handles Keydown events on the document
document.onkeydown = 
	function()
	{
		//enterKeyToSubmit(event, this.form);
		//debugger
		objForm = document.frmPage;
		if(objForm) 
		{
			
			var bRet = enterKeyToSubmit(objForm);
			if (objForm && window.event && window.event.keyCode == 13)
				return bRet;
				
		}	
	}	
	

function enterKeyToSubmit(objForm) 
{
	
	//function added by Jai - 05/09/03
	//handles Enter and Backspace keys 
	//pressed on the document and 
	
	/*
		IMPORTANT NOTE: THIS FUNCTION USES HARD CODED VALUES
		- hard coded for this specific application for
		btnSearch and btnSave control which are used 
		as a standard practice.
	*/
	//debugger
	
	var FORBIDDENTAGS = "|SELECT|INPUT|TEXTAREA|SELECT-ONE|SELECT-MULTIPLE|" //control names to ignore
	var elTag = window.event.srcElement.tagName; //get control name
	var strValidTags = "|FORM|SELECT|INPUT|TEXTAREA|PASSWORD|SELECT-ONE|SELECT-MULTIPLE|RADIO|CHECKBOX|LINK|";
	
	if (strValidTags.indexOf("|" + elTag + "|")>=0)
	{
		var oRetMsg = document.all("rtnmsg");
		if(oRetMsg)
		{
			oRetMsg.innerText = " ";
		}
	}
	
	if (window.event.keyCode == 8){ // Backspace
		if (FORBIDDENTAGS.indexOf("|" + elTag + "|")>=0){
			// Disable
			event.cancelBubble = true;
			event.keyCode = 0;
			return false;
		}
	}
	
	if (objForm && window.event && window.event.keyCode == 13) //enter key
	{
		//ignore enter key when in textarea
		if(elTag == "TEXTAREA")
		{
			event.cancelBubble = true;
			event.keyCode = 0;
			return false;
		}
		//debugger
		var objSave = objForm.btnSave;
		
		var oEnterKey = document.all("hdnSavedWithEnterKey");//not used
		if (objSave)
		{		
			var strInput = confirm("Do you want to SAVE the data now?");
			if (strInput == true)
			{
			    //debugger
			    selectListBoxes();
				var bRet = isFormFormattedCorrectly(objForm);
				//alert('bRet1: ' + bRet);
				//objSave.onclick();
				if(bRet)
				{
					//objSave.onclick();
					//alert("got it");	
					//frmPage.submit();
					if (oEnterKey)
						oEnterKey.value = "1";
					//return __doPostBack('btnSave','');	
				}
				else
				{
					oEnterKey.value = "1";
					return false;
				}
			}
			else
				return false;	
		}
		else
		{
			var objSearch = objForm.btnSearch;
			objSearch.onclick();		
		}
	}  
	else
	{
		return true;
	}  
}

/*****************ENDS KEY DOWN EVENT HANDLER*************************/ 


function checkPageMove(objThis)		
{
	//alert("hello " + g_bFormChanged);
	if (g_bFormChanged == true)
	{
		var bRet = confirm("There was an attempt to change the data, do you want to save the EDITED/ADDED information?");
		if (bRet == true)
		{
			var objForm = document.frmPage;
			var objSave = objForm.btnSave;
			//alert('helo');
			//objForm.submit();
			if(objSave)
			{
				try
				{
					//alert(requiredFields.length);
					selectListBoxes();
					var bRet = isFormFormattedCorrectly(objForm);
					//alert('bRet: ' + bRet);
					//objSave.onclick();
					if(bRet)
					{
						/*
						not used
						var objhdnDetailButton = objForm.hdnDetailButton;
						if(objhdnDetailButton && objThis)
							objhdnDetailButton.value = objThis.id;
						
						return __doPostBack('btnSave','');	
						*/
					}	
					return false;
					//objForm.submit();
					//alert("hello");
				}
				catch(e)
				{
					//alert(e.description);
					return false;
				}
			
			}
			return false;	
		}	
		else
			return false;
		/*var bRet = confirm("There was an attempt to change the data, do you want to save the changed information?");
		if (bRet == true)
		{
			///
			////debugger
			//var objForm = document.frmPage;
			//var objSave = objForm.btnSave;
			////alert('helo');
			//objForm.submit();
			////objSave.onclick();
			///
			return false;
		}
		else
		{
			//return true;
			return checkKeysExists();
		}	
		*/
	}
	else
		{
			//return true;
			return checkKeysExists();
		}	
}

function formChanged()
{
	//added by Jai on 07/07/03
	//this function updates the global flag.
	g_bFormChanged = true;
	//alert('formChanged: ' + g_bFormChanged );
}

function checkFromToDate(strStartDate, strEndDate, strMessage)
{
/********************
* var objStart = frm.txtStartDate;
* var objEnd = frm.txtEndDate;
*******************/
/*	if (objStart != "" && objEnd) 
	{
		var strStartDate = trim(objStart.value);
		var strEndDate = trim(objEnd.value);
*/
		if (trim(strStartDate) != "" && trim(strEndDate) != "")
		{
			var numStart = Date.parse(strStartDate);
			var numEnd	= Date.parse(strEndDate) ;
			var numDiffrence = numEnd - numStart ;
			if (numDiffrence >= 0) 
				return true; 
			else
			{
				addErrorMessage(strMessage);
				return displayError();	
			}	
		}
/*	}		
*/
}


function checkMonth(dateMonth)
{
	// if any non-digits in the month, invalid date
	for (var x=0; x < dateMonth.length; x++) 
	{
		var digit = dateMonth.substring(x, x+1);
		if ((digit < "0") || (digit > "9")) { return false; }
	}
	// convert the text month to a number
	var numMonth = 0;
	for (var x=0; x < dateMonth.length; x++) 
	{
		digit = dateMonth.substring(x, x+1);
		numMonth *= 10;
		numMonth += parseInt(digit);
	}
	if ((numMonth <= 0) || (numMonth > 12)) 
	{ 
		return false;
	}
	return true;
}

function checkNumberDependency(intToCheckWith, intCheckThis, strMessage)
{
	if ((! isNaN(intCheckThis)) && (! isNaN(intToCheckWith)))
	{
		//toCheckWith is greater than to check this
		if (intToCheckWith >= intCheckThis)
		{
			return true;
		}
		else
		{
			addErrorMessage(strMessage);
			return false;
		}

	}
	else
		return false;
}


function getTimeString(strDateTime)
{
	//added by Jai on Thursday, August 14, 2003
	//this is a utility function for 'checkDateDependency'
	
	strDateTime = strDateTime.split(" ");
	if (strDateTime.length > 1 )
	{
		var strAMPM = trim(strDateTime[2]).toUpperCase();
		
		//var strDate = strDateTime[0];
		var strTime = strDateTime[1];
		strTime = strTime.split(":");
		if (strAMPM =="AM")
		{	
			if (strTime[0] == "12")
				strTime[0] = "00";
		}
		else//"PM"
		{
			if (strTime[0] == "12")
				strTime[0] = strTime[0]; //leave it alone (check later ??)
			else
				strTime[0] = parseInt(strTime[0]) + 12 ;
		}
		strTime = strTime.join(":");
		
		return strDateTime[0] + " " + strTime + ":00";
	}
	else
		return  strDateTime = strDateTime.join(" ");
		
	
}
function checkDateDependency(strStartDate, strEndDate, strMessage)
{
	//
	//format being sent: "3/12/1999 12:01:00 AM"
	// format expected by date object...
	// "3/12/1999 00:01:00";
	//
	
	//debugger
	if (trim(strStartDate) != "" && trim(strEndDate) != "")
	{
		
		var strStartDateTime = getTimeString(strStartDate); 
		var strEndDateTime = getTimeString(strEndDate); 
		
		var dtStart = new  Date(strStartDateTime); 
		var dtEnd	= new Date(strEndDateTime); 
		
		var numStart = dtStart.valueOf(); 
		var numEnd	= dtEnd.valueOf() ; 
		
		var numDiffrence = numEnd - numStart;
		
		if (numDiffrence >= 0) 
			return true; 
		else
		{
			addErrorMessage(strMessage);
			return false;
		}	
	}
	else
		return true;
}

function autoTabToField(cur_field, char_max, goto_field)
{    
//added by Jai on 05/21/03
//auto table to specified field
//after max number of characters are enterd.
//does not check for numerics.
	if (cur_field.value.length > (char_max-1)){
			goto_field.focus();
	}
}

/*
//Dropdown/selectlist autoselect/complete
//Jai added this code - 06/26/03
// --------------------------autoComplete Starts Here---------------------------------
// autoComplete (text_input, select_input, ["text"|"value"], [true|false])
//   Use this function when you have a SELECT box of values and a text
//   input box with a fill-in value. Often, onChange of the SELECT box
//   will fill in the selected value into the text input (working like
//   a Windows combo box). Using this function, typing into the text
//   box will auto-select the best match in the SELECT box and do
//   auto-complete in supported browsers.
//   Arguments:
//      field = text input field object
//      select = select list object containing valid values
//      property = either "text" or "value". This chooses which of the
//                 SELECT properties gets filled into the text box -
//                 the 'value' or 'text' of the selected option
//      forcematch = true or false. Set to 'true' to not allow any text
//                 in the text box that does not match an option. Only
//                 supported in IE (possible future Netscape).
// -------------------------------------------------------------------
function autoComplete (field, select, property, forcematch) {
	var found = false;
	for (var i = 0; i < select.options.length; i++) {
	if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
		found=true; break;
		}
	}
	if (found) { select.selectedIndex = i; }
	else { select.selectedIndex = -1; }
	if (field.createTextRange) {
		if (forcematch && !found) {
			field.value=field.value.substring(0,field.value.length-1); 
			return;
			}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) {
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) {
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
				}
			}
		}
	}


// --------------------------autoComplete Ends Here---------------------------------
*/

//---added by Jai - 06/27/03
// to check if primar key is present if user tries to leave
// from current page without first saving the info.
function checkKeysExists(keyFields)
{
	//alert('chks');
	errorCount = 0;
	errorMessage = "";
	var strValue = "";	
		
	if (typeof(keyFields) == "object")
	{
		//comes here when array is passed
		//loop thru and check if all the fields are present
		var reqdLen = keyFields.length;
		
		for (var x=0; x < reqdLen; x++) 
		{
			eval("var field = document.form." + requireds[x]);
			
			if (field) 
			{ 
				strValue = strValue + getFieldValue(field);
			}
		}	
		
	}//end if for object check
	else
	{
		
		
		if (keyFields == null)
		{
			//no value is passed
			//by defalut hdnKeySeq is used to store key field info.
			var objKeyField = document.all("hdnKeySeq");
			
			if (objKeyField)
				strValue = getFieldValue(objKeyField);
			else
				alert("No default key element present to check.");	
			//alert(strValue );
		}//end if for passed keyfiled is null
		else
		{	
			//if any other field is passed then 
			//check if its value exists.
			if (keyFields)
				strValue = getFieldValue(keyFields);
			else
				alert("Default key element expected to check is not available.");	
			
		}//end else for passed keyfiled is null
		
		
			
	}//end else for object check

	if (strValue == "" )
	{
		addErrorMessage("Please Select the data from the grid before trying to perform this action.")	 
		displayError();
		return false;
	}
	else
		return true;
		
}

function replaceSubstring(inputString, fromString, toString) 
{
	//added by Jai on 07/07/03
	//extends the javascript's functionality to replace
	//multiple occurances os the string.
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

function setFieldValue(oFieldID, strValue)
{
	//this function is written 
	// to set the btnAction hidden field
	// it helps in resetting the form when page is reloaded.
	if (typeof(oFieldID)=="object")
	{
		if(oFieldID) 
			oFieldID.value = strValue;
	}
	else
	{
		var objField = document.all(oFieldID);
		if (objField )
			objField.value = strValue;
	}	
		
}

/***********************Tooltip for dropdown's starts here**********************/
//Added by Jai on 07/31/03
// this utility gives a tooltip for the options/elements of the
//dropdown/listbox if the width is less than the text of the elements data
//tipical usage example:
// onmouseover="showpop(this)" onmouseout="hidepop();"

	

document.onmousedown = 
	function()
	{
		//enterKeyToSubmit(event, this.form);
		//debugger
		objForm = document.frmPage;
		if(objForm) 
		{
			var elTag = window.event.srcElement.tagName; //get control name
			var strValidTags = "|FORM|SELECT|INPUT|TEXTAREA|PASSWORD|SELECT-ONE|SELECT-MULTIPLE|RADIO|CHECKBOX|LINK|";
			
			if (strValidTags.indexOf("|" + elTag + "|")>=0)
			{
				var oRetMsg = document.all("rtnmsg");
				if(oRetMsg)
				{
					oRetMsg.innerText = " ";
				}
			}
			
			var oGridNum = document.all("hdnGridNum");
			var gridNum = "";
			if(oGridNum)
			{ 
				gridNum = oGridNum.value;
				
				if ((gridNum == null) || (trim(gridNum) == ""))
					gridNum = "1";
				eval("var oRow = document.all('rowHeader" + gridNum + "');");
				if(oRow)
				{
					oRow.onclick = 
						function()
						{
							
							//<INPUT id="hdnSortField" type="hidden" name="hdnSortField" >
							//<INPUT id="hdnSortOrder" type="hidden" name="hdnSortOrder" >
							var oSortField = document.all("hdnSortField");
							var oSortOrder = document.all("hdnSortOrder");
							
							
							var srcElem = window.event.srcElement;
							if (srcElem)
							{
								//loop tru the cells to find the matching sortfiled 
								// this can be improved by get to the cell count
								//directly... ??
								for (var n=0; n<srcElem.parentElement.cells.length; n++)
								{
									if(srcElem.SortField == srcElem.parentElement.cells(n).SortField)
									{
										//store the values of sort column and order.
										oSortField.value = n;
										oSortOrder.value = srcElem.className;
										//alert('setting n: ' + oSortField.value + '; srcElem.className: ' + oSortOrder.value);
										
									}//check field name 
										
								}// end for loop
								//eval ("SortJS" + gridNum + "('');");
								/*eval ("var srcElem = rowHeader" + gridNum + ".cells(" + oSortField.value + ");");
								if (srcElem)
								{
									//alert('hello1: ' + srcElem.className);
									if (srcElem.className == 'clsTDSortUp')
									{
										srcElem.className = 'clsTDSortDown';
										strSortOrder = 'descending';
									}
									else
									{
										srcElem.className = 'clsTDSortUp';
										strSortOrder = 'ascending';
									}
									
									CustomSortJS(srcElem, srcElem.className, gridNum);
								}
								window.event.cancelBubble = true;
								window.event.keyCode = 0;
								*/
							}//end check srcElem
							
								
						}//end function()	
				}//end check table row exists	
			}//end check hidden grid num field	
	
		}// end check form exists	
	}// end function()

/***************end custom keydown function overloading*///////////

/****************Adds Filter Criteria Starts*****************************/

function addFilterCriteria(bDateHasSpace)
{
	/* 
	*	Jai added this function on 09/17/2003
	*	builds the filter (where ) condition .
	*
	*	Should extended (later)to build XML string
	*	to build the table and moving data accross.
	*/
	//debugger
	var oTable = document.all("tblFilter")
	var oQField = document.all("selQueryField")
	var oQOPerator = document.all("selQueryOperator")
	var oQCriteria = document.all("txtQueryCriteria")
	var bReplaceExpression = false;
	//check if objects exist
	if(oTable && oQField && oQOPerator && oQCriteria)
	{
		//set Query variables
		var arrValType = oQField.value;//need to get field value into an array
									   //data is of the format 'cu.cleanup_seq|$pbcc$|System.String'
									   //   where:
									   //		cu.cleanup_seq	- QueryField Name 
									   //		|$pbcc$|		- Saperator
									   //		System.String	- Datatype	  
									   
		var strFieldName = oQField.options[oQField.selectedIndex].text;
		var strValue = trim(oQCriteria.value);//.toUpperCase();
		var strDisplayValue = strValue;
		var strOperator = oQOPerator.value;
		strOperator = strOperator.toLowerCase();
		
		//check if no value is entered return false (do not accept).
		if((strOperator.indexOf('is') <= 0) && (strValue == "") )
		{
			oQCriteria.select();
			//oQCriteria.focus();
			fieldFocus(oQCriteria);
			return false;
		}	 
		
		//for contracts application we have set the saperator as |$pbcc$|
		arrValType = arrValType.split("|$pbcc$|");
		//as stated earlier (above).
		//first (0) element will be field name
		//second(1) element will be datatype
		if (typeof(arrValType) == "object")
		{
			if (arrValType.length > 1)
			{
				if (arrValType[0].indexOf("|$spl$|") > 0 )
				{
					var strFieldName = arrValType[0].replace("|$spl$|", "");
					var oField = document.all("hdnSPLConditions");
					//special case when more than one field name 
					//have same name (from diffrent table) 
					strFieldName = strFieldName.replace("|$_$|", ".");
					
					arrValType[0] = strFieldName;
					if (oField)
					{
						bReplaceExpression = true;
						//debugger
						//strExprCondition = oField.value;
						try
						{
							
							eval("strExprCondition = oField." + strFieldName.replace(".", "_"));
							if(strExprCondition)
							{
								//continue
							}
							else
							{
								alert("Encountered problems while adding the criteria, please select another field.");
								return false;
							}
				
						}
						catch(e)
						{
							//do nothing
							alert("Encountered problems while adding the criteria, please select another field.");
							return false;
						}
						//replaceSubstring(strCondition, "|$expr$|", "");
						//alert(strExprCondition);
					}
					else
					{
						//do nothing
						alert("Encountered problems while adding the criteria, please select another field.");
						return false;
					}	
					
					strFieldName = oQField.options[oQField.selectedIndex].text;
				}
				//check for data types, process accordingly
				// NOTE: need to expand to handle all data types
				/*
				------------------------------------
				VB.NET          CLR                 
				------------------------------------
				Boolean      -  System.Boolean      
				Byte         -  System.Byte         
				Native       -  System.Int32        
				Integer      -  System.Int64        
				Float        -  System.Double       
				Decimal      -  System.Decimal      
				Date         -  System.Date         
				Object       -  System.Object       
				String       -  System.String       
				*/
				switch(arrValType[1].toLowerCase())
				{
					case "system.string" :
						var strCompareField =  '|$pbcc$|' + strFieldName + '|$pbcc$|';
						strCompareField = strCompareField.toLowerCase();
						if (strCompareField.indexOf("date")>0 )	
						{
							if (strOperator.indexOf('is') <= 0)
							{
								if ( (! checkValidDate(strValue)) || strValue.length > 10)
								{
									alert("Please enter a valid date.\n In MM/DD/YYYY format.");
									oQCriteria.select();
									//oQCriteria.focus();
									fieldFocus(oQCriteria);
									return false; 
									
								}
							}	
							//Newly added code for date check with other operators
							//added:09/29/03
							//MODIFIED by Jai on 10/01/2003
							//should allow user selection, 
							//just need to change the operator to be used.
							switch (trim(strOperator))
							{
								case "like" ://like op
									//alert("Like operator cannot be used for Date search");
									//return false;
									strOperator = " = ";
									break;
								case "not like" ://not like op
									//alert("Not Like operator cannot be used for Date search");
									//return false;
									strOperator = " <> ";
									break;
								case "starts" : //starts op
									//alert("Starts operator cannot be used for Date search");
									//return false;
									strOperator = " >= ";
									break;
								case "ends" ://ends op
									//alert("Ends operator cannot be used for Date search");
									//return false;
									strOperator = " <= ";
									break;
								case "is null" ://is null op
									strValue = "";
									strDisplayValue = "";
									strOperator = " is null ";
									break;
								case "is not null" ://is not null op
									strValue = "";
									strDisplayValue = "";
									strOperator = " is not null ";
									break;
								default :
									break;
							}
							//end
							//arrValType[0] = " to_char(" + arrValType[0] + ", 'mm/dd/yyyy') ";
							//strValue = "'" + strValue + "'";
							if (strOperator.indexOf('is') <= 0)
							{
								strDisplayValue = strValue;
								
								//alert(arrValType[0]);
								if(bDateHasSpace.toLowerCase() == "true")
								{
									arrValType[0] = " to_date(decode(" + arrValType[0] + ", ' ', '01/01/1800', " + arrValType[0] + "), 'mm/dd/yyyy') ";
									strValue =  " to_date('" + strValue  + "', 'mm/dd/yyyy') ";
								}
								else	
									strValue = " to_date('" + strValue + "', 'mm/dd/yyyy') ";
							}
							else
							{
								if (bDateHasSpace.toLowerCase() == "true")
								{
									strOperator = " = ";
									strValue =  "' '";
								}
								else
									strValue = "";
							}
						}
						else
						{
							strValue = replaceSubstring(strValue, "'", "''");
								
							switch (trim(strOperator))
							{
								case "like" :
									strValue = "%" + strValue + "%";
									strDisplayValue = "%" + strDisplayValue + "%";
									strOperator = " Like ";
									break;
								case "not like" :
									strValue = "%" + strValue + "%";
									strDisplayValue = "%" + strDisplayValue + "%";
									strOperator = " Not Like ";
									break;
								case "starts" : //not added yet
									strValue = strValue + "%";
									strDisplayValue = strDisplayValue + "%";
									strOperator = " Like ";
									break;
								case "ends" ://not added yet
									strValue = "%" + strValue ;
									strDisplayValue = "%" + strDisplayValue;
									strOperator = " Like ";
									break;
								case "is null" ://like op
									strValue = "";
									strDisplayValue = "";
									strOperator = " is null ";
									break;
								case "is not null" ://like op
									strValue = "";
									strDisplayValue = "";
									strOperator = " is not null ";
									break;
								default :
									break;
							}
							
							strValue = "'" + strValue + "'";
							arrValType[0] = "upper(" + arrValType[0] + ")";
							strValue = "upper(" + strValue + ")";
							strDisplayValue = "'" + strDisplayValue + "'";
							if ((strOperator.indexOf('is') > 0) &&  (bDateHasSpace.toLowerCase() == "true"))
							{
								arrValType[0] = arrValType[0];
								strValue = "' '";	
								strOperator = " = "; 
								strDisplayValue = " ";
							}
							else if(strOperator.indexOf('is') > 0) 
							{
								arrValType[0] = arrValType[0];
								strValue = "";	
								strDisplayValue = "";
							}
							
						}	
						
						break;
					case "system.decimal" :
					case "system.int32" :
					case "system.int64" :
					case "system.double" :
					
						if(isNaN(strValue))
						{
							alert("Please enter a number");
							oQCriteria.select();
							//oQCriteria.focus();	
							fieldFocus(oQCriteria);
							return false;
						}	
						switch (trim(strOperator))
						{
							case "like" :
								strValue = "'%" + strValue + "%'";
								strDisplayValue = "'%" + strDisplayValue + "%'";
								strOperator = " Like ";
								break;
							case "not like" :
								strValue = "'%" + strValue + "%'";
								strDisplayValue = "'%" + strDisplayValue + "%'";
								strOperator = " Not Like ";
								break;
							case "starts" : //not added yet
								strValue = "'" + strValue + "%'";
								strDisplayValue = "'" + strDisplayValue + "%'";
								strOperator = " Like ";
								break;
							case "ends" ://not added yet
								strValue = "'%" + strValue + "'";
								strDisplayValue = "'%" + strDisplayValue + "'";
								strOperator = " Like ";
								break;
							case "is null" ://like op
								strValue = "";
								strDisplayValue = "";
								strOperator = " is null ";
								break;
							case "is not null" ://like op
								strValue = "";
								strDisplayValue = "";
								strOperator = " is not null ";
								break;
							default :
								break;
						}
						if ((strOperator.indexOf('is') > 0) &&  (bDateHasSpace.toLowerCase() == "true"))
						{
							strValue = "0";	
							strOperator = " = "; 
							strDisplayValue = " ";
						}
						//strValue = strValue;
						break;
					default :
						
						strValue = "'" + strValue + "'";
						strDisplayValue = "'" + strDisplayValue + "'";	
						break;
				}
			}
		}
		//insert a new row
		var oRow = oTable.insertRow();
		//insert first cell to hold AND/OR
		var oCell = oRow.insertCell();
		var intRowCount = oTable.rows.length;
		
		//check to see if the row being added is odd even
		if(intRowCount%2 == 0)
			oRow.className = "clsTREven";
		else	
			oRow.className = "clsTROdd";
		
		var oCriteria = frmPage.all("hdnFilterCriteria");
		var oDispCriteria = frmPage.all("hdnDispFilterCriteria");
		var strAndOr = document.frmPage.rdAndOr(0).checked ? document.frmPage.rdAndOr(0).value  : document.frmPage.rdAndOr(1).value
		strAndOr = " " + strAndOr; 

		//debugger
		if(oCriteria && oDispCriteria)
		{
			//debugger
			//only for second row or if the hdnFilterCriteria is not empty
			if(intRowCount > 2 || trim(oCriteria.value) != "")
				strAndOr += " " ;
			else
				strAndOr = " " ;
			
			if (bReplaceExpression == true)
			{
				//strExprCondition = replaceSubstring(strExprCondition, "|$expr$|", " upper(" + arrValType[0] + ") " + strOperator + " upper(" + strValue + ") " + " |$pbcc$| ");
			
				strExprCondition = replaceSubstring(strExprCondition, "|$expr$|", arrValType[0] + strOperator + strValue + "|$pbcc$|");
				oCriteria.value += strAndOr + " " + strExprCondition;
				bReplaceExpression = false;
				
			}			
			else
				oCriteria.value += strAndOr + arrValType[0] + strOperator + strValue + "|$pbcc$|";
			
			oDispCriteria.value += strAndOr + " " + strFieldName + oQOPerator.value + " " + strDisplayValue + " &nbsp; ";
			
			//alert(oCriteria.value);
		}
		
		oCell.innerHTML = strAndOr + " " ;
		
		//insert second cell spanning 3 cells	
		oCell = oRow.insertCell();
		oCell.colSpan = 3;
		oCell.innerHTML = strFieldName + "&nbsp;" + oQOPerator.value + "&nbsp;" + strDisplayValue;
		
		//show/hide the radio button
		if(intRowCount > 1 || trim(oCriteria.value) != "")
		{
			rdAndOr.style.display = '';
			//document.frmPage.rdAndOr(0).checked = true;
		}	
		else
			rdAndOr.style.display = 'none';
		
		
		oCell.align = "center";
		oCell = oRow.insertCell();
		//intRowCount += 1;
		
		//NOTE: can be expanded to add more buttons as needed.
		/*
		var strControlHTML = "<input type='button' value='Up' class='clsButton' id='btnUp' name='btnUp' onclick='MoveThis(this, 1)'>"
		strControlHTML += "<input type='button' value='Down' class='clsButton' id='btnDown' name='btnDown' onclick='MoveThis(this, 0)'>"
		strControlHTML += "&nbsp;<input type='button' value='Edit' class='clsButton' id='btnEdit' name='btnEdit' onclick='EditThis(this)'>"
		strControlHTML += "&nbsp;&nbsp;<input type='button' value='Del' class='clsButton' id='btnDelete' name='btnDelete' onclick='deleteThis(this)'>"
		*/
		var strControlHTML = "&nbsp;&nbsp;<input type='button' value='Del' class='clsButton' id='btnDelete' name='btnDelete' onclick='deleteThis(this)'>"
		oCell.innerHTML = strControlHTML;
		
		oQCriteria.value = "";
	}
}
	
function deleteThis(oThis)
{
	/* 
	*	Jai added this function on 09/17/2003
	*	deletes.
	*
	*	Should extended (later)to build XML string
	*	to build the table and moving data accross.
	*/
	var oDelRow = oThis.parentElement.parentElement;
	var oTable = document.all("tblFilter")
	var intRowIndex = oDelRow.rowIndex;
	
	oTable.deleteRow(intRowIndex);
	
	var intRowCount = oTable.rows.length;
	var oCriteria = frmPage.all("hdnFilterCriteria");
	var oDispCriteria = frmPage.all("hdnDispFilterCriteria");
	//debugger
	if(oCriteria && oDispCriteria) 
	{
		
		if(intRowCount > 1 || trim(oCriteria.value) != "")
			rdAndOr.style.display = '';
		else
			rdAndOr.style.display = 'none';
		
		if (trim(oCriteria.value) != "")
		{
			var arrCriteria = oCriteria.value;
			var arrDispCriteria = oDispCriteria.value;
			
			arrCriteria = arrCriteria.split("|$pbcc$|");
			arrDispCriteria = arrDispCriteria.split("&nbsp;");
			
			if (typeof(arrCriteria) == "object" && typeof(arrDispCriteria) == "object" )
			{
				if (arrCriteria.length >= intRowIndex)
				{
					//alert(arrCriteria[intRowIndex -1]); 
					//arrCriteria[intRowIndex-1] = "";

					var arrayelement = intRowIndex-1;  // array element to remove
					var arraylength = arrCriteria.length; // size of array
					for (var i=arrayelement;i<arraylength-1;i++)
						arrCriteria[i]=arrCriteria[i+1];
					arrCriteria.length-=1
				}
				
				arrCriteria[0] = replaceSubstring(arrCriteria[0].toLowerCase(), " and ", " ")
				
				if (arrDispCriteria.length >= intRowIndex)
				{
					//alert(arrCriteria[intRowIndex -1]); 
					//arrCriteria[intRowIndex-1] = "";

					var arrayelement = intRowIndex-1;  // array element to remove
					var arraylength = arrDispCriteria.length; // size of array
					for (var i=arrayelement;i<arraylength-1;i++)
						arrDispCriteria[i]=arrDispCriteria[i+1];
					arrDispCriteria.length-=1
				}
				arrDispCriteria[0] = replaceSubstring(arrDispCriteria[0].toLowerCase(), " and ", " ")
			}
			
			arrCriteria = arrCriteria.join("|$pbcc$|");
			arrDispCriteria = arrDispCriteria.join("&nbsp;");
			
			oCriteria.value = arrCriteria;
			oDispCriteria.value = arrDispCriteria;
		}		
	}
}

function EditThis(oThis)
{
	var oRow = oThis.parentElement.parentElement;
	//var oTable = document.all("tblFilter")
	//oTable.deleteRow(oDelRow.rowIndex);
	var oCell = oRow.cells(1);
	//alert(oCell.innerHTML);
	var arrCellVal = oCell.innerHTML;
	arrCellVal = arrCellVal.split("&nbsp;");
	var oQField = document.all("selQueryField")
	var oQOPerator = document.all("selQueryOperator")
	var oQCriteria = document.all("txtQueryCriteria")
	
	oQField.options[oQField.selectedIndex].text = arrCellVal[0];
	oQOPerator.value = arrCellVal[1];
	var strVal = replaceSubstring(arrCellVal[2],"'", "");	
	strVal = replaceSubstring(arrCellVal[2],"%", "");	
	oQCriteria.value = strVal;	

}

function MoveThis(oThis, intUpDown)
{
	//intUpDown = 1 => UP
	//intUpDown = 0 => DOWN
	var oDelRow = oThis.parentElement.parentElement;
	var oTable = document.all("tblFilter")
	oTable.deleteRow(oDelRow.rowIndex);
}

//function filterShowHide(iShowHide)
function filterShowHide()
{
	
	//iShowHide - 0 => Hide
	//iShowHide - 1 => Show
	var oShow = document.all("btnShowHide")
	var oTable = document.all("tblFilter")	
	
	if(oTable && oShow)
	{
		var strShowHide = oShow.value.toLowerCase();
		if (strShowHide == "show")
		{
			//iShowHide = 1;
			oShow.value = "Hide";
			oTable.style.display = "";
		}
		else
		{
			//iShowHide = 0;	
			oShow.value = "Show";
			oTable.style.display = "none";
		}	
	}
	/*
	if(oTable)
	{
		if (iShowHide == 1)
			oTable.style.display = "";
		else
			oTable.style.display = "none";
	}		
	*/
}

function clearFilter()
{
	var oCriteria = frmPage.all("hdnFilterCriteria");
	var oFilterCriteria = frmPage.all("hdnFilter");
	if(oCriteria) 
	{
		//alert(oCriteria.value);
		//if (trim(oCriteria.value) != "")
		//{
			oCriteria.value = "";
			oFilterCriteria.value = "";
			var oClear = document.all("btnClear");
			//var oFilCrit = document.all("hdnFilterCriteria");
			var oDispFilCrit = document.all("hdnDispFilterCriteria");
			//debugger
			if(oCriteria && oDispFilCrit)
			{
				oCriteria.value = "";
				oFilterCriteria.value = "";
				oDispFilCrit.value = "";
			}
			if (oClear)
				oClear.disabled = true;
			frmPage.submit();
			
		//}	
	}
	
}

function getData()
{
	var oCriteria = frmPage.all("hdnFilterCriteria");
	//alert(oCriteria);
	if(oCriteria) 
	{
		var strCriteria = oCriteria.value;
		//alert(strCriteria);
		if (trim(strCriteria) != "" )
		{
			if (strCriteria.length > 4000)
			{
				alert("Filter Criteria too long, please redefine your filters.\n" +
						"Max length of filter criteria is 4000, you tried to enter filter criteria of length: " + strCriteria.length );
				return false;
			}	
			strCriteria = replaceSubstring(oCriteria.value, "|$pbcc$|", "")
			//alert(strCriteria);
			oCriteria.value = strCriteria
			var oGetData = document.all("btnGetData");
			if (oGetData)
				oGetData.disabled = true;
			frmPage.submit();
		}	
	}		
}
/****************Adds Filter Criteria Ends*****************************/

function hideField(oThisControl, oHideControl)
{
	var oControlToHide = document.all(oHideControl);
	var oThisControlValue = '|$$|' + trim(oThisControl.value).toLowerCase();
	if (oControlToHide && oThisControlValue.indexOf('is') > 0)
		oControlToHide.style.visibility = 'hidden';
	else
		oControlToHide.style.visibility = 'visible';
}

function printExport(sWhat)
{
	//IMP. NOTE: variable xmlDSO1 is hardcoded to get
	//lookup for the first grid.
	//var oXML = document.all("xmlDSO1");
	//if(oXML )
	//{
		if(sWhat.toLowerCase() == 'xl')
			window.open('/contracts_fmb/aspx/PrintThis.aspx?xl=true');
		else
			window.open('/contracts_fmb/aspx/PrintThis.aspx');
	//}	
}

//*********************************************************************************


function showDependents(me)
{
	if(me.value.toLowerCase() == "8") //Guest
	{
		spGuest.style.display = "";
		spDate.style.display = "none";
	}
	else if(me.value.toLowerCase() == "1") //Annual
	{
		spGuest.style.display = "none";
		spDate.style.display = "";
	}
	else
	{
		spGuest.style.display = "none";
		spDate.style.display = "none";
	}
	
}



function autotab(object1, object2, objectsize)
{
	if (object1.value.length == objectsize)
		object2.focus()
}

function toggleControl()
{
	var f = document.frmPage;
	//if (spCommmets.style.display == "")
	if (spCommmets.style.visibility == "visible")
	{	
		f.btnShow.value="Show Comments";
		//spCommmets.style.display = "none";
		spCommmets.style.visibility = "hidden";
	}
	else
	{
		f.btnShow.value="Hide Comments";
		//spCommmets.style.display = "";	
		spCommmets.style.visibility = "visible";
	}	
}	

function acceptValues(a)
{
	var dummy = a;
}

function onfieldfocus(e) {
    /* Cookie-cutter code to find the source of the event */
    if (typeof e == 'undefined') {
        var e = window.event;
    }
    var source;
    if (typeof e.target != 'undefined') {
        source = e.target;
    } else if (typeof e.srcElement != 'undefined') {
        source = e.srcElement;
    } else {
        return;
    }
    /* End cookie-cutter code */
   // source.style.border='2px solid #000';
	if(source.tagName.toLowerCase() == "select")
	{	try
		{
			source.options(source.selectedIndex).className='clsOnFocus';
		}
		catch(e)
		{
			return;
		}	
	}
	else
		source.className='clsOnFocus';
    
}
function onfieldblur(e) {
    /* Cookie-cutter code to find the source of the event */
    if (typeof e == 'undefined') {
        var e = window.event;
    }
    var source;
    if (typeof e.target != 'undefined') {
        source = e.target;
    } else if (typeof e.srcElement != 'undefined') {
        source = e.srcElement;
    } else {
        return;
    }
    /* End cookie-cutter code */
    //source.style.border='2px solid #ccc';
    if(source.tagName.toLowerCase() == "select")
    {	try
		{
			source.options(source.selectedIndex).className='clsOnLostFocus';
		}
		catch(e)
		{
			return;
		}	
	}
	else
		source.className='clsOnLostFocus';
}

///////////////////////////editable dropdown starts ////////////////////

    /*------------------------------------------------
    Variables required for 
    fnChangeHandler_First() & fnKeyPressHandler_First() 
    for Editable Dropdowns
    */


    var PreviousSelectIndex_First = 0;       
    /* Contains the Previously Selected Index */
    
    var SelectIndex_First = 0;               
    /* Contains the Currently Selected Index  */
    
    var SelectChange_First = 'MANUAL_CLICK'; 
    /* Indicates whether Change in dropdown selected value */
    /* was due to a Manual Click                           */
    /* or due to System properties of dropdown             */
    



    /*------------------------------------------------
    Functions required for  Editable Dropdowns
   */
   
    function fnChangeHandler_First(getdropdown)
    {
      PreviousSelectIndex_First = SelectIndex_First;       
      /* Contains the Previously Selected Index */
      
      SelectIndex_First = getdropdown.options.selectedIndex;
      /* Contains the Currently Selected Index  */
      
      if ((PreviousSelectIndex_First == (0)) && (SelectIndex_First != (0))&&(SelectChange_First != 'MANUAL_CLICK')) 
      /* To Set value of Index variables */
      {
        getdropdown[(0)].selected=true;
        PreviousSelectIndex_First = SelectIndex_First;
        SelectIndex_First = getdropdown.options.selectedIndex;
        SelectChange_First = 'MANUAL_CLICK';         
        /* Indicates that the Change in dropdown selected 
			value was due to a Manual Click */
      }
    }
    
    
    
    

    function fnKeyPressHandler_First(getdropdown)
    {
		//alert(getdropdown.options(0).text);
      if(getdropdown.options.length != 0)
      /*if dropdown is not empty*/
        if (getdropdown.options.selectedIndex == (0))
        /*if option the Editable field i.e. the FIRST option */
        {
		  var oEditMe; 
		  var sOptId = getdropdown.id.replace("_d1", "") + "_EditMe_First";
		  //debugger
		  eval ("oEditMe = document.all('" + sOptId + "');");	
          var EditString = oEditMe.text;    
          
          /* Contents of Editable Option */
          
          if (EditString == "--select from here--")            
          /* On backspace on default value of Editable option make Editable option Null */
            EditString = "";
            
          if ((window.event.keyCode==8 || window.event.keyCode==127)) 
          /* To handle backspace */
          {
            EditString = EditString.substring(0,EditString.length-1); 
            /* Decrease length of string by one from right */
            
            SelectChange_First = 'MANUAL_CLICK';      
            /* Indicates that the Change in dropdown selected 
				value was due to a Manual Click */
            
          }
          
          
          /* Check for allowable Characters  */
          /*
          The various characters allowable for entry into Editable option..
          may be customized by minor modifications in the code (if condition below)
          (you need to know the keycode/ASCII value of the  character to be allowed/disallowed.
          */
          if ((window.event.keyCode==46) || (window.event.keyCode>47 && window.event.keyCode<59)||(window.event.keyCode>62 && window.event.keyCode<127) ||(window.event.keyCode==32)) 
          /* To handle addition of a character*/
          {
			
            EditString+=String.fromCharCode(window.event.keyCode);
            /*Concatenate Enter character to Editable string*/

            /* The following portion handles the "automatic Jump" bug*/
            /*
            The "automatic Jump" bug (Description):
               If a alphabet is entered (while editing)
               ...which is contained as a first character in one of the read-only options
               ..the focus automatically "jumps" to the read-only option
               (-- this is a common property of normal dropdowns
                ..but..is undesirable while editing).
            */
            
            var i=0;
            var EnteredChar = String.fromCharCode(window.event.keyCode);
            var UpperCaseEnteredChar = EnteredChar;
            var LowerCaseEnteredChar = EnteredChar;
            
            
            if(((window.event.keyCode)>=97)&&((window.event.keyCode)<=122))
            /*if EnteredChar lowercase*/
              UpperCaseEnteredChar = String.fromCharCode(window.event.keyCode - 32); 
              /*This is UpperCase*/
              
              
            if(((window.event.keyCode)>=65)&&((window.event.keyCode)<=90))
            /*if EnteredChar is UpperCase*/            
              LowerCaseEnteredChar = String.fromCharCode(window.event.keyCode + 32); 
              /*This is lowercase*/
              
              
            for (i=0;i<(getdropdown.options.length-1);i++)
            { var ReadOnlyString = getdropdown[i].text;
              var FirstChar = ReadOnlyString.substring(0,1);
              if((FirstChar == UpperCaseEnteredChar)||(FirstChar == LowerCaseEnteredChar))
              {
                SelectChange_First = 'AUTO_SYSTEM';   
                /* Indicates that the Change in dropdown selected 
                value was due to System properties of dropdown */
                break;
              }
              else
              {
                SelectChange_First = 'MANUAL_CLICK';   
                /* Indicates that the Change in dropdown selected 
                value was due to a Manual Click */
              }
            }
          }
          
          /*Set new value of edited string into the Editable field */
          //alert(EditString);
          oEditMe.text = EditString;
          oEditMe.value = EditString;
          return false;
        }
      return true;
    }
   
function fnLeftToRight(getdropdown)
{
  getdropdown.style.direction = "ltr";
}

function fnRightToLeft(getdropdown)
{
  getdropdown.style.direction = "rtl";
}

function fnDelete(getdropdown)
{
      if(getdropdown.options.length != 0)
      /*if dropdown is not empty*/
        if (getdropdown.options.selectedIndex == (0))
        /*if option the Editable field i.e. the FIRST option */
        {
			getdropdown.options[getdropdown.options.selectedIndex].text = '';
        }
}
///////////////////////////editable dropdown ends ////////////////////
function fieldFocus(field)
{
	//debugger
	switch(field.type)
	{
		case "text" :
		case "textarea" :
		case "password" :
		case "select-one" :
		case "select-multiple" :
		case "button" :
		case "reset" :
		case "submit" :
		case "radio" :
		case "checkbox" :
		case "file" :
			if(field) 
			{	try
				{
					field.focus();
					//field.select();
				}
				catch(e)	
				{
					//do nothing
				}
			}
			return;
		case "hidden" :
			return;	
		default :
			if (field.tagName == "TD")
			{
				return;
			}
			if(field[0].type == "radio")
			{
				
				//field[i].focus();
				return;
			}
			else if(field[0].type == "checkbox")
			{
				if(field[i]) 
				try
				{
					field[i].focus();
					//field[i].select();
				}
				catch(e)	
				{
					//do nothing
				}	
				return;
			}
			else
				var str = "";
				for (x in field) { str += x + "\n"; }
				alert("I couldn't figure out what type this field is...\n\n" + field.name + ": ???\n\n\n" + str + "\n\nlength = " + field.length);
			break;
	}		
}

function MyMsgBox(textstring)
{
alert(textstring)
}

function goBack()
{
	var oHitCounter = document.all("hdnHitCounter");
	if(oHitCounter)
	{
		var iCounter = oHitCounter.value;
		if (trim(iCounter) != "" && ! isNaN(iCounter))
		{
			iCounter = (iCounter*(-1));
			history.go(iCounter);
		}
		else
			history.go(-1)	
		
		return false;
		//alert(iCounter);	
	}
}