/*
This function validates a structure element, running the necessary validation functions based
on display type.
*/
function validateStructureElement(
		subForm,
		structureId,
		structureElementName,
		fieldLabel,
		fieldType,
		fieldSize,
		displayType,
		required, handleRequired,
		minimumValue, maximumValue, decimalPlaces, maximumWordCount, 
		regularExpression, regularExpressionError)
{

	var strError = '';
	var structureElement = subForm[structureElementName];
	/* Required Field Validation */



	
	if(window.document.getElementById('req_' + structureId))
	{
		if(window.document.getElementById('req_' + structureId).innerHTML == '*') { required = true } else { required = false };
	}

	var boolHidden = false;
	if(window.document.getElementById('row_' + structureId))
	{
		if(window.document.getElementById('row_' + structureId).style.display == 'none') boolHidden = true;
	}
	if(boolHidden == true) required = false;
	
	if(required == true && handleRequired == true)
	{
	
		switch(displayType)
		{
		
			case 'Select':
				
				if(structureElement.selectedIndex == 0)
				{
					strError += 'You must select a value for: ' + fieldLabel + '\n';
				}
				break;
			
			case 'Multiple Choice (Radio)':
			case 'Radio':
				
				radioFound = false;

				for(var i = 0; i < structureElement.length; i++)
				{
					if(structureElement[i].checked) radioFound = true;
				}

				if(radioFound == false)
				{
					strError += 'You must select a value for: ' + fieldLabel + '\n';
				}
				break;
			
			case 'Multiple Choice (Checkbox)':
			case 'Checkbox':
			
				checkFound = false;
				if(structureElement.length)
				{
				 	for(var i = 0; i < structureElement.length; i++)
					{
						if(structureElement[i].checked) checkFound = true;
				 	}
				}
				else
				{
					if(structureElement.checked) checkFound = true;
				}

				if(checkFound == false)
				{
					if(structureElement.length) {
						strError += 'You must select a value for: ' + fieldLabel + '\n';
					}
					else
					{
						strError += 'The following field must be checked: ' + fieldLabel + '\n';
				 	}
				}
			
				break;
				
				

				
			case 'Date/Time':
				break;
			
			case 'File Image':
				
			case 'File Slot':
				if(document.getElementById(structureElementName + '_newfile').value == '')
				{ 
					if(structureElement.value == '')
					{
						 strError += 'You must upload a file for: ' + fieldLabel + '\n';
					}
					else if(document.getElementById(structureElementName + '_deletefile').checked)
					{
						strError += 'You must upload a file for: ' + fieldLabel + '\n';
					}
					
				}
				break;
				
			case 'Phone Number':
			
				if(subForm[structureElementName + '_areacode'].value == '' || subForm[structureElementName + '_prefix'].value == '' || subForm[structureElementName + '_line'].value == '')
				{
					
					strError += 'You must enter a complete phone number for: ' + fieldLabel + '\n';	
				}
				break;
				
			default:
			
			
				if(structureElement.value == '')
				{
				 strError += 'You must enter a value for: ' + fieldLabel + '\n';
				}
			
				break;
			
		}
		
	}
	
	
	/* Value-based validation */
	if(fieldType == 'Numeric' && displayType != 'Radio' && displayType != 'Checkbox' && displayType != 'Multiple Choice (Radio)' && displayType != 'Multiple Choice (Checkbox)')
	{
	
		if(displayType == 'Currency')
		{
			structureElement.value = replace_norm(structureElement.value, '$', '');
		}
		strError += validate_num(structureElement.value, structureElement.name, fieldLabel, minimumValue, maximumValue, decimalPlaces);
	
	
	}

	if(displayType == 'Memo' || displayType == 'Memo - HTML' || displayType == 'Memo - Expanding')
	{
		strError += validate_memo(structureElement.value, structureElement.name, fieldLabel, fieldSize);
	}

	/* Validate maximum word count */
	if(maximumWordCount != '-1' && displayType == 'Memo')
	{
	
		
		var intMaximumWordCount = parseInt(maximumWordCount)

		if(getWordCount(structureElement.value) > intMaximumWordCount)
		{
			return fieldLabel + " must be " + intMaximumWordCount + " words or less\n";
		}
	
	
	}


	if (displayType == 'Phone Number') {
		if (
			isNaN(subForm[structureElementName + '_areacode'].value) ||
			isNaN(subForm[structureElementName + '_prefix'].value) ||
			isNaN(subForm[structureElementName + '_line'].value) ||
			isNaN(subForm[structureElementName + '_ext'].value)) {

			strError += 'Every component of ' + fieldLabel + ' must be a number.\n';
		}

		var strPhoneComp = new String('')

		strPhoneComp = subForm[structureElementName + '_areacode'].value + subForm[structureElementName + '_prefix'].value + subForm[structureElementName + '_line'].value
		if (strPhoneComp != '' && strPhoneComp.length != 10) {
			strError += 'Every component of ' + fieldLabel + ' must have the correct number of digits.\n';
		}

	}
	
	if(displayType == 'Date/Time')
	{
		strError += validate_date_time(
			structureElement.value,
			subForm[structureElement.name + '_hour'].options[subForm[structureElement.name + '_hour'].selectedIndex].value,
			subForm[structureElement.name + '_minute'].options[subForm[structureElement.name + '_minute'].selectedIndex].value,
			subForm[structureElement.name + '_ampm'].options[subForm[structureElement.name + '_ampm'].selectedIndex].value,
			fieldLabel,
			minimumValue,
			maximumValue,
			structureElement,
			required);
	}

	/* Date Validation */
	if(fieldType == 'Date' && displayType != 'Date/Time')
	{
		strError += validate_date(structureElement.value, structureElement.name, fieldLabel, minimumValue, maximumValue)
	}

	/* Regular Expression Validation */
	if(regularExpression != '' && handleRequired == true)
	{
		var regExObj = new RegExp(regularExpression);
		var patternstructureElement = new String(structureElement.value);
		
		if(!regExObj.test(patternstructureElement) && structureElement.value != '')
		{
			strError += regularExpressionError + '\n';
		}
		
		
	}

	return strError;

}



