/*****************************************************************************
*	Start of general tool script 
*****************************************************************************/
function GetElement(strName) {
	var objElement = null;
	
	if (document.getElementById){
		objElement = document.getElementById(strName);
	} else if (document.all) {
		objElement = document.all[strName];
	} else if (document.layers)	{
	 	objElement = document.layers[strName];
	}
	
	return objElement;
}

//
// Script that called from class
//
function InsertTableRow(strTableID) {
	var objTable, objRow, objCell;
	var objClone;
	var i, j;

	objTable = GetElement(strTableID);
	i = objTable.rows.length;
	if (i >= 2) {
		objRow = objTable.rows[i-2];
		objClone = objRow.cloneNode(true);	//clone the node and all its children
		ChangeElementAttribute(objClone, i);		// Change the id of the node and all its children
		objTable.tBodies[0].insertBefore(objClone, objRow.nextSibling);
	} else {
		alert("You cannot insert a new line at this time. Please refresh the page and try it again.");
	}
}

// Change the node attribute recursively
function ChangeElementAttribute(objNode, intIndex) {
	var i;
	var id;

	if (objNode.attributes) {
		id = objNode.getAttribute("id");
		if (id != null && id != '') {
			id = id.replace(/_\d+/g, '_' + intIndex);
			objNode.setAttribute("id", id);
		}
	}
	if (objNode.childNodes) {
		for (i = 0; i < objNode.childNodes.length; i++) {
			ChangeElementAttribute(objNode.childNodes[i], intIndex);
		}
	}
}

function DeleteTableRow(strTableID) {
	var objTable
	var i;
	
	objTable = GetElement(strTableID); 
	i = objTable.rows.length;
	if (i >= 2) {
		objTable.deleteRow(i - 2);
	}
}

/*
 * Append a row to the current table
 */
function AppendTableRow(objRow) {
	var objTBody;
	var objClone;
	var intRow;

	intRow = objRow.sectionRowIndex;
	objTBody = objRow.parentNode;
	if (intRow >= 1) {
		objClone = objTBody.rows[intRow - 1].cloneNode(true);	//clone the node and all its children
		ChangeElementAttribute(objClone, intRow);				// Change the id of the node and all its children
		objTBody.insertBefore(objClone, objRow);
	} else {
		alert("You cannot insert a new line at this time. Please refresh the page and try it again.");
	}
}

/*
 * Insert a row after the current table row
 */
function InsertAfterTableRow(objRow) {
	var objTBody;
	var objClone;
	var intRow;

	intRow = objRow.sectionRowIndex;
	objTBody = objRow.parentNode;
	objClone = objTBody.rows[intRow].cloneNode(true);			//clone the node and all its children
	ChangeElementAttribute(objClone, intRow + 1);				// Change the id of the node and all its children
	objTBody.insertBefore(objClone, objRow.nextSibling);
}

/*
 * Remove the current table row
 */
function RemoveCurrentTableRow(objRow) {
	var objTBody;
	var intRow;
	
	objTBody = objRow.parentNode;
	intRow = objRow.sectionRowIndex;
	objTBody.deleteRow(intRow);
}

function CaptionCollapse(objCaption) {
	var objTable, objBody;

	objTable = objCaption.parentNode;
	for (var i = 0; i < objTable.tBodies.length; i++) {
		objBody = objTable.tBodies[i];
		if (objBody.style.display == 'none') {
			objCaption.firstChild.src = strApplicationRootPath + 'images/ico_minus.gif'
			objBody.style.display = '';
		} else {
			objCaption.firstChild.src = strApplicationRootPath + 'images/ico_plus.gif'
			objBody.style.display = 'none';
		}
	}
}

/*
 * Expand and collapse all child nodes of a given element
 */
function ExpandCollapseChildNodes(objElement) {
	var i;
	var objChild;
	
	for (i = 0; i < objElement.childNodes.length; i++) {
		objChild = objElement.childNodes[i];
		if (objChild.style) {
			if (objChild.style.display == 'none') {
				objChild.style.display = 'block';
				objElement.style.listStyleImage = 'url(' + strApplicationRootPath + 'images/ico_minus.gif)';
			} else {
				objChild.style.display = 'none';
				objElement.style.listStyleImage = 'url(' + strApplicationRootPath + 'images/ico_plus.gif)';
			}
		}
	}
}