/*
This function runs validation to insure the entered value is a number, that it
is inside the designated minimum and maximum values, and that it has the proper
amount of decimal places.
*/
function validate_num(strNum, fldName, fldLabel, minValue, maxValue, decimalPlaces)
{
	var decimalIndex;
	if(!(strNum == ""))
	{
		// CHECK TO MAKE SURE VALUE IS A NUMBER
		if(strNum.indexOf("$") > -1 || strNum.indexOf(",") > 0)
		{
		
			return fldLabel + " must be a Number, No $ or ,\n"
		}
		if(isNaN(strNum)) {

			return fldLabel + " must be a Number.\n";
		}
		
		// if the minimum value setting wasn't set to a number, see if it points to the name of another input element
		if(isNaN(parseFloat(minValue)) && minValue != '')
		{
		
			if(window.document.getElementById(minValue))
			{
				minValue = window.document.getElementById(minValue).value;
			}
		
		}

		// if the maximum value setting wasn't set to a number, see if it points to the name of another input element
		if(isNaN(parseFloat(maxValue)) && maxValue != '')
		{
		
			if(window.document.getElementById(maxValue))
			{
				maxValue = window.document.getElementById(maxValue).value;
			}
		
		}

		if(window.document.getElementById(fldName + '_new_min'))
		{
			minValue = window.document.getElementById(fldName + '_new_minimum').value;	
		}

		if(window.document.getElementById(fldName + '_new_max'))
		{
			maxValue = window.document.getElementById(fldName + '_new_minimum').value;	
		}

		
		if(minValue != "")
		{
			if(parseFloat(minValue) > parseFloat(strNum))
			{
				return fldLabel + " must be greater than or equal to " + minValue + ".\n";
			}
		}
		
		if(maxValue != "")
		{
			if(parseFloat(maxValue) < parseFloat(strNum))
			{
				return fldLabel + " must be smaller than or equal to " + maxValue + ".\n";
			}
		}
		
		decimalIndex = strNum.indexOf(".")
		if(decimalIndex > -1)
		{
			if(decimalPlaces == "0")
			{
				return fldLabel + " must be an integer.\n";
			}
	
			if(parseInt(decimalPlaces) < strNum.length - decimalIndex - 1)
			{
				return fldLabel + " has too many decimal places.\n";
			}
		}		

		
	}
	return "";
}


/*
This function validates the text within textarea fields to insure the amount of characters entered
does not exceed the configured maximum.
*/
function validate_memo(strMemo, fldName, fldLabel, fldSize)
{
	if(!strMemo == "")
	{
		if(strMemo.length > fldSize)
		{
			return fldLabel + " must be Less than " + fldSize  + "\n";
		}
	}
	

	
	
	return "";
}




/*
This function converts a date from the user's regional format to standard
US format.
*/
function convertUserDateToSystemFormat(strDate)
{

	// return an empty string if one was passed in.
	if(strDate == '') return '';

	var strSplit = new String(strDate)
	var date_array = new Array();
	var data_array2 = new Array();
	
	// split any timestamps off
	date_array = strSplit.split(" ")
	
	// split the date into month, day, and year components.
	date_array2 = date_array[0].split("/")
	
	// if the length of the array isn't three, then return empty string.
	if(date_array2.length != 3)
	{	
		return '';
	}
	
	// reformat date to US format based on user's regional setting.
	if(userDateFormat == "dd/mm/yyyy")
	{
		strSplit = date_array2[1] + '/' + date_array2[0] + '/' + date_array2[2];
		
	}
	
	// reformat date to US format based on user's regional setting.
	if(userDateFormat == "yyyy/mm/dd")
	{
		strSplit = date_array2[1] + '/' + date_array2[2] + '/' + date_array2[0];
		
	}
	
	// re-add any date information.
	for(var i = 1; i < date_array.length; i++)
	{
		strSplit += ' ' + date_array[i];
		
	}
	return strSplit;

}

/*
This function insures that dates entered by users are valid dates, and come between specified minimum and maximum values.
The dates are converted to US format if the user has a date format setting other than US format.
*/
function validate_date(strDate, fldName, fldLabel, minValue, maxValue)
{
	var x
	var strSplit = new String(strDate)
	var date_array = new Array();
	var testDate;
	
	
	date_array = strSplit.split(" ")
	date_array = date_array[0].split("/")
	
	if(strDate == '') return '';
	
	if(date_array.length != 3)
	{	
		return fldLabel + " must be a date.\n";
	}
	
	if(userDateFormat == "dd/mm/yyyy")
	{
		strSplit = date_array[1] + '/' + date_array[0] + '/' + date_array[2];
		date_array = strSplit.split("/")
	}
	
	if(userDateFormat == "yyyy/mm/dd")
	{
		strSplit = date_array[1] + '/' + date_array[2] + '/' + date_array[0];
		date_array = strSplit.split("/")
	}
	


	if(!strDate == "")
	{
		
		x = Date.parse(strSplit);
		

		if(isNaN(x))
		{
			
			return fldLabel + " must be a date.\n";
		}
		
		if(date_array[0].length < 1 || date_array[0].length > 2)
		{
			return fldLabel + " has an invalid month.\n";
		}

		if(date_array[2].length > 4 || date_array[2].valueOf() < 0)
		{
			return fldLabel + " has an invalid year.\n";
		}
		
		testDate = new Date(date_array[2], date_array[0] - 1, date_array[1]);
		if (testDate.getMonth() != date_array[0] - 1)
		{
			return fldLabel + " must be a date.\n";
		}
		

		
		// Check min/max values
		if(window.document.getElementById(fldName + '_new_min'))
		{
			minValue= window.document.getElementById(fldName + '_new_minimum').value;	
		}

		if(window.document.getElementById(fldName + '_new_max'))
		{
			maxValue = window.document.getElementById(fldName + '_new_minimum').value;	
		}
		
		// get minimum date from another element for comparison if the minValue setting was entered as a string and not as a date
		if(isNaN(Date.parse(minValue)) && minValue != '')
		{
		
			if(window.document.getElementById(minValue))
			{
				minValue = convertUserDateToSystemFormat(window.document.getElementById(minValue).value);
			}
		
		}
		
		// get maximum date from another element for comparison if the maxValue setting was entered as a string and not as a date
		if(isNaN(Date.parse(maxValue)) && maxValue != '')
		{
		
			if(window.document.getElementById(maxValue))
			{
				maxValue = convertUserDateToSystemFormat(window.document.getElementById(maxValue).value);
			}
		
		}


		// Evaluate the entered date value against the minimum allowed value
		if(!isNaN(Date.parse(minValue)))
		{
			if(x < Date.parse(minValue))
			{
				return fldLabel + " must be on or after " + minValue + ".\n";
			}
		}
		
		// Evaluate the entered date value against the maximum allowed value
		if(!isNaN(Date.parse(maxValue)))
		{
			if(x > Date.parse(maxValue))
			{
				return fldLabel + " must be on or before " + maxValue + ".\n";
			}
		}
		
		
		
	}
	
	return "";
}