/*
 * Expand and collapse next row of a given table row
 */
function ExpandCollapseTableRow(objCurrent) {
	var objCurrentRow, objNextRow;
	var intRow;
	
	objCurrentRow = objCurrent.parentNode.parentNode;
	intRow = objCurrentRow.sectionRowIndex;
	objNextRow = objCurrentRow.parentNode.rows[intRow + 1];
	if (objNextRow) {
		if (objNextRow.style.display == 'none') {
			objNextRow.style.display = 'block';
			objCurrent.src = strApplicationRootPath + 'images/ico_minus.gif';
		} else {
			objNextRow.style.display = 'none';
			objCurrent.src = strApplicationRootPath + 'images/ico_plus.gif';
		}
	}
}

/*
 * Check on or off all checkbox in a given table
 */
function CheckWholeTable(objTable, bitCheckOn) {
	var objTable, objBody, objRow, objCell, objChild;

	for (var i = 0; i < objTable.tBodies.length; i++) {
		objBody = objTable.tBodies[i];
		for (var j = 0; j < objBody.rows.length; j++) {
			objRow = objBody.rows[j];
			for (var k = 0; k < objRow.cells.length; k++) {
				objCell = objRow.cells[k];
				for (l = 0; l < objCell.childNodes.length; l++) {
					objChild = objCell.childNodes[l];
					if (objChild.type == 'checkbox') {
						if (bitCheckOn) objChild.checked = true;
						else objChild.checked = false;
					}
				}
			}
		}
	}
}

/*
 * Check on or off all checkbox in a given table column
 */
function CheckWholeColumn(objCurrentCell, bitCheckOn) {
	var objBody, objCell, objChild;
	var strID, objElement;

	objBody = objCurrentCell.parentNode.parentNode;
	for (var i = 0; i < objBody.rows.length; i++) {
		if (objCurrentCell.rowIndex != i) {
			objCell = objBody.rows[i].cells[objCurrentCell.cellIndex];
			for (j = 0; j < objCell.childNodes.length; j++) {
				objChild = objCell.childNodes[j];
				if (objChild.type == 'checkbox') {
					strID = objChild.id.replace(/hid/, 'bit');
					objElement = GetElement(strID);
					if (objElement) {
						if (bitCheckOn) {
							objChild.checked = true;
							objElement.value = 1;
						} else {
							objChild.checked = false;
							objElement.value = 0;
						}
					}
				}
			}
		}
	}
}

function popupDate(objTarget) {
	var cal = new calendar2(objTarget);
	cal.year_scroll = true;
	cal.popup();
}

//get the field value
function getFieldValue(objField) {
	var	strValue = "";
	
	switch (objField.type) {
		case "select-one":
			strValue = objField.options[objField.selectedIndex].value;
			break;
		case "radio":
		case "checkbox":
			if (objField.length > 1) {		//is radio button or checkbox group field
				for (var i = 0; i < objField.length; i++) {
					if (objField[i].checked)	strValue = objField[i].value;
				}
			}
			else {
				if (objField.checked)	strValue = objField.value;
			}
//			alert(objField.type + ':' + strValue + ':' + objField.length);		
			break;
		default:
			strValue = objField.value;
			break;
	}
	
	return strValue;
}