/*
This function validates both a date component, as well as three separate time components.
*/
function validate_date_time(strDate, strHour, strMinute, strAMPM, fldLabel, minValue, maxValue, hidBox, required)
{

	var strError = new String("");
	strError = validate_date(strDate, fldLabel, fldLabel, minValue, maxValue)
	
	if(strError != "") return strError;
	
	var strTime = new String(strHour + strMinute + strAMPM)
	
	
	if(strDate == "" || strTime ==  "")
	{
		if(strDate == "" && strTime == "")
		{
			if(required == false ) return "";
			
			return "You must enter a value for: " + fldLabel + ".\n";
		}
		else
		{
			return fldLabel + " has an invalid date or time.\n";	
		}
		
	}
	
	
	
	if(strTime.length != 6)
	{
		return fldLabel + " has an invalid time.\n";
	}
	

	return "";
}



/*
This function validates dates based on individually passed in date components.
*/
function validate_date_dd(strMonth, strDay, strYear, fldLabel, hidBox, required, minValue, maxValue)
{
	var x
	var y
	var strDate = new String(strMonth + "/" + strDay + "/" + strYear)
	
	var z = Date.parse(strDate);
	
	// alert(strDate)
	if(strDate.length == 10)
	{

		x = new Date(strYear, strMonth - 1, strDay)

		if(x.getMonth() != strMonth - 1)
		{
			hidBox.value = "";
			return fldLabel + " must be a date.\n";
		}
		
		// CHECK MIN/MAX VALUES
		if(z < Date.parse(minValue))
		{
			hidBox.value = "";
			return fldLabel + " must be on or after " + minValue + ".\n";
		}

		if(z > Date.parse(maxValue))
		{
			hidBox.value = "";
			return fldLabel + " must be on or before " + maxValue + ".\n";
		}		

		
		hidBox.value = strDate;
		
		
		
		
	}
	else
	{
		if(strDate.length != 2) {

			hidBox.value = "";
			return "Invalid " + fldLabel + "\n";
		}
		
		if(required == true) {
			hidBox.value = "";
			return "You must enter a value for: " + fldLabel + "\n";
		}
	}


	return "";
}








function isCurrency(str){
	var isFlag=0;
    var isDollarSign=0;
    var isPeriod = 0;
	var isStr=str;
	
	for (var i=0; i <isStr.length ; i++) {
		if (isStr.charAt(i) == "$" ) {
			isDollarSign=isDollarSign + 1;
		}else if (isStr.charAt(i) == "." ) {
			isPeriod=isPeriod + 1;
		}else if (isStr.charAt(i) == "," ) {
			//do nothing
		} else {
			if (isNumber(isStr.charAt(i)) == false ) {
				isFlag=1;
			}
		}
	}	
	if (isFlag == 0 && isDollarSign < 2 && isPeriod < 2 ) { 
		return true;
	} else {
		return false
	}
}

function isNumber (tmp) {  
	var i; 
	for (i=0;i<tmp.length;i++) { 
		c = tmp.charAt(i) 
		if (c < "0" || c > "9") return false; 
	} 
	return true; 
} 



function getCurrencyNumber(sstr) {

	sstr = replace_norm(sstr,'$','');
	sstr=sstr.replace(/,/gi,'');
	return sstr;

}





function textSelect_autoscroll(textElement, selectElement, prevH, prevK)
{


	var lngMatches = 0;
	var lngIndex = -1;
	var strOption = new String("");
	var strValue = new String("");
	var strElValue = new String(textElement.value);
	
	
	if(document.all)
	{
		
		var strKeyCode = new String(event.keyCode)
		
		if(document.getElementById(prevK).value != strKeyCode)
		{

			return false;
		}
	
	
		if(window.event.keyCode == 16)
		{
			return false;
		}	
		if(window.event.keyCode == 8)
		{

			if(document.getElementById(prevH).value == "true")
			{
				textElement.value = strElValue.substr(0, strElValue.length - 1);
			}
			// return false;
		}
	}
	if(textElement.value == "") 
	{	
		selectElement.options[0].selected = true;
		return false;
	}
	
	for(i = 0; i < selectElement.options.length; i++)
	{
		strOption = selectElement.options[i].text
		strOption = strOption.toUpperCase();
		strValue = textElement.value;
		strValue = strValue.toUpperCase();
		
		if(strOption.indexOf(strValue) == 0)
		{
			if(lngIndex == -1)
			{
				selectElement.options[i].selected = true;
				lngIndex = i;
			}
			lngMatches++;
		}
	}

	if(lngMatches == 0)
	{
		selectElement.options[0].selected = true;
		document.getElementById(prevH).value = "false";
		return false;
		
	}
	else
	{
		if(lngMatches == 1)
		{
			strValue = textElement.value;
			var oldLength = strValue.length
			
			if(document.all)
			{
				textElement.value = selectElement.options[lngIndex].text;
				
				strValue = textElement.value;
				var newLength = strValue.length
				
				var tRange = textElement.createTextRange();
				
				
				
				tRange.moveStart("character", oldLength)
				if(tRange.text != "")
				{
					document.getElementById(prevH).value = "true";
				}
				else
				{
					document.getElementById(prevH).value = "false";
				}
			
				tRange.select();
			}
		}
		else
		{
			document.getElementById(prevH).value = "false";
		}
		return true;
	}
}	

function textSelect_select2text(textElement, selectElement)
{

	if(selectElement.selectedIndex > 0)
	{	

		textElement.value = selectElement.options[selectElement.selectedIndex].text
		selectElement.focus();	
	}
	else
	{

		textElement.value = "";
		selectElement.focus();
	}
}


/*
This function clears a field's value.
*/
function clearField(theField)
{

	if(!theField.length)
	{

		if(theField.checked)
			theField.checked = false;
		

		if(theField.value)
			theField.value = '';
			
		
		
	}
	else
	{
		for(var i = 0; i < theField.length; i++)
		{
			if(theField[i].checked)
				theField[i].checked == false;
		}
	
		if(theField.selectedIndex)
		{
			theField.selectedIndex = 0;
		}

	
	}

}


/*
This function validates a structure element as it appears on the search screen.
*/
function validateSearchField(y, theform, ssid, fldname, fldlbl, fldtype, fldsize, flddisplaytype)
{

   if(fldtype == "Numeric")
   {
   	if(flddisplaytype == "Text" || flddisplaytype == "Currency")
	{

		xx = theform["f1_"+ ssid].value
		xx2 = theform["f2_" + ssid].value
		xxst = theform["st_" + ssid].options[theform["st_" + ssid].selectedIndex].value
		
		xx = ltrim(xx)
		xx = rtrim(xx)
					
		xx2 = ltrim(xx2)
		xx2 = rtrim(xx2)
		
	       if(xx != "")
		{
		
			if(isNaN(xx))
			{
				alert(fldlbl + " must be a Number.")
				y = 1;
			}
	
			if(xxst == "notbetween" || xxst == "between")
			{
				if(isNaN(xx2) || xx2 == "")
				{
					alert("The second value for " + fldlbl + " must be a Number.")
					y = 1;
				}
			}
		}
	}
	else
	{

		if(theform[fldname].tagName.toLowerCase() != "select")
		{

			if(!theform[fldname].value == "")
			{

				xx = theform[fldname].value
				
				xx = ltrim(xx)
				
				if(isNaN(xx))
				{
					alert(fldlbl + " must be a Number.")
					y = 1;
				}
			
			       xx = theform[fldname].value;
				theform[fldname].value = replace_norm(xx, " ", "")
			}

		}
		else
		{
			
			theform[fldname].options[0].selected = false;
		}
	}
   }

   
   if(fldtype == "Date")
   {
	xx = theform["f1_" + ssid].value
	xx2 = theform["f2_" + ssid].value
	xxst = theform["st_" + ssid].options[theform["st_" + ssid].selectedIndex].value
	
	xx = ltrim(xx)
	xx = rtrim(xx)
				
	xx2 = ltrim(xx2)
	xx2 = rtrim(xx2)
	
	if(xx != "")
	{
		/* Check against the days counter */
		if(xx.indexOf("days") > -1)
		{
			xx = xx.replace("days", "")
			xx = xx.replace(" ", "")
			if(isNaN(xx) || xx == "")
			{
				window.alert(fldlbl + " has an invalid number of days specified.");
				y = 1;

			}
			return y;
		}
		
		if (xx != 'today' && xx != 'yesterday' && xx.indexOf("day") > -1) {
			xx = xx.replace("day", "")
			xx = xx.replace(" ", "")
			if (isNaN(xx) || xx == "") {
				window.alert(fldlbl + " has an invalid number specified.");
				y = 1;
			}
			return y;
		}

		
		/* Check against month number */
		if (xx.indexOf("month") > -1) {
			xx = xx.replace("month", "")
			xx = xx.replace(" ", "")
			if (isNaN(xx) || xx == "") {
				window.alert(fldlbl + " has an invalid month specified.");
				y = 1;
			}
			return y;
		}

		/* Check against year number */
		if (xx.indexOf("year") > -1) {
			xx = xx.replace("year", "")
			xx = xx.replace(" ", "")
			if (isNaN(xx) || xx == "") {
				window.alert(fldlbl + " has an invalid year specified.");
				y = 1;
			}
			return y;
		}
		
		
		/* Check against any of the standard keywords */
		if (xx != "today" && xx != "yesterday" && xx != "tomorrow" && xx != "ytd" && xx != "mtd")
		{
			x = validate_date(xx, fldname,  fldlbl)
			if(x != "")
			{
				window.alert(x);
				y = 1;
						
			}
		}
		
		if(xxst == "notbetween" || xxst == "between")
		{
			x = validate_date(xx2, fldname, 'The second value for ' + fldlbl)
			if(x != "")
			{
				window.alert(x);
				y = 1;
						
			}
		}
	}
    }

    return y;
}