function TrimSpace(inputString) {
   // 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 getCurrentDate() {
	var d = new Date();
	return (d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear();
}

function getCurrentTime() {
	var d = new Date();
	return (d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes();
}

/*****************************************************************************
*	End of general tool script 
*****************************************************************************/

/*****************************************************************************
*	Start of menu script 
*****************************************************************************/
	var	orignalColor;
	var orignalElement = null;
	
	function ChangeBackground(objElement) {
		if (objElement != null) {
			if (orignalElement != null) {
				orignalElement.style.backgroundColor = orignalColor;
			}
			orignalElement = objElement;
			orignalColor = objElement.style.backgroundColor;
			objElement.style.backgroundColor = "white";
		}
	}
	
	function printMainFrame() {		//print main frame page
		if (document.all) {		//IE
			window.parent.fraMain.focus();
			window.print();
		} else {				//NS
			window.parent.fraMain.print();
		}
	}
/*****************************************************************************
*	End of menu script 
*****************************************************************************/

/*****************************************************************************
*	Start of form validation script 
*****************************************************************************/
regDate = /^((((([13578])|(1[0-2]))[\-\/\s]?(([1-9])|([1-2][0-9])|(3[01])))|((([469])|(11))[\-\/\s]?(([1-9])|([1-2][0-9])|(30)))|(2[\-\/\s]?(([1-9])|([1-2][0-9]))))[\-\/\s]?\d{2,4})(\s([0][1-9]|[1][0-9]|[2][0-3]|[0-9])\:([0-5][0-9]|[0-9]))?$/;
regTime = /^([0]?[1-9]|[1][0-9]|[2][0-3])\:[0-5][0-9]$/;
regEmail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
regZIP = /^(\d{5}-\d{4}|\d{5})$|^([a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d)$/;
regName = /^[a-zA-Z0-9]+(([\'\,\.\- ][a-zA-Z0-9 ]?)?[a-zA-Z0-9]*)*$/;
regSSN = /^[0-9]{3}-[0-9]{2}-[0-9]{4}$/;
regPhone = /^[0-9a-zA-Z]{3}-[0-9a-zA-Z]{3}-[0-9a-zA-Z]{4}-?[0-9a-zA-Z]{0,5}$/;
regDecimal = /^\d*.?\d*$/;
regText = /^[\s\S]*$/;

function formValidate(objForm) {
	var objField;
	var strValue;
	var bitValid, bitReturn;
	var error;
	var bitRequiredError;
	
	bitReturn = true;
	bitRequiredError = false;
	error = "";
	for (var i = 0; i < objForm.elements.length; i++) {
		objField = objForm.elements[i];
		intIndex = needValidation(getShortFieldName(objField.name));
		if (intIndex >= 0) {
			strValue = getFieldValue(objField);
			if ((strValue.length == 0) && (validationRules[intIndex][2] == true)) {
				bitReturn = false;
				bitRequiredError = true;
				error = error + "<LI><B>" + validationRules[intIndex][5] + " field: </B>"
					+ "This field must be filled!<BR>";
			} else {
				bitValid = validateField(validationRules[intIndex][1], strValue);
				if (!bitValid) {
					bitReturn = false;
					error = error + "<LI><B>" + validationRules[intIndex][5] + " field: </B>"
						+ validationRules[intIndex][6] + "<BR>";
				} else {
					bitValid = validateRange(getShortFieldName(objField.name), strValue, validationRules[intIndex][3], validationRules[intIndex][4]);
					if (!bitValid) {
						bitReturn = false;
						error = error + "<LI><B>" + validationRules[intIndex][5] + " field: </B>"
							+ "the value or length must be between " + validationRules[intIndex][3] + ' and ' + validationRules[intIndex][4] + "<BR>";
					}
				}
			}
		}
	}
	
	if (GetElement("btnIgnoreError") != null) {
		GetElement("btnIgnoreError").style.display = 'none';
	}
	if (bitReturn == false) {
		displayError(error);
		GetElement("errorDisplay").scrollIntoView();
		if (GetElement("btnIgnoreError") != null && bitRequiredError == true) {
			GetElement("btnIgnoreError").style.display = 'inline';
		}
	}
	
	return bitReturn;
}

function getShortFieldName(strName) {
	var strShortName;
	var intIndex;
	
	intIndex = strName.indexOf(".");
	if (intIndex > 0) {
		strShortName = strName.substring(intIndex + 1);
	} else {
		strShortName = strName;
	}
	
	return strShortName;
}

function needValidation(strName) {
	if (typeof(validationRules) == "object") {
		for (var i = 0; i < validationRules.length; i++) {
			if (validationRules[i][0] == strName) {
				return i;
			}
		}
	}
	return -1;
}

function validateField(strPattern, strValue) {
	if (strValue.length > 0) {
		return strPattern.exec(strValue);
	}
	return true;
}

function validateRange(strName, strValue, strMin, strMax) {
	if (strMin.length > 0) {
		if (strName.substring(0, 3) == 'dtm') {
			if (new Date(strValue) < new Date(strMin)) return false;
		} else if (strName.substring(0, 3) == 'int') {
			if (parseInt(strValue) < parseInt(strMin)) return false;
		} else if (strName.substring(0, 3) == 'str') {
			if (strValue.length < parseInt(strMin)) return false;
		}
	}
	if (strMax.length > 0) {
		if (strName.substring(0, 3) == 'dtm') {
			if (new Date(strValue) > new Date(strMax)) return false;
		} else if (strName.substring(0, 3) == 'int') {
			if (parseInt(strValue) > parseInt(strMax)) return false;
		} else if (strName.substring(0, 3) == 'str') {
			if (strValue.length > parseInt(strMax)) return false;
		}
	}
	
	return true;
}

function displayError(strError) {
	var objField;

	strError = "<STRONG>This form has the following errors:</STRONG><BR><UL>" + strError + "</UL>"
	strError = strError + "Please change the inputs and save again!";
	objField = GetElement("errorDisplay");
	objField.className = "cssErrorMessage";
	objField.innerHTML = strError;
}
/*****************************************************************************
*	End of form validation script 
*****************************************************************************/

/*****************************************************************************
*	Start of real-time field validation script 
*****************************************************************************/
function ValidateDateField(objField) {
    var strValue, varTest;
    var	year;
    
    strValue = TrimSpace(objField.value);
	if (strValue.length > 0) {  
		varTest = Date.parse(strValue);
		if (isNaN(varTest)) {
		    alert("Wrong Date Format '" + strValue + "'; Please Change it into format 'mm/dd/yyyy'");
		    objField.focus();
		    return false;
		} else {
		    nDate = new Date(varTest);
		    if (nDate.getFullYear() < 1900 || nDate.getFullYear() > 2049) {
				alert("The value must be between '1/1/1900' and '1/1/2049'");
				objField.focus();
				return false;
			} else {
				year = nDate.getFullYear();
//				if (year < 1910)	year = year + 100;
		        strValue = (nDate.getMonth() + 1) + '/' + nDate.getDate() + '/' + year;
		        if (nDate.getHours() > 0) strValue = strValue + ' ' + nDate.getHours() + ':' + nDate.getMinutes();
		        objField.value = strValue
		        return true;
		    }
		}
	}
}

function ValidateTimeField(objField) {
    var strValue, varTest;
    
    strValue = TrimSpace(objField.value);
	if (strValue.length > 0) {  
		if (!validateField(regTime, strValue)) {
		    alert("Wrong Time Format '" + strValue + "'; Please Change it into format 'hh:mm'. Use the leading zero if less than two digits.");
		    objField.focus();
		}
	}
}

function ValidateIntegerField(objField) {
    var strValue, varTest;
    
    strValue = TrimSpace(objField.value);
	if (strValue.length > 0) {  
		varTest = parseInt(strValue);
		if (isNaN(varTest)) {
		    alert("Invalid integer.");
		    objField.focus();
		} else {
	        objField.value = varTest;
		}
	}
}

function ValidateDecimalField(objField) {
    var strValue, varTest;
    
    strValue = TrimSpace(objField.value);
	if (strValue.length > 0) {  
		varTest = parseFloat(strValue);
		if (isNaN(varTest)) {
		    alert("Invalid decimal.");
		    objField.focus();
		} else {
	        objField.value = varTest;
		}
	}
}

function CheckSSN(objField) {
	var strSSN = objField.value
	var matchArr = strSSN.match(/^(\d{3})-?\d{2}-?\d{4}$/);
	var numDashes = strSSN.split('-').length - 1;
		
	if (strSSN == '') return;
	if (matchArr == null || numDashes == 1) {
		alert('Invalid SSN. Must be 9 digits or in the form NNN-NN-NNNN.');
		objField.focus();
	} else if (parseInt(matchArr[1],10)==0) {
		alert("Invalid SSN: SSN's can't start with 000.");
		objField.focus();
	} else {
		if (strSSN.length == 9) {
			objField.value = strSSN.substring(0, 3) + '-' + strSSN.substring(3, 5) + '-' + strSSN.substring(5, 9);
		}
	}
}
/*****************************************************************************
*	End of real-time field validation script 
*****************************************************************************/


/*****************************************************************************
*	Start of page related script 
*****************************************************************************/
function LogOff(intSessionID) {
	window.open("LogOff.asp?SessionID=" + intSessionID, "_top");
}

//loadmenu loads page into navigation frame 
function LoadMenu(loc){
	if (parent.fraMenu != null) {
		parent.fraMenu.location.href = loc;
	}
}

function InitialFocus(element) {	
	if (document.forms.length > 0) {
		document.forms[0].elements[element].focus();
	}
}

function ExpandCollapse(objRow) {
	var	objNextRow;
	var	intRow;
	
	intRow = objRow.rowIndex;
	objNextRow = objRow.parentElement.rows[intRow + 1];
	
	if (objNextRow.style.display == 'none') {	
		objRow.cells[0].firstChild.src = strApplicationRootPath + 'images/minus.gif';
		objNextRow.style.display = '';
	} else {
		objRow.cells[0].firstChild.src = strApplicationRootPath + 'images/plus.gif';
		objNextRow.style.display = 'none';
	}
}

function setActiveState(id_name, field_name) {
	var id;
	id_name = id_name.replace(eval('/' + field_name + '/g'), 'hidActive');

	id = GetElement(id_name);
	id.checked = true;
	id_name = id_name.replace(/hidActive/g, 'bitActive');
	id = GetElement(id_name);
	id.value = 1;
}


function popupCalendar(objTarget) {
	var cal = new calendar2(objTarget);
	cal.year_scroll = true;
	cal.time_comp = true;
	cal.popup();
}
	
function ChangePullDownList(objCurrent, srcFieldName, destFieldName, strSQL) {
	var value;
	var id;
	var	id_name = objCurrent.id;
	id_name = id_name.replace(eval('/' + srcFieldName + '/g'), destFieldName);
	id = GetElement(id_name);
	id.length = 0;

	value = getFieldValue(objCurrent);
	if(value != "") {
		strSQL = strSQL.replace("%1%", value);
		var objRS = RSGetASPObject(strApplicationRootPath + "Include/RemoteScript.asp");
		var objResult = objRS.GetList(strSQL);
		var strList = objResult.return_value;
		if (strList != "") {
			PopulatePullDown(strList, id);
		}
	}
}

function PopulatePullDown(strList, objSelect) {
	var strGroup;
	var arrList, arrRow;
	var objGroup, objOption;
	var i;
	
	objGroup = objSelect;
	objOption = CreateOptionElement('', '--Select One--');	//append an empty option
	objGroup.appendChild(objOption);

	strGroup = '';
	arrList = strList.split("$$");
	for(i = 0; i < arrList.length; i++) {
		arrRow = arrList[i].split("&&");
		if (arrRow.length > 2) {
			if (arrRow[2] != strGroup) {
				objGroup = CreateOptGroupElement(arrRow[2]);
				objSelect.appendChild(objGroup);
				strGroup = arrRow[2];
			}
		}
		objOption = CreateOptionElement(arrRow[0], arrRow[1]);
		objGroup.appendChild(objOption);
	}
}

function CreateOptionElement(strValue, strText) {
	var objOption;
	
	objOption = document.createElement('option');
	objOption.value = strValue;
	objOption.innerText = strText;
	
	return objOption;
}

function CreateOptGroupElement(strLabel) {
	var objGroup;
	
	objGroup = document.createElement('optgroup');
	objGroup.label = strLabel;
	
	return objGroup;
}

function PopupWindow(strURL, strName) {
	var h_win;

	h_win = window.open(strURL, strName, 'toolbar=0,status=0,menubar=0,titlebar=0,resizable=1,scrollbars=1,height=400px,width=600px');
	h_win.focus();
	
	return h_win;
}
/*****************************************************************************
*	End of page related script 
*****************************************************************************/