/*
This function determines whether a field is empty.
*/
function validateIsEmpty(passed_form, fldname, displaytype, boolEmpty)
{
	
	if(displaytype == "Select" || displaytype == "Select Type-In")
	{
		if(passed_form[fldname].selectedIndex > 0) boolEmpty = false;
	}
	
	else if(displaytype == "Radio")
	{
		radioFound = false;

		for(var i = 0; i < passed_form[fldname].length; i++)
		{

			if(passed_form[fldname][i].checked) radioFound = true;
		}

		if(radioFound == true) boolEmpty = false;
	}
	
	else if(displaytype == "Checkbox")
	{
		checkFound = false;
		if(passed_form[fldname].length)
		{
			for(var i = 0; i < passed_form[fldname].length; i++)
			{
				if(passed_form[fldname][i].checked) checkFound = true;
			}
		}
		else
		{
			if(passed_form[fldname].checked) checkFound = true;
		}
		
		
		if(checkFound == true) boolEmpty = false;
	}
	else if(displaytype == "File Image" || displaytype == "File Slot")
	{
		var FileFound = true
		if(document.getElementById(fldname + '_newfile').value == '')
		{ 
			if(document.getElementById(fldname).value == '')
			{
				 FileFound = false;
			}
			else if(document.getElementById(fldname + '_deletefile').checked)
			{
				FileFound = false;
			}
			
		}
		if(FileFound == true) boolEmpty = false;
	}
	else if(displaytype == "Phone Number")
	{
		if(passed_form[fldname + '_areacode'].value != '' ||
			passed_form[fldname + '_prefix'].value != '' ||
			passed_form[fldname + '_line'].value != '' ||
			passed_form[fldname + '_ext'].value != '')
		{
			boolEmpty = false;
		}	
	
	}
	

	else
	{
		
		if(passed_form[fldname].value != "")
		{
			boolEmpty = false;
		}
	}
	return boolEmpty;
}


/*
This function sets a field's value
*/
function setFieldValue(passed_form, fldname, displaytype, newValue, newValuePlainText)
{

	if(!passed_form[fldname] && !passed_form[fldname+ "_areacode"]) return false;
	
	if ((displaytype == "Select" || displaytype == "Select Type-In") && passed_form[fldname].options) {

	    for (e = 0; e < passed_form[fldname].options.length; e++) {
	        if (passed_form[fldname].options[e].value == newValue) { passed_form[fldname].options[e].selected = true; } else { passed_form[fldname].options[e].selected = false; }
	    }

	    if (displaytype == "Select Type-In") {

	        passed_form[fldname + '_typein'].value = newValuePlainText;
	    }

	}
	else if (displaytype == 'Type-In Lookup' || displaytype == 'Type-In Lookup (With Add New)') {
	    passed_form[fldname].value = newValue;
	    passed_form[fldname + '_textbox'].value = newValuePlainText;
	}

	else if (displaytype == 'Select Popup' || displaytype == 'Section Search Popup') {
	    passed_form[fldname].value = newValue;
	    passed_form[fldname + '_label'].value = newValuePlainText;

	}

	else if (displaytype == "Radio" || displaytype == "Multiple Choice (Radio)") {
	    for (var i = 0; i < passed_form[fldname].length; i++) {

	        if (passed_form[fldname][i].value == newValue) {
	            passed_form[fldname][i].checked = true;
	        }
	        else {
	            passed_form[fldname][i].checked = false;
	        }
	    }

	}

	else if (displaytype == "Checkbox" || displaytype == "Multiple Choice (Checkbox)") {

	    if (passed_form[fldname].length) {
	        for (var i = 0; i < passed_form[fldname].length; i++) {
	            if (passed_form[fldname][i].value = newValue) {
	                passed_form[fldname][i].checked = true;
	            }
	            else {
	                passed_form[fldname][i].checked = false;
	            }
	        }

	    }
	    else {
	        if (newValue == '1') { passed_form[fldname].checked = true } else { passed_form[fldname].checked = false };
	    }

	}
	else if (displaytype == "Phone Number")
	{
		
		
		var strPhoneComp = new String(newValue);
		strPhoneComp = replace_norm(strPhoneComp, "-", " ");
		strPhoneComp = replace_norm(strPhoneComp, "(", "");
		strPhoneComp = replace_norm(strPhoneComp, ")", "");
		strPhoneComp = replace_norm(strPhoneComp, " x ", " ");
		strPhoneComp = replace_norm(strPhoneComp, "  ", " ");
		
		var arrPhone = strPhoneComp.split(" ");
		if(arrPhone.length > 0)
		{
			passed_form[fldname + '_areacode'].value = arrPhone[0];
		}	
		else
		{
			passed_form[fldname + '_areacode'].value = '';
		}	

		if(arrPhone.length > 1)
		{
			passed_form[fldname + '_prefix'].value = arrPhone[1];
		}
		else
		{
			passed_form[fldname + '_prefix'].value = '';
		}
		
		if(arrPhone.length > 2)
		{
			passed_form[fldname + '_line'].value = arrPhone[2];
		}	
		else
		{
			passed_form[fldname + '_line'].value = '';
		}		

		if(arrPhone.length > 3)
		{
			passed_form[fldname + '_ext'].value = arrPhone[3];
		}
		else
		{
			passed_form[fldname + '_ext'].value = '';
		}
	
	}
	
	
	else
	{
	    passed_form[fldname].value = newValue;
	}
	

}



/* This function determines the current value of a field. */
function getFieldValue(passed_form, fldname, displaytype)
{

	var strValue = new String('');
	
	if(displaytype == "Select" || displaytype == "Select Type-In")
	{
		if(passed_form[fldname].selectedIndex > 0)
		{
			strValue = passed_form[fldname].options[passed_form[fldname].selectedIndex].value;
		}
	}
	
	else if(displaytype == "Radio" || displaytype == "Multiple Choice (Radio)")
	{
		radioFound = false;

		for(var i = 0; i < passed_form[fldname].length; i++)
		{

			if(passed_form[fldname][i].checked) { strValue = passed_form[fldname][i].value }
		}

		if(radioFound == true) boolEmpty = false;
	}
	
	else if(displaytype == "Checkbox" || displaytype == "Multiple Choice (Checkbox)")
	{
		s
		strValue = '';
		if(passed_form[fldname].length)
		{
			for(var i = 0; i < passed_form[fldname].length; i++)
			{
				if(passed_form[fldname][i].checked) strValue += passed_form[fldname][i].value + ';';
			}
			if(strValue != '') strValue = strValue.substr(0, strValue.length - 1)
		}
		else
		{
			if(passed_form[fldname].checked) strValue = '1';
		}
		
	}
	else if(displaytype == "Date/Time")
	{
		strValue = passed_form[fldname].value + " " + passed_form[fldname + '_hour'].options[passed_form[fldname + '_hour'].selectedIndex].value + ":" + passed_form[fldname + '_minute'].options[passed_form[fldname + '_minute'].selectedIndex].value + ":00 " + passed_form[fldname + '_ampm'].options[passed_form[fldname + '_ampm'].selectedIndex].value
	
	}
	
	else if(displaytype == "Phone Number")
	{
		strValue = "(" + passed_form[fldname + "_areacode"].value + ")-" + passed_form[fldname + "_prefix"].value + "-" + passed_form[fldname + "_line"].value + " x " + passed_form[fldname + "_ext"].value;
		
		if(strValue == "()-- x ") strValue = "";
		if(strValue.substr(strValue.length - 3, 3) == ' x ') strValue = strValue.substr(0, strValue.length - 3)
	
	}
	
	else
	{
		
		strValue = passed_form[fldname].value;
	}
	
	return strValue;
	
}




function subNavValidate()
{

	if(editOccured == true) {
		return confirm('Clicking on this link will result in your current edits not being saved.');
	} else {
		return true
	}

}





function structureTypeInLookupChange(structureid, fieldName, boolAddItem)
{
    var hidElement = window.document.getElementById(fieldName);
    var txtElement = window.document.getElementById(fieldName + '_textbox');

	var strPost = new String('');
	
	var addElem;
	var strAddItem;
	if (boolAddItem == true) { strAddItem = 'true'; } else { strAddItem = 'false'; }
	
	if(txtElement.value == '') 
	{
	
		hidElement.value = '';
		structureTypeInLookupHideAdd(fieldName);
		structureTypeInLookupHide(fieldName);
		txtElement.className = 'structureTypeInLookupNotSelected';
	}
	else
	{
	    strPost = 'structureid=' + structureid + '&fieldname=' + encodeURIComponent(fieldName) + '&textvalue=' + encodeURIComponent(txtElement.value) + '&additem=' + strAddItem
		var url = "ajax_handletypeinlookup.aspx?" + window.location.search.substring(1);
		xmlHttpTypeInLookup = GetXMLHttpObject(handleStructureTypeInLookupChange);
		xmlHttpTypeInLookup.open("POST", url, true);
		xmlHttpTypeInLookup.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlHttpTypeInLookup.send("action=post&" + strPost);
	}	

	

}

function handleStructureTypeInLookupChange()
{

	if (xmlHttpTypeInLookup.readyState == 4 || xmlHttpTypeInLookup.readyState == "complete")
	{
	
		eval(xmlHttpTypeInLookup.responseText);

	}

}

function structureTypeInLookupShow(fieldName, strString) {

   
     var textElem = window.document.getElementById(fieldName + '_textbox');
     var divElem = window.document.getElementById(fieldName + '_lookuplistdiv');

 

     var xer = 0; var yer = 0;
     var cOffset = textElem;
     while (cOffset.offsetParent) {

         xer += cOffset.offsetLeft
         yer += cOffset.offsetTop
         cOffset = cOffset.offsetParent

     }
     
     // divElem.style.width = textElem.clientWidth;
     divElem.innerHTML = strString;

     divElem.style.position = 'absolute';
     divElem.style.display = 'inline';
     
     divElem.style.top = (yer + textElem.clientHeight) + 'px'
     divElem.style.left = (xer) + 'px'
     divElem.style.zIndex= 2000
 }

 function structureTypeInLookupHide(fieldName) {
    
     var divElem = window.document.getElementById(fieldName + '_lookuplistdiv');
 
     divElem.innerHTML = '';
     divElem.style.display = 'none';

 }


 function structureTypeInLookupSetValueAndTextBox(fieldName, newValue, newLookupValue) {


     var hidElement = window.document.getElementById(fieldName);
     var txtElement = window.document.getElementById(fieldName + '_textbox');

     hidElement.value = newValue;
     txtElement.value = newLookupValue;

     if (newValue != '') {
         txtElement.className = 'structureTypeInLookupSelected';
     }
     else {
         txtElement.className = 'structureTypeInLookupNotSelected';
     }
     structureTypeInLookupHideAdd(fieldName);
 }

 function structureTypeInLookupSetValue(fieldName, newValue) {


     var hidElement = window.document.getElementById(fieldName);
     var txtElement = window.document.getElementById(fieldName + '_textbox');
     hidElement.value = newValue;

     if (newValue != '') {
         txtElement.className = 'structureTypeInLookupSelected';
     }
     else {
         txtElement.className = 'structureTypeInLookupNotSelected';
     }
     structureTypeInLookupHideAdd(fieldName);
 }

 function structureTypeInLookupShowAdd(fieldName)
 {

	var aElement = window.document.getElementById(fieldName + '_addlookupitem');
	if(aElement)
	{
		aElement.style.display = 'inline';
	}
 }

 function structureTypeInLookupHideAdd(fieldName)
 {

	var aElement = window.document.getElementById(fieldName + '_addlookupitem');
       if(aElement)
	{ 
		aElement.style.display = 'none';
	}
 }

 function getWordCount(Words)
 {
	
	var strWords = new String(Words);
	var wordCount = 0;
	
	strWords = strWords.replace(/(\.|\?|\!|\;|\,)/g, ' ');

	var arrWords = strWords.split(' ');
	for(var i = 0; i < arrWords.length; i++)
	{
		if(arrWords[i] != '') wordCount += 1;
	}
	return wordCount;

 }

function displayWordCount(elementId, maximumWordCount)
{
	var elem = document.getElementById(elementId);
	var elemLabel = document.getElementById(elementId + '_wordcount');
	
	var strHTML = (maximumWordCount - getWordCount(elem.value)) + ' words left';
	if(elemLabel.innerHTML != strHTML) elemLabel.innerHTML = strHTML;

}

