<!--//
/*
// Name: UIElements.js
// Purpose: Repository of functions for validating data entry prior to accepting a form submit
// Author: Michael Bane (mtb)
// Date: 02/19/2003
// Modification History:
// 02/19/2003	mtb	Most functions are written by me; however, some are snippets collected from the web
// 03/19/2003		All array information related to asset classes has been
//					remove, since that control has been changed to checkboxes.
// 03/26/2003	mtb	Not doing any page validation until the review page
//					to avoid annoying popups
					Just putting a "break" at the start of each case
// 03/27/2003	mtb	Adding all validation test (e.g. numerics) that occur onBlur
//					to the final check
*/
// LIST OF FUNCTIONS

function appValidateInput(intPage){
/*
	// False: reloads form
	// True: processes submit
MODIFICATION HISTORY:
10/06/2008	mtb	Adding scrollto top if errors.
				Adding event argument for the msg window.	
				Instead, here we should not be displaying the error with each valication since we are building an error string.
				Setting showmsg to false.
*/	
	//alert('Running appValidateInput...');
	var blnIsValid = true;
	var strErrors = '';
	var strErrorsS1 = '';
	var strErrorsS2 = '';
	var strErrorsS3 = '';
	
	var intCountryID = 0;
	var intStateID = 0;
			
	var blnHasSelection = false;
	var blnRetVal = false;
	
	var authCode = $('x29p3').value;	
	
	var datDate = new Date();
	var strYear = datDate.getFullYear(); // getYear can be 2,3,or 4 digit, getFullYear returns 4 digit only
	var strYear1 = eval(strYear) - 1;
	var strYear2 = eval(strYear) - 2;
	var strYear3 = eval(strYear) - 3;

	
	//alert('blnIsValid = ' + blnIsValid);
	//alert("Test");
	resetErrorMsg();
	
	//alert('validating page...' + intPage);	
	switch(intPage){
		case "1": // General Info						
			break;
		case "2": // Company Profile			
			break;
		case "3": // Financials			
			break;
		case "4": // Review (no additional test)
			//alert('validating page...4');	
			//alert('validating page...4');
			
			//////////////////////////////////////////////////////////////////////////////////
			// General Information
			// MODIFICATION HISTORY:
			//	03/24/2006	mtb	Removing validation for controls that have been deleted e.g. Assets questions
			//////////////////////////////////////////////////////////////////////////////////
			
			//alert('validating page...4 - General Information');
			
			//////////////////////////////////////////////////////////////////////////////////
			// Company Information
			//////////////////////////////////////////////////////////////////////////////////
			
			
			if($('txtCompanyName').value  == '') strErrorsS1 += 'Company Name.\n';
			if($('txtStreet').value == '') strErrorsS1 += 'Street Name.\n';
			if($('txtCity').value == '') strErrorsS1 += 'City.\n';
			if($('cboState').selectedIndex <= 0 ) strErrorsS1 += 'State.\n';
			if($('txtZip').value  == '') strErrorsS1 += 'Zip / Postal Code.\n';
			if($('cboCountry').selectedIndex <= 0 ) strErrorsS1 += 'Country.\n';
			
			
			// If non-US then that should be selected in the state
			// If US then NOT the non-US state option
			intCountryID = eval($('cboCountry').options[$('cboCountry').selectedIndex].value);			
			intStateID = eval($('cboState').options[$('cboState').selectedIndex].value);
			if(intCountryID == 268) { // US
				// State must be US or unselected (at this point)				
				if((intStateID >=60) ||(intStateID == 0))	strErrorsS1 += 'You must select a US state if you are in the United States.\n';
				// We can only validate the Zip for numerics if it is US.
				if(!(validateUSZip($('txtZip'),false))) strErrorsS1 += 'Zip / Postal Code is invalid for US format.\n';	
			}else{ // Non-US
				// State must be Non-US
				if((g_intNonUSStateID > 0) && (intStateID != g_intNonUSStateID))
					strErrorsS1 += 'State must be outside the US if the country is not in the United States.\n';				
			}			
			
			// 08/08/2008	mtb	We need to validate the website if one was supplied
			// 08/11/2008	mtb	The repeated scripting error for line 146 was actually a missing parenthesis here.
			//alert("Website = " + $('txtWebsite').value);
			if(!($('txtWebsite').value  == '')){
				//alert('Website = ' + $('txtWebsite').value );
				if(!(validateURL($('txtWebsite'), false)))
					 strErrorsS1 += 'The Website needs to be in the correct format (e.g. http://www.yourdomain.com).\n';
			}
			
			//////////////////////////////////////////////////////////////////////////////////
			// Applicant (Preparer)
			//////////////////////////////////////////////////////////////////////////////////
			if($('txtAppFirstName').value == '') strErrorsS1 += 'Preparer - First Name.\n';
			if($('txtAppLastName').value == '') strErrorsS1 += 'Preparer - Last Name.\n';
			if($('txtAppTitle').value == '') strErrorsS1 += 'Preparer - Title.\n';
			// Only tests if referred is selected if index is > 0
			if($('cboReferrer').selectedIndex <= 0 ) 
				strErrorsS1 += 'Preparer - How did you hear about this website.\n';			
			else if($('cboReferrer').options[$('cboReferrer').selectedIndex].value == $('SiteReferrerOthers').value){
				
				if($('txtSiteReferrerOther').value == '') strErrorsS1 += 'Preparer - If referred, by whom.\n';
				
			} 
			
			//////////////////////////////////////////////////////////////////////////////////
			// Validate Primary Contact
			//////////////////////////////////////////////////////////////////////////////////
			if($('txtPCFirstName').value  == '') strErrorsS1 += 'Primary Contact - First Name.\n';
			if($('txtPCLastName').value  == '') strErrorsS1 += 'Primary Contact - Last Name.\n';
			if($('txtPCTitle').value  == '') strErrorsS1 += 'Primary Contact - Title.\n';
			
			// Validate phone
			if($('txtPhone').value  == '') {
				strErrorsS1 += 'Primary Contact - Phone.\n';
			}else{
				blnRetVal = validatePhone($('txtPhone') ,false,1); // Phone
				
				if(!(blnRetVal)) {
					strErrorsS1 += 'Primary Contact - Phone number is invalid. For a US location, the phone number must be in the following format: ###-###-####.\n';
				}			
			}
			// Validate Fax
			if($('txtFax').value  == '') {
				strErrorsS1 += 'Primary Contact - Fax.\n';
			}else{				
				blnRetVal = validatePhone($('txtFax'),false,2); // Fax
				if(!(blnRetVal)) {
					strErrorsS1 += 'Primary Contact - Fax number is invalid.  For a US location, the fax number must be in the following format: ###-###-####..\n';
				}			
			}
			// Validate Email
			if($('txtEmail').value  == '') {
				strErrorsS1 += 'Primary Contact - Email.\n';
			} else{
				blnRetVal = validateEmail2($('txtEmail'),false); // Email
				if(!(blnRetVal)) {
					strErrorsS1 += 'Primary Contact - Email is invalid.\n';
				}	
			}
			
			
			if(strErrorsS1 != '') strErrorsS1 = '----------S T E P   1----------\n' + strErrorsS1;
			
			//////////////////////////////////////////////////////////////////////////////////
			// Company Profile
			//////////////////////////////////////////////////////////////////////////////////
			
			//alert('validating page...4 - Company Profile');
			
			//////////////////////////////////////////////////////////////////////////////////
			// Asset Classes
			//////////////////////////////////////////////////////////////////////////////////
			// 09/02/2008	mtb	To get the arry of checkboxes we need getElementsByName and just Length not options since not a dropdown
			if($Name('chkAssetRes')[$Name('chkAssetRes').length-1].checked){
				if($('txtAssetResOther').value == '')  strErrorsS2 += 'Asset Classes (Residential) other description is required if "other" is checked.\n';
			}
			
			//if($('chkAssetHtl($('chkAssetHtl').length-1).checked){
				// No other
			//}
			if($Name('chkAssetInd')[$Name('chkAssetInd').length-1].checked){
				if($('txtAssetIndOther').value == '')  strErrorsS2 += 'Asset Classes (Industrial) other description is required if "other" is checked.\n';
			}
			if($Name('chkAssetOff')[$Name('chkAssetOff').length-1].checked){
				if($('txtAssetOffOther').value == '')  strErrorsS2 += 'Asset Classes (Office) other description is required if "other" is checked.\n';
			}
			if($Name('chkAssetRet')[$Name('chkAssetRet').length-1].checked){
				if($('txtAssetRetOther').value == '')  strErrorsS2 += 'Asset Classes (Retail) other description is required if "other" is checked.\n';
			}
			
			// Test that at least one asset class is selected
			// General Note: Debug tip - did you try to define a specific data type		
			blnHasSelection = false;				
			for (var intClass = 0; intClass < 6; intClass++){
				switch(intClass){				
					case 0: // Residential
						for(var x = 0; x < $Name('chkAssetRes').length; x++){
							if($Name('chkAssetRes')[x].checked){
								blnHasSelection = true;
								break;
							}
						}
						break;
					case 1: // Hotel
						if($('chkAssetHtl').checked) blnHasSelection = true;					
						break;						
					case 2: // Industrial
						for(var x = 0; x < $Name('chkAssetInd').length; x++){
							if($Name('chkAssetInd')[x].checked){
								blnHasSelection = true;
								break;
							}
						}						
						break;						
					case 3: // Office
						for(var x = 0; x < $Name('chkAssetOff').length; x++){
							if($Name('chkAssetOff')[x].checked){
								blnHasSelection = true;
								break;
							}
						}
						break;						
					case 4: // Retail
						for(var x = 0; x < $Name('chkAssetRet').length; x++){
							if($Name('chkAssetRet')[x].checked){
								blnHasSelection = true;
								break;
							}
						}
						break;
					case 5: // Specialty
						if($('chkAssetSpecial').checked) blnHasSelection = true;
						break;
				}				
				if(blnHasSelection) break; 
			}
			
			if(!(blnHasSelection))  strErrorsS2 += 'You must select as least one Asset Class.\n';
			
			if($('ttaInvFocus').value  == '') strErrorsS2 += 'Describe your company\'s investment niche or focus.\n';
			if($('ttaCompAdv').value  == '') strErrorsS2 += 'Define your competitive advantage.\n';
			
			//////////////////////////////////////////////////////////////////////////////////
			// Business Structure
			//////////////////////////////////////////////////////////////////////////////////
			// Year Founded
			if($('txtYearFounded').value  == '') {
				strErrorsS2 += 'Year Founded.\n';
			} else{
				blnRetVal = validateNumeric($('txtYearFounded'),false,'Year Founded'); // Year Founded
				
				if(!(blnRetVal)) {
					strErrorsS2 += 'Only numeric entries are allowed in the Year Founded field..\n';
				}	
				blnRetVal = validateYear($('txtYearFounded'),1850,strYear ,false,'Year Founded'); // Year Founded
				if(!(blnRetVal)) {
					strErrorsS2 += 'The values for the Year Founded field must be between 1850 and ' + strYear + '.\n';
				}	
			}
			
			if($('cboOwnership').selectedIndex <= 0 ) strErrorsS2 += 'Ownership Structure.\n';
			if($('cboBizType').selectedIndex <= 0 ) strErrorsS2 += 'Corporate Structure.\n';
			if($('cboHasBoard').selectedIndex <= 0 ) strErrorsS2 += 'Do you have a board of directors?.\n';
			
			//////////////////////////////////////////////////////////////////////////////////
			// Assets
			//////////////////////////////////////////////////////////////////////////////////

			//////////////////////////////////////////////////////////////////////////////////
			// Investment Locations
			//////////////////////////////////////////////////////////////////////////////////

			//////////////////////////////////////////////////////////////////////////////////
			// Senior Management Team
			//////////////////////////////////////////////////////////////////////////////////
			
			
			if(strErrorsS2 != '') strErrorsS2 = '----------S T E P   2----------\n' + strErrorsS2;
			
			//////////////////////////////////////////////////////////////////////////////////
			// Financials
			//////////////////////////////////////////////////////////////////////////////////
			
			//alert('validating page...4 - Financials');
			
			// Current Capital Cost
			// If there is a value then it must be numeric
			//if($('txtCurrCapCost').value  == '') strErrorsS3 += 'Current Cost of Capital.\n';
			if(!($('txtCurrCapCost').value  == '')){
				blnRetVal = validateNumeric($('txtCurrCapCost'),false,'Current Cost of Capital'); // Current Cost of Capital
				
				if(!(blnRetVal)) {
					strErrorsS3 += 'Only numeric entries are allowed in the Current Cost of Capital field..\n';
				}	
			}
			
			if($('cboReqCap12Mos').selectedIndex <= 0 ) strErrorsS3 += 'Capital requirements for the next 12 months.\n';
			if($('cboReqCap24Mos').selectedIndex <= 0 ) strErrorsS3 += 'Capital requirements for the next 24 months.\n';
			
			// Capital Use
						
			// If other is selected then must have other text
			if($Name('chkCapitalUse')[$Name('chkCapitalUse').length-1].checked){
				if($('txtCapitalUseOther').value == '')  strErrorsS3 += 'Capital use other description is required if "other" is checked.\n';
			}
			// Ensure that at least one is selected
			blnHasSelection = false;
			for(var x = 0; x < $Name('chkCapitalUse').length; x++){
				if($Name('chkCapitalUse')[x].checked){
					blnHasSelection = true;
					break;
				}
			}
			if(!(blnHasSelection)) strErrorsS3 += 'You must select as least one Preferred Use of Capital.\n';
			
			
			
			//if($('cboInvPref').selectedIndex <= 0 ) strErrorsS3 += 'Do you prefer debt or equity?.\n';
			if($('cboWillCoInv').selectedIndex <= 0 ) strErrorsS3 += 'Are you willing to co-invest?.\n';
			
			
			if($('cboInvStrats').selectedIndex <= 0 ) strErrorsS3 += 'Investment strategy.\n';
			if($('txtPropInvDebtRangeVal').value  == ''){
				strErrorsS3 += 'Debt in proposed investment.\n';
			} else{
				blnRetVal = validateNumeric($('txtPropInvDebtRangeVal'),false,'Debt in proposed investment'); // Expected ROI
				
				if(!(blnRetVal)) {
					strErrorsS3 += 'Only numeric entries are allowed in the Debt in proposed investment field.\n';
				}	
			}
			
			if($('txtExpectedROI').value  == ''){
				strErrorsS3 += 'Expected return on investment.\n';
			} else{
				blnRetVal = validateNumeric($('txtExpectedROI'),false,'Expected ROI'); // Expected ROI
				
				if(!(blnRetVal)) {
					strErrorsS3 += 'Only numeric entries are allowed in the Expected ROI field.\n';
				}	
			}
			
			// 04/08/2005	mtb	 Removed per Jim's request
			// Financial History
			// If there are values then they must be numeric
			
			// Check the user authentication field
			var authCode = $('x29p3').value;
			//alert('authCode = ' + authCode);
			if($('txtAuthCode').value == '') {
				strErrorsS3 += 'User authentication.\n';
			}else{
			 	if($('txtAuthCode').value != authCode){
					strErrorsS3 += 'User authentication does not match the image.\n';
				}
			}
			if(strErrorsS3 != '') strErrorsS3 = '----------S T E P   3----------\n' + strErrorsS3;	
			//alert('Exiting switch block');
			
			break;	
	}	 
	
	//alert('Testing error strings');		
	if(intPage < 4 ){
		if(strErrors != '') {
			strErrors = 'You will need to return to --STEP ' + intPage + '-- before submitting the form. Some required entries are missing:\n\n' + strErrors;
			alert(strErrors);
		}
	}else{
		if(strErrorsS1 != '' || strErrorsS2 != '' || strErrorsS3 != '' ) {
			strErrors = 'The following required entries are missing or invalid:\n' + strErrors;
			// For testing doing both popup and div
			var bShowPopups = false;
			if(bShowPopups) {
				alert(strErrors + strErrorsS1 + strErrorsS2 + strErrorsS3);
			}
			//var tblMsgs = $('tblErrorMsgs');
			//tblMsgs.style.visibility = "";
			showErrorMsg(strErrors + strErrorsS1 + strErrorsS2 + strErrorsS3,null,null,true);
			/*
			var oMsgs = $('ErrorMsgs');
			oMsgs.style.visibility = "";
			
			var sMsg = strErrors + strErrorsS1 + strErrorsS2 + strErrorsS3;
			sMsg = sMsg.replace(/\n/gi,"<BR>");
			oMsgs.innerHTML = sMsg;
			*/
			
			blnIsValid = false;
		}
	}
	
	//alert('blnIsValid = ' + blnIsValid);
	
	// Set the validation flag
	$('IsValid').value = blnIsValid; 
	if(blnIsValid)  
		SetSecurityCookie('NE', '0');
	else
		// Force a move to the top of the page so the user can see any error messages.
		window.scrollTo(0,0);

	
				
	return blnIsValid;
	
}



function validateMetricSearch(){
	if($('fbm').selectedIndex <= 0){
		alert('You must select a metric level.');
		return false;
	}else{
 		$('p').value=2; 
		document.getElementByName("frmNav")[0].submit();
	}
	return true;
}

function validateEditForm(strFormName){
	var blnIsValid = false;
	var strErrors = '';
	var blnHasSelection = false;
	
	//alert('Form = ' + strFormName);
	
	switch(strFormName){
		case 'frmCompanyAtAGlance':
			// 03/17/2006	mtb	Changing to use the checkbox status rather than the dropdown
			if((!($('chkIsProspect').checked)) && (($Name("chkDiligenceStages")[9].checked)|| ($Name("chkDiligenceStages")[10].checked))){
				// Need to change to a non-prospect status if not a prospect
				strErrors += 'You need to change to a non-prospect status if this company is not a prospect.\n';
			}
			
			// 03/17/2006	mtb Need to add a check that if a stage is checked that date needs to be entered
			//					This may present some issues if it is for a preexisting entry
			//					For now just skipping it until further details known 
			//					Need some entry or the array indexing is wrong, possibly a default of [No Date]
			for(var i = 0; i < $Name("chkDiligenceStages").length; i++){
				if($Name("chkDiligenceStages")[i].checked){
					if($Name("txtDiligenceStages")[i].value == '') $Name("txtDiligenceStages")[i].value ='[No Date]';
				}
			}
			
			if(strErrors == '')  blnIsValid = true;
			if(blnIsValid){
				setSubmitValuesAtAGlance();
			}
			break;
			
		case 'frmCompanyAddress': 
			// 06/02/2008	mtb	companyAddress and AddCompany now differ greatly so they now have separate validation blocks.
			if($('txtCompanyName').value  == '') strErrors += 'Company Name.\n';
			if($('txtStreet').value == '') strErrors += 'Street Name.\n';
			if($('txtCity').value == '') strErrors += 'City.\n';
			if($('cboState').selectedIndex <= 0 ) strErrors += 'State.\n';
			if($('txtZip').value  == '') strErrors += 'Zip / Postal Code.\n';
			if($('cboCountry').selectedIndex <= 0 ) strErrors += 'Country.\n';
			// If the website is filled in then it needs to be correctly formatted (TBD)
			// 06/03/2008	mtb This incorrectly was requiring the website. Website not required only properly formatted if entered.
			//if($('txtWebsite.value  == '') 
			//	strErrors += 'Website.\n';
			if(!($('txtWebsite').value  == '') ){
				if(!(validateURL($('txtWebsite'), false))) // Note: use the control, not the control.value
				strErrors += 'Website (URL) is invalid.\n';
			}
			
			// Only tests if referred is selected if index is > 0
			if($('cboReferrer').selectedIndex <= 0 ) 
				strErrors += 'Preparer - How did you hear about this website.\n';			
			else if($('cboReferrer').options[$('cboReferrer').selectedIndex].value == $('SiteReferrerOthers').value){
				
				if($('txtSiteReferrerOther').value == '') strErrors += 'Preparer - If referred, by whom.\n';
				
			}
			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmAddCompany':
			// 09/09/2003	mtb With the addition of prospects, we need to add validation
			//					if the entry is for a prospect
			var blnIsProspect;
			if(!( $('chkIsProspect') ==  null))
				blnIsProspect = $('chkIsProspect').checked;
			else
				// If it is false either we are on the EditCompanyAddress or this is not a prospect
				// on the AddCompany page. Either way, we would only require the companyname.
				blnIsProspect = false;
			//alert("IsProspect = " + blnIsProspect);
			if($('txtCompanyName').value  == '') strErrors += 'Company Name.\n';
			if(blnIsProspect){
				if($('cboState').selectedIndex <= 0 ) strErrors += 'State.\n';
				//if($('cboContact.selectedIndex <= 0 ) strErrors += 'Contact.\n';
				if($('cboDiligenceStage').selectedIndex <= 0 ) {
					strErrors += 'Status.\n';
				}else{
					// If reject then a reason is required
					if(($('cboDiligenceStage').selectedIndex == 1 ) && ($('ttaRejectReason').value  == ''))
						strErrors += 'Reason For Rejection.\n';
				}
			}
			//////////////////////////////////////////////////////////////////////////////////
			// Asset Classes
			//////////////////////////////////////////////////////////////////////////////////
			
			if($Name("chkAssetRes")[$Name("chkAssetRes").length-1].checked){
				if($('txtAssetResOther').value == '')  strErrors += 'Asset Classes (Residential) other description is required if "other" is checked.\n';
			}
			//if($('chkAssetHtl($('chkAssetHtl.length-1).checked){
				// No other
			//}
			if($Name("chkAssetInd")[$Name("chkAssetInd").length-1].checked){
				if($('txtAssetIndOther').value == '')  strErrors += 'Asset Classes (Industrial) other description is required if "other" is checked.\n';
			}
			if($Name("chkAssetOff")[$Name("chkAssetOff").length-1].checked){
				if($('txtAssetOffOther').value == '')  strErrors += 'Asset Classes (Office) other description is required if "other" is checked.\n';
			}
			if($Name("chkAssetRet")[$Name("chkAssetRet").length-1].checked){
				if($('txtAssetRetOther').value == '')  strErrors += 'Asset Classes (Retail) other description is required if "other" is checked.\n';
			}
			if($('chkAssetSpecial').checked){
				if($('txtAssetSpecialOther').value == '')  strErrors += 'Asset Classes (Specialty) description is required if it is checked.\n';
			}
			// Test that at least one asset class is selected
			// General Note: Debug tip - did you try to define a specific data type		
			blnHasSelection = false;				
			for (var intClass = 0; intClass < 6; intClass++){
				switch(intClass){				
					case 0: // Residential
						for(var x = 0; x < $Name("chkAssetRes").length; x++){
							if($Name("chkAssetRes")[x].checked){
								blnHasSelection = true;
								break;
							}
						}
						break;
					case 1: // Hotel
						if($('chkAssetHtl').checked) blnHasSelection = true;					
						break;						
					case 2: // Industrial
						for(var x = 0; x < $Name("chkAssetInd").length; x++){
							if($Name("chkAssetInd")[x].checked){
								blnHasSelection = true;
								break;
							}
						}						
						break;						
					case 3: // Office
						for(var x = 0; x < $Name("chkAssetOff").length; x++){
							if($Name("chkAssetOff")[x].checked){
								blnHasSelection = true;
								break;
							}
						}
						break;						
					case 4: // Retail
						for(var x = 0; x < $Name("chkAssetRet").length; x++){
							if($Name("chkAssetRet")[x].checked){
								blnHasSelection = true;
								break;
							}
						}
						break;
					case 5: // Specialty
						if($('chkAssetSpecial').checked) blnHasSelection = true;					
						break;						
				}				
				if(blnHasSelection) break; 
			}
			
			if(!(blnHasSelection))  strErrors += 'You must select as least one Asset Class.\n';
				
			// For validation on submit only check if both have a been set
			if(	$('cboReqCap12Mos').selectedIndex > 0 && eval($('txtReqCap12MosVal').value) > 0){
				if(!(validateReqCap($('cboReqCap12Mos'),'Required Capital - 12 months','combo',$('cboReqCap12MosMin'),$('cboReqCap12MosMax'),$('txtReqCap12MosVal'),false)))
					strErrors += 'The range selected for (Required Capital - 12 months) is inconsistent with the entered value.\n';
			}
			if(	$('cboReqCap24Mos').selectedIndex > 0 && eval($('txtReqCap24MosVal').value) > 0){
				if(!(validateReqCap($('cboReqCap24Mos'),'Required Capital - 24 months','combo',$('cboReqCap24MosMin'),$('cboReqCap24MosMax'),$('txtReqCap24MosVal'),false)))
			 		strErrors += 'The range selected for (Required Capital - 24 months) is inconsistent with the entered value.\n';
			}
			
			// Ensure than if any of the contact information is entered than there must be a first and last name
			////if($('txtCompanyName.value  == '') strErrors += 'Company Name.\n';
			
			if(
				(
				   (!($('txtTitle').value  == ''))  
				|| (!($('txtYrsFirm').value  == '')) 
				|| (!($('txtYrsInd').value  == '')) 
				//|| (!($('cboIsMgmt.value  == ''))
				|| (!($('ttaBio').value  == '') ) 
				|| (!($('txtContactCompanyName').value  == '') )
				) 
				&& (($('txtFirstName').value  == '') || ($('txtLastName').value  == ''))
			)
				strErrors += 'You must enter both a First Name and Last Name to add a Primary Contact.\n';
			
			// If the website is filled in then it needs to be correctly formatted (TBD)
			
			if(strErrors == '')  blnIsValid = true;
			break;
	
		case 'frmCompanyDefinition':
		
			if(strErrors == '')  blnIsValid = true;
			
			if(blnIsValid){
				setSubmitValuesCompDef();
			}
			break;
	
		case 'frmCompanyBusStruct':
			if(strErrors == '')  blnIsValid = true;
			break;
			
		case 'frmCompanyContctRec':
			
			if($('txtFirstName').value  == '') strErrors += 'First name.\n';
			if($('txtLastName').value  == '') strErrors += 'Last name.\n';
			
			if(strErrors == '')  blnIsValid = true;
			
			if(blnIsValid){
				setSubmitValuesCompContacts();
			}
			break;
		case 'frmCompanyAssets':
			if($('txtAUMCurrent').value  == '') strErrors += 'What is the market value of current portfolio or business?.\n';
			//if($('txtAUMLife.value  == '') strErrors += '$ volume of investment or development activity over the life of the company.\n';
			if($('txtAUM3YR').value  == '') strErrors += '$ volume of investment or development activity in the past 3 years.\n';
			// CapReqPipelineVal required only if DealPipeline entered
			if(($('txtDealPipeline').value  != '') && ($('txtDealPipeline').value  > 0)){				 
				if($('txtCapReqPipelineVal').value  == '') strErrors += 'A percent taken down with capital requested is required if the deal pipeline value is greater than zero.\n';
			}
		
			if(strErrors == '')  blnIsValid = true;
			
			if(blnIsValid) {
				setSubmitValuesCompAsset();
			}
			
			break;
		case 'frmCompanyFinancialNeeds':
			// Capital Use
			// If other is selected then must have other text
			//alert("$('chkCapitalUse').value = " + $('chkCapitalUse').value);
			//var capUses = $Name('chkCapitalUse');
			//alert("capUses.length = " + capUses.length);
			//alert("$('chkCapitalUse')[2].value = " + $('chkCapitalUse')[2].value);
			//alert("$Name('chkCapitalUse').length = " + $Name('chkCapitalUse').length);
			//alert("$Name('chkCapitalUse')[$Name('chkCapitalUse').length-1].checked = " + $Name('chkCapitalUse')[$Name('chkCapitalUse').length-1].checked);						
			if($Name('chkCapitalUse')[$Name('chkCapitalUse').length-1].checked){
				if($('txtCapitalUseOther').value == '')  strErrors += 'Capital use other description is required if "other" is checked.\n';
			}
			
			if(!(validateReqCap($('cboReqCap12Mos'),'Required Capital - 12 months','combo',$('cboReqCap12MosMin'),$('cboReqCap12MosMax'),$('txtReqCap12MosVal'),false)))
				strErrors += 'The range selected for (Required Capital - 12 months) is inconsistent with the entered value.\n';
			if(!(validateReqCap($('cboReqCap24Mos'),'Required Capital - 24 months','combo',$('cboReqCap24MosMin'),$('cboReqCap24MosMax'),$('txtReqCap24MosVal'),false)))
			 	strErrors += 'The range selected for (Required Capital - 24 months) is inconsistent with the entered value.\n';
			 
			// Ensure that at least one is selected

			// If will co-invest, then level of co-investment must be greater than zero
			// 05/01/2003	mtb Removing requirement
	
	
			if(strErrors == '')  blnIsValid = true;
			
			if(blnIsValid) {
				setSubmitValuesCompFinNeeds();
			}
			break;
		case 'frmCompanyApproachToInvesting':
			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmCompanyFinancials':
			// If any of the financial items are filled in then there must be an 
			// associated date value
			var blnHasEntry = false;
			var blnInNewMode = false;
			var blnNoDate = false;
			var blnHasNegative = false;
			var blnIsHistory = false;
			
			if($('.m').value  == 1) blnInNewMode = true;
			if($('txtGrRev') == null) blnIsHistory = true;
			if(blnIsHistory){
				// Validate financial history
				if(strErrors == '')  blnIsValid = true;
				
			}else{
				// Validate financial statements
				if(($('txtGrRev').value  != '') && ($('txtGrRev').value  > 0)) blnHasEntry = true;
				if(($('txtRecurrRev').value  != '') && ($('txtRecurrRev').value  > 0)) blnHasEntry = true;
				if(($('txtTransacRev').value  != '') && ($('txtTransacRev').value  > 0)) blnHasEntry = true;
				if(($('txtOtherRev').value  != '') && ($('txtOtherRev').value  > 0)) blnHasEntry = true;
				if(($('txtOpExp').value  != '') && ($('txtOpExp').value  > 0)) blnHasEntry = true;
				if(($('txtStaffExp').value  != '') && ($('txtStaffExp').value  > 0)) blnHasEntry = true;
				if(($('txtOccExp').value  != '') && ($('txtOccExp').value  > 0)) blnHasEntry = true;
				if(($('txtTravelExp').value  != '') && ($('txtTravelExp').value  > 0)) blnHasEntry = true;
				if(($('txtSalesCost').value  != '') && ($('txtSalesCost').value  > 0)) blnHasEntry = true;
				if(($('txtOtherGenAdmin').value  != '') && ($('txtOtherGenAdmin').value  > 0)) blnHasEntry = true;
				if(($('txtIntExp').value  != '') && ($('txtIntExp').value  > 0)) blnHasEntry = true;
				if(($('txtTaxDep').value  != '') && ($('txtTaxDep').value  > 0)) blnHasEntry = true;
				if(($('txtBonus').value  != '') && ($('txtBonus').value  > 0)) blnHasEntry = true;
				if(($('txtCash').value  != '') && ($('txtCash').value  > 0)) blnHasEntry = true;
				if(($('txtCashEq').value  != '') && ($('txtCashEq').value  > 0)) blnHasEntry = true;
				if(($('txtInventory').value  != '') && ($('txtInventory').value  > 0)) blnHasEntry = true;
				if(($('txtOtherCurrAsset').value  != '') && ($('txtOtherCurrAsset').value  > 0)) blnHasEntry = true;
				if(($('txtOtherNCurrAsset').value  != '') && ($('txtOtherNCurrAsset').value  > 0)) blnHasEntry = true;
				if(($('txtAP').value  != '') && ($('txtAP').value  > 0)) blnHasEntry = true;
				if(($('txtOtherLiab').value  != '') && ($('txtOtherLiab').value  > 0)) blnHasEntry = true;
				if(($('txtLoans').value  != '') && ($('txtLoans').value  > 0)) blnHasEntry = true;
				if(($('txtOtherNCurrLiab').value  != '') && ($('txtOtherNCurrLiab').value  > 0)) blnHasEntry = true;
				if(($('txtShareHldrEq').value  != '') && ($('txtShareHldrEq').value  > 0)) blnHasEntry = true;
				if(blnHasEntry){
					if(blnInNewMode){
						if($('txtDate').value  == '') blnNoDate = true;
					}else{
						if($('cboDate1').selectedIndex == 0) blnNoDate = true;
					}
					if(blnNoDate) strErrors += 'A date is required if any values have been filled in.\n'
				}
	
				if(($('txtGrRev').value  != '') && ($('txtGrRev').value  < 0)){strErrors += 'Gross Revenue value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtRecurrRev').value  != '') && ($('txtRecurrRev').value  < 0)) {strErrors += 'Recurring Revenue value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtTransacRev').value  != '') && ($('txtTransacRev').value  < 0)) {strErrors += 'Transaction Revenue value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOtherRev').value  != '') && ($('txtOtherRev').value  < 0)) {strErrors += 'Other Revenue value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOpExp').value  != '') && ($('txtOpExp').value  < 0)) {strErrors += 'Operations Expenses value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtStaffExp').value  != '') && ($('txtStaffExp').value  < 0)) {strErrors += 'Staff Expenses value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOccExp').value  != '') && ($('txtOccExp').value  < 0)) {strErrors += 'Occupancy Expenses value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtTravelExp').value  != '') && ($('txtTravelExp').value  < 0)) {strErrors += 'Travel Expenses value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtSalesCost').value  != '') && ($('txtSalesCost').value  < 0)) {strErrors += 'Cost of Sales value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOtherGenAdmin').value  != '') && ($('txtOtherGenAdmin').value < 0)) {strErrors += 'Other General and Admin value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtIntExp').value  != '') && ($('txtIntExp').value  < 0)) {strErrors += 'Interest Expense value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtTaxDep').value  != '') && ($('txtTaxDep').value  < 0)) {strErrors += 'Taxes and Depreciation value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtBonus').value  != '') && ($('txtBonus').value  < 0)) {strErrors += 'Bonus and Incentives value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtCash').value  != '') && ($('txtCash').value  < 0)) {strErrors += 'Cash value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtCashEq').value  != '') && ($('txtCashEq').value  < 0)) {strErrors += 'Cash Equivalents value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtInventory').value  != '') && ($('txtInventory').value  < 0)) {strErrors += 'Inventory value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOtherCurrAsset').value  != '') && ($('txtOtherCurrAsset').value  < 0)) {strErrors += 'Other Current Assets value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOtherNCurrAsset').value  != '') && ($('txtOtherNCurrAsset').value  < 0)) {strErrors += 'Other Non-Current Assets value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtAP').value  != '') && ($('txtAP').value  < 0)) {strErrors += 'AP value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOtherLiab').value  != '') && ($('txtOtherLiab').value  < 0)) {strErrors += 'Other Liability value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtLoans').value  != '') && ($('txtLoans').value  < 0)) {strErrors += 'Loans value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtOtherNCurrLiab').value  != '') && ($('txtOtherNCurrLiab').value  < 0)) {strErrors += 'Other Non-Current Liability value is less than zero.\n'; blnHasNegative = true;}
				if(($('txtShareHldrEq').value  != '') && ($('txtShareHldrEq').value  < 0)) {strErrors += 'Shareholder Equity value is less than zero.\n'; blnHasNegative = true;}
				if(blnHasNegative) strErrors += 'All values must be greater than or equal to zero.\n'
			
				if(strErrors == '')  blnIsValid = true;
				// Change the value of the selected item
				// from ID to Date
				if(blnIsValid) {
					if(!(blnInNewMode)){
						$('txtDate1Val').value = $('cboDate1').options[$('cboDate1').selectedIndex].text; 
					}
				}
			} // if(blnIsHistory) {
			break;
		case 'frmCompanyDueDiligence':
			// Select the appropriate screen
			if($('st').value == "1"){
				// Edit due diligence stage
				if($('cboDiligenceStages').selectedIndex <= 0 ) strErrors += 'Analysis Stage.\n';
			}
			if($('rt').value == "1"){
				// Edit ratings
				if($('cboRating').selectedIndex <= 0 ) strErrors += 'Rating.\n';
			}
			if($('cm').value == "1"){
				// Edit comments
				if($('m').value == "1"){
					// In add new only
					if($('cboGroup').selectedIndex <= 0 ) strErrors += 'Group.\n';					
				}
				// In Edit and Add New
				if($('ttaComment').value == '' ) strErrors += 'Comment.\n';
				
			}
			
		
			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmCompanyDealsRec':
			if($('txtDealName').value == '' ) strErrors += 'Deal name.\n';
			if($('cboDealStatuses').selectedIndex <= 0 ) strErrors += 'Deal status.\n';
			
			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmSysAdmSecurity':
			// If this user is an administrator than the password can just be changed
			// since they are in the manage accounts mode
			
			// If this any other user, the old password and new password need to be confirmed
			
			
			
			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmCompanyMetricsL1ADM':
			// If between than valid date range (update or not this still applies)
			if($('cboDateOperator').selectedIndex == 7){
				// Require an ROI and a date range
				if(($('txtAppliedStart').value == '') && ($('txtAppliedStop').value == ''))  strErrors += 'You must enter a start and end date.\n';
				// Check that date range is valid
				if(dateDiff($('txtAppliedStart').value , $('txtAppliedStop').value, 'd', 0 ) <  0) strErrors += 'The end date must be equal to or greater than the start date.\n';
				
				
			}
			// Must enter a valid ROI
			if($('txtROI').value == ''){
				// Missing entry
				 strErrors += 'Expected ROI.\n';		
			}else{
				// Test for validity
				if($('txtROI').value <= 0 || $('txtROI').value >= 100) strErrors += 'Expected ROI must be between 0.01 and 99.99.\n';	
			}
									
		
			if(strErrors == '')  blnIsValid = true;
			if(blnIsValid) {
				// Enable field so that we can get them in the request object
				// 05/02/2003	mtb Keep fields disabled just set the hidden field values
				$('fbc').value = $('fbc_ctrl').options[$('fbc_ctrl').selectedIndex].value;
				//$('fbt.value = $('fbt_ctrl.options[$('fbt_ctrl.selectedIndex].value;	
				//$('cboROIOp.value = $('cboROIOp_ctrl.options[$('cboROIOp_ctrl.selectedIndex].value ;	
				//$('txtROI.value = $('txtROI_ctrl.value;	
				//$('cboDateOperator.value = $('cboDateOperator_ctrl.options[$('cboDateOperator_ctrl.selectedIndex].value;	
			}
			break;
		case 'frmCompanyMetricsL2':	
			if($('fbc').selectedIndex <= 0) strErrors += 'Company Name.\n';		
			//if(($('fbc.selectedIndex <= 0) && ($('fbl.selectedIndex <= 0)) strErrors += 'You must select either a Company Name or a Location.\n';
			
			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmSysAdmSysConfigADM':	

			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmSysAdmMetricPoints':
			if(strErrors == '')  blnIsValid = true;
			break;
		case 'frmCompanyReportsPRSADM':
			// If between than valid date range (update or not this still applies)
			if($('cboDateOperator').selectedIndex == 7){
				// Require an ROI and a date range
				if(($('txtAppliedStart').value == '') && ($('txtAppliedStop').value == ''))  strErrors += 'You must enter a start and end date.\n';
				// Check that date range is valid
				if(dateDiff($('txtAppliedStart').value , $('txtAppliedStop').value, 'd', 0 ) <  0) strErrors += 'The end date must be equal to or greater than the start date.\n';
			}
			
			if(strErrors == '')  blnIsValid = true;
			if(blnIsValid) {
				// Enable field so that we can get them in the request object
				// 05/02/2003	mtb Keep fields disabled just set the hidden field values
				$('cboDateOperator').value = $('cboDateOperator_ctrl').options[$('cboDateOperator_ctrl').selectedIndex].value;	
			}
			break;
		case 'frmCompanyReportsOPPADM':
			// If between than valid date range (update or not this still applies)
			if($('cboDateOperator').selectedIndex == 7){
				// Require an ROI and a date range
				if(($('txtAppliedStart').value == '') && ($('txtAppliedStop').value == ''))  strErrors += 'You must enter a start and end date.\n';
				// Check that date range is valid
				if(dateDiff($('txtAppliedStart').value , $('txtAppliedStop').value, 'd', 0 ) <  0) strErrors += 'The end date must be equal to or greater than the start date.\n';
			}
			//////////////////////////////////////////////////////////////////////////////////
				// Asset Classes
			//////////////////////////////////////////////////////////////////////////////////
			
			if($Name("chkAssetRes")[$Name("chkAssetRes").length-1].checked){
				if($('txtAssetResOther').value == '')  strErrors += 'Asset Classes (Residential) other description is required if "other" is checked.\n';
			}
			//if($Name("chkAssetHtl($Name("chkAssetHtl.length-1).checked){
				// No other
			//}
			if($Name("chkAssetInd")[$Name("chkAssetInd").length-1].checked){
				if($('txtAssetIndOther').value == '')  strErrors += 'Asset Classes (Industrial) other description is required if "other" is checked.\n';
			}
			if($Name("chkAssetOff")[$Name("chkAssetOff").length-1].checked){
				if($('txtAssetOffOther').value == '')  strErrors += 'Asset Classes (Office) other description is required if "other" is checked.\n';
			}
			if($Name("chkAssetRet")[$Name("chkAssetRet").length-1].checked){
				if($('txtAssetRetOther').value == '')  strErrors += 'Asset Classes (Retail) other description is required if "other" is checked.\n';
			}
			if($('chkAssetSpecial').checked){
				if($('txtAssetSpecialOther').value == '')  strErrors += 'Asset Classes (Specialty) description is required if it is checked.\n';
			}

			if(strErrors == '')  blnIsValid = true;
			if(blnIsValid) {
				// Enable field so that we can get them in the request object
				// 05/02/2003	mtb Keep fields disabled just set the hidden field values
				$('cboDateOperator').value = $('cboDateOperator_ctrl').options[$('cboDateOperator_ctrl').selectedIndex].value;	
			}
			break;
		
	}
	
	if(blnIsValid){
		// Set submit values e.g. arrays
		//setSubmitValuesADM();
		// Submit the form
		$('IsValid').value = blnIsValid;
		$Name(strFormName)[0].submit();
	}else{
		// Show error message
		strErrors = 'Some required entries are missing or invalid:\n\n' + strErrors;
		alert(strErrors);
		blnIsValid = false;
	
	}
	return blnIsValid;

}

function checkSafeText(txtCtrl){
	var strValue = txtCtrl.value;
	strValue = strValue.replace(/\,/g," "); // Repeat within the group all commas
	strValue = strValue.replace(/\|/g," ");// Repeat within the group all pipes
	//strValue = strValue.replace(/\'/g,"''");// Repeat within the group all single quotes
	txtCtrl.value = strValue;
}
function removeCurrencyFormat(txtField){
	var dblValue = txtField.value;
	//dblValue = dblValue.replace('$','');
	
	//dblValue = dblValue.replace(',','');
	dblValue = dblValue.replace(/\$/g,""); // Repeat within the group all dollar signs
	dblValue = dblValue.replace(/\,/g,""); // Repeat within the group all commas
	txtField.value = dblValue;
}

function textLimit(field, maxlen,e) {
	// Limits the number of characters to the given size
	// This is used primarily for textareas that don't have a maxlength property
	//if (field.value.length > maxlen + 1)
	resetErrorMsg();
	
	if (field.value.length > maxlen){
		//alert('Your input has been truncated\nbecause it exceeded the ' + maxlen + ' char. limit!');
		field.value = field.value.substring(0, maxlen);
		showErrorMsg('Your input has been truncated\nbecause it exceeded the ' + maxlen + ' char. limit.',field,e);
		
	}
	
}

function validateEmail2(email, blnShowMsg,e) 
{
/*		Regular expression analysis

       ^         anchor to beginning of string
       \w+	       one or more "word" characters
      [\.-]?     zero or one period or hyphen after 1st char
     (       )   above expression wrapped in parentheses
      \w+        followed by one or more "word" characters
      @          an actual @
      \w+        one or more word characters
     \.-]?       zero or more periods or hyphens
     \w+         followed by one or more word characters
    (      )     above three expr wrapped in parentheses
     *           zero or more times the above (expression)
     \.w{2,3}    a period followed by 2 to 3 characters
     (      )    above expression wrapped in parentheses
     $           anchored to end of string             

*/
// look for one or more "word" characters to start, optionally
// followed by a period or hyphen,
// followed by one or more word characters, repeated zero
// or more times,
// followed by a '@',
// followed by at least one word character, followed by at
// least one period, followed by two or three word characters,
// repeated one or more times,
// anchored to end of string

// 02/19/2003	mtb	Modified by removing alerts and passing in just the email field
//					This will allow it to be used in conjunction with other validation routines
//					as well as allowing for variation in the name of the field to be tested.

	resetErrorMsg();

	var returncode=true;
	var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ 
	
	if(blnShowMsg == null) blnShowMsg = false;
	
	if(email.value == '') return true;
	
	if ( re.test(email.value) ){
	  returncode = true;  // it passes
	}
	else{  
  		returncode = false;  // it fails
	}
	
	if(blnShowMsg) {
		if(!(returncode)) 
			//alert('Email is invalid');
			showErrorMsg('Email is invalid',email,e);
	}
	
	return returncode;

}	// end of validate function





function validatePhone(phone, blnShowMsg, intType,e) 
{
// start with (optional) left paren, 3 digits, optional right paren,
// a period or a hyphen or a slash, 3 more digits,
// a period or hyphen or slash,
// and 4 more digits, anchored to end of string
// minimum contents : 10 digits
	
	resetErrorMsg();
	
	var re = /^\(?(\d{3})\)?[\.\-\/ ]?(\d{3})[\.\-\/ ]?(\d{4})$/
  	var returncode=true;
	var intCountryID = $('cboCountry').options[$('cboCountry').selectedIndex].value;
	// Don't valid phone if not in the US
	if(intCountryID != 268) return true;
	if(phone.value == '') return true;
	
	var validPhone = re.exec(phone.value)
	
	if(blnShowMsg == null) blnShowMsg = false;
	if(intType == null) intType = 1;
	if (validPhone) {
		//phone.value = "(" + validPhone[1] + ") " + validPhone[2] + "-" + validPhone[3]
		phone.value = validPhone[1] + "-" + validPhone[2] + "-" + validPhone[3]
	}else {
   		returncode=false;
	}
	
	if(blnShowMsg) {
		if(!(returncode)) {

			if(intType == 1)
				showErrorMsg('Phone number is invalid. For a US location, the phone number must be in the following format: ###-###-####.', phone,e);
				//alert('Phone number is invalid. You must enter both an area code and and a phone number.');
			else
				showErrorMsg('Fax number is invalid. For a US location, the fax number must be in the following format: ###-###-####.',phone, e);
				//alert('Fax number is invalid. You must enter both an area code and and a phone number.');
		}
	}
	return returncode
}
function validatePhoneUS_Old(phone, blnShowMsg, intType,e) 
{
// start with (optional) left paren, 3 digits, optional right paren,
// a period or a hyphen or a slash, 3 more digits,
// a period or hyphen or slash,
// and 4 more digits, anchored to end of string
// minimum contents : 10 digits
// 04/21/2003	mtb Like validatePhone but assumes US

	resetErrorMsg();


	var re = /^\(?(\d{3})\)?[\.\-\/ ]?(\d{3})[\.\-\/ ]?(\d{4})$/
  	var returncode=true;
	// Don't valid phone if not in the US
	//if(intCountryID != 268) return ;
	if(phone.value == '') return true;
	
	
	
	var validPhone = re.exec(phone.value)

	
	if(blnShowMsg == null) blnShowMsg = false;
	if(intType == null) intType = 1;
	if (validPhone) {
		//phone.value = "(" + validPhone[1] + ") " + validPhone[2] + "-" + validPhone[3]
		phone.value = validPhone[1] + "-" + validPhone[2] + "-" + validPhone[3]
	}else {
   		returncode=false;
	}
	
	if(blnShowMsg) {
		if(!(returncode)) {
			if(intType == 1)
				//alert('Phone number is invalid. You must enter both an area code and and a phone number.');
				showErrorMsg('Phone number is invalid. You must enter both an area code and and a phone number.',phone,e);
			else
				//alert('Fax number is invalid. You must enter both an area code and and a phone number.');
				showErrorMsg('Fax number is invalid. You must enter both an area code and and a phone number.',phone,e);
		}
	}
	return returncode
}
/*******************************************************************************
FILE: RegExpValidate.js

DESCRIPTION: This file contains a library of validation functions
  using javascript regular expressions.  Library also contains functions that re-
  format fields for display or for storage.


  VALIDATION FUNCTIONS:

  validateEmail - checks format of email address
    validateUSPhone - checks format of US phone number
    validateNumeric - checks for valid numeric value
  validateInteger - checks for valid integer value
    validateNotEmpty - checks for blank form field
  validateUSZip - checks for valid US zip code
  validateUSDate - checks for valid date in US format
  validateValue - checks a string against supplied pattern

  FORMAT FUNCTIONS:

  rightTrim - removes trailing spaces from a string
  leftTrim - removes leading spaces from a string
  trimAll - removes leading and trailing spaces from a string
  removeCurrency - removes currency formatting characters (), $
  addCurrency - inserts currency formatting characters
  removeCommas - removes comma separators from a number
  addCommas - adds comma separators to a number
  removeCharacters - removes characters from a string that match passed pattern


AUTHOR: Karen Gayda

DATE: 03/24/2000
MODIFICATION HISTORY:
03/26/2003	mtb	Adapted some functions for MOP
				added/revised user message
				added additional validation criteria
				added varying mode where applicable
				added skips for non-US where applicable
*******************************************************************************/

function validateEmail_Old( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp  = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

  //check for valid email
  return objRegExp.test(strValue);
}

function validateUSPhone_Old( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;

  //check for valid us phone with or without space between
  //area code
  return objRegExp.test(strValue);
}

function  validateNumeric( objField ,blnShowMsg, strFieldName,e ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************************/
	resetErrorMsg();

  	var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  	if(blnShowMsg == null) blnShowMsg = false;

	if(objField.value == '') return true;
	
	var returncode = objRegExp.test(objField.value);
		
	
	if(blnShowMsg) {
		
		if(!(returncode)){
			if(strFieldName == null)
				//alert('Only numeric entries are allowed in this field.');
				showErrorMsg('Only numeric entries are allowed in this field.',objField,e);
			else
				//alert('Only numeric entries are allowed in the ' + strFieldName + ' field.');
				showErrorMsg('Only numeric entries are allowed in the ' + strFieldName + ' field.',objField,e);
		}
			
	}
	
	//if(!(returncode)) objField.focus();
	
	return returncode;
  //check for numeric characters
  //return objRegExp.test(strValue);
}

function validateYear(dateField, intMinYear, intMaxYear,blnShowMsg,strFieldName,e){
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid year values.

PARAMETERS: dateField
			intMinYear
			intMaxYear
			blnShowMsg
			strFieldName
RETURNS:  True if valid, otherwise false.
AUTHOR: Michael Bane (mtb)
DATE: 03/18/2003
MODIFICATION HISTORY:
 
******************************************************************************/
	
	resetErrorMsg();


  	if(blnShowMsg == null) blnShowMsg = false;

	if(dateField.value == '') return true;
	
	var returncode = false;
	
	if(dateField.value >= intMinYear  && dateField.value <= intMaxYear) returncode = true;
	
	if(blnShowMsg) {
		
		if(!(returncode)){
			if(strFieldName == null)
				//alert('The values for this field must be between ' + intMinYear + ' and ' + intMaxYear + '.');
				showErrorMsg('The values for this field must be between ' + intMinYear + ' and ' + intMaxYear + '.',dateField,e);
			else
				//alert('The values for the ' + strFieldName + ' field must be between ' + intMinYear + ' and ' + intMaxYear + '.');
				showErrorMsg('The values for the ' + strFieldName + ' field must be between ' + intMinYear + ' and ' + intMaxYear + '.',dateField,e);
		}
			
	}
	
	//if(!(returncode)) objField.focus();
	
	return returncode;	

}

function validateNumberRange(numField,intMinVal,intMaxVal,blnShowMsg,strFieldName,e){
/******************************************************************************
DESCRIPTION: Validates that a string contains only numbers within a range.

PARAMETERS: numField
			intMinVal
			intMaxVal
			blnShowMsg
			strFieldName
RETURNS:  True if valid, otherwise false.
AUTHOR: Michael Bane (mtb)
DATE: 04/02/2003
MODIFICATION HISTORY:
 
******************************************************************************/
	resetErrorMsg();

  	if(blnShowMsg == null) blnShowMsg = false;

	if(numField.value == '') return true;
	
	var returncode = false;
	
	if(numField.value >= intMinVal  && numField.value <= intMaxVal) returncode = true;
	
	if(blnShowMsg) {
		
		if(!(returncode)){
			if(strFieldName == null)
				//alert('The values for this field must be between ' + intMinVal + ' and ' + intMaxVal + '.');
				showErrorMsg('The values for this field must be between ' + intMinVal + ' and ' + intMaxVal + '.',numField,e);
			else
				//alert('The values for the ' + strFieldName + ' field must be between ' + intMinVal + ' and ' + intMaxVal + '.');
				showErrorMsg('The values for the ' + strFieldName + ' field must be between ' + intMinVal + ' and ' + intMaxVal + '.',numField,e);
		}
			
	}
	
	return returncode;	

}

function validateInteger( strValue,e ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue,e ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function validateUSZip( zipcode , blnShowMsg,e) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

*************************************************/
	resetErrorMsg();
	
	var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

	var intCountryID = $('cboCountry').options[$('cboCountry').selectedIndex].value;
	// Don't valid phone if not in the US
	if(intCountryID != 268) return true ;
	
	if(blnShowMsg == null) blnShowMsg = false;
	
	if(zipcode.value == '') return true ;
	
	var returncode = objRegExp.test(zipcode.value);
		
	
	if(blnShowMsg) {
		
		if(!(returncode)) 
			//alert('Zipcode is invalid');
			showErrorMsg('Zipcode is invalid',zipcode,e);
			
	}
	
	return returncode;
  //check for valid US Zipcode
  //return objRegExp.test(strValue);
}
function validateURL( website , blnShowMsg,e) {
/************************************************
DESCRIPTION: Validates that a string is in URL format

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

*************************************************/
	resetErrorMsg();
	//var objRegExp  = /(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/; 
	//var objRegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	var v = new RegExp(); 
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); 
	
	if(blnShowMsg == null) blnShowMsg = false;
	
	if(website.value == '') return true ;
	
	if(blnShowMsg) alert ('website.value = ' + website.value);
	
	//var returncode = objRegExp.test(website.value);
	var returncode = v.test(website.value)
	if(blnShowMsg) {
		if(!(returncode)) 
			//alert('Website (URL) is invalid - (' + website.value +')');		
			showErrorMsg('Website (URL) is invalid - (' + website.value +')',website,e);		
				
		//else
		//	alert('Website (URL) IS valid - (' + website.value +')');			
	}	
	
	return returncode;
  
}
function validateURL2_Old(strValue,blnShowMsg){
	var returncode=true;
	

	return returncode;
}
function validateUSDate( strValue,e ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var strSeparator = strValue.substring(2,3) //find date separator
    var arrayDate = strValue.split(strSeparator); //split date into month, day, year
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
    var intDay = parseInt(arrayDate[1]);

    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }

    //check for February
    var intYear = parseInt(arrayDate[2]);
    var intMonth = parseInt(arrayDate[0]);
    if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
      return true; //Feb. had valid number of days
  }
  return false; //any other values, bad date
}

function validateValue( strValue, strMatchPattern,e ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.

PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);

 //check if string matches pattern
 return objRegExp.test(strValue);
}



function validateDate(dateField,blnShowMsg,strFieldName,e){
/*
This file retrieved from the JS-Examples archives
http://www.js-examples.com
1000s of free ready to use scripts, tutorials, forums.
Author: Alex B. - 0
MODIFICATION HISTORY:
04/10/2003	mtb	Adapted for MOP
*/
/*
    var _value = dateField.value;
    var _test = Date.parse(_value)

    if (isNaN(_test)) {
        _form.myDate.value = "";
        alert("Date is invalid.");
        _form.myDate.focus();
    }
    else {
        nDate = new Date(_test);
        _form.myDate.value = nDate.toUTCString();
    }
}
*/
	resetErrorMsg();


  	if(blnShowMsg == null) blnShowMsg = false;

	if(dateField.value == '') return true;
	
	var _value = dateField.value;
    var _test = Date.parse(_value)
	
	//if(!(isNaN(_test))) returncode = true;

	var objRegExp  = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

	
	var returncode = objRegExp.test(dateField.value);

	
	if(blnShowMsg) {
		
		if(!(returncode)){
			if(strFieldName == null)
				//alert('This field must be a valid date.');
				showErrorMsg('This field must be a valid date.',dateField,e);
			else
				//alert(strFieldName + ' field must be a valid date.');
				showErrorMsg(strFieldName + ' field must be a valid date.',dateField,e);
		}
			
	}
	
	//if(!(returncode)) objField.focus();
	
	return returncode;	

}

function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.

PARAMETERS:
   strValue - String to be trimmed.

RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;

      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}

function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.

PARAMETERS:
   strValue - String to be trimmed

RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;

      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';

  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS:
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid
  numeric value in the rounded to 2 decimal
  places.  If not, returns original value.
*************************************************/
  var objRegExp = /-?[0-9]+\.[0-9]{2}$/;

    if( objRegExp.test(strValue)) {
      objRegExp.compile('^-');
      strValue = addCommas(strValue);
      if (objRegExp.test(strValue)){
        strValue = '(' + strValue.replace(objRegExp,'') + ')';
      }
      return '$' + strValue;
    }
    else
      return strValue;
}

function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS:
  strValue - Source string from which commas will
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally

  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS:
  strValue - source string containing commas.

RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is
  returned.

REMARKS: Used with integers or numbers with
  2 or less decimal places.
*************************************************/
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match,
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS:
  strValue - source string containing number.

RETURNS: String modified with characters
  matching search pattern removed

USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd',
                                '\s*')
*************************************************/
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );

 //replace passed pattern matches with blanks
  return strValue.replace(objRegExp,'');
}

function resetErrorMsg(){
/************************************************
DESCRIPTION: Clears and hides the error msg DIV.

PARAMETERS:
  none

RETURNS: Nothing

REMARKS: 

*************************************************/
	//alert('(resetErrorMsg) starting...');
	var oMsgs = $('ErrorMsgs');
	var oMsgsFloat = $('ErrorFloat');
	if(!(oMsgs == null)) oMsgs.style.visibility = "hidden";
	if(!(oMsgsFloat == null)) oMsgsFloat.style.visibility = "hidden";
	//{
		//alert('Found ErrorMsgs span(resetErrorMsg)...');
		
	//}else{
	//	alert('ErrorMsgs was not found (resetErrorMsg)...');
	//}
	
	//alert('(resetErrorMsg) complete...');	
}
function showErrorMsg(sValue,oSrc,e,bNoFloat){
/************************************************
DESCRIPTION: Shows the error msg DIV.

PARAMETERS:
 	sValue - The text for the msg.
	oSrc - In most cases the event property to get the mouse coordinates.

RETURNS: Nothing

REMARKS: 

*************************************************/
	// As an easier alternative to massive conditional block when not on the application page
	// using the if the oMsgs is null then show alert rather than resetting all the alerts in the validators.
	if(sValue == null || sValue == "") return true;
	if(bNoFloat == null) bNoFloat = false;
	// Adding a "hidden" textbox for the capital P to allow for a call to focus
	// at the error message
	//var sIntro = 'Please correct your application:<BR><BR>'
	var sIntro = 'Please correct you<input type="text" name="txtErrorTop" ID="txtErrorTop" style="background-color:#DEE7EF; border:0; font-weight:bold; font-size:8pt; vertical-align:middle; color:Red;width:10px; direction:ltr;" value="r"> application:<BR><BR>'
	if(sValue.indexOf(sIntro) < 0) sValue = sIntro + sValue;
	
	var sMsg = sValue;
	var sMsgHTML = sMsg.replace(/\n/gi,"<BR>");
	
	if((!(oSrc == null)) && (!(bNoFloat))){
		var oMsgs = $('ErrorFloat');
		if(document.all){
			oMsgs.style.pixelTop = (e.y+10+document.body.scrollTop) ; // no px append here or value = 0 (oSrc.y+document.body.scrollTop); 
			oMsgs.style.pixelLeft = (e.x+85+document.body.scrollLeft) ; // no px append here or value = 0 (oSrc.x+15+document.body.scrollLeft); 
		}else{
			var yfind = findPosY(oSrc);
			var xfind = findPosX(oSrc);
			var topFind = (yfind+10+document.body.scrollTop) ;
			var leftFind = (xfind+85+document.body.scrollLeft);
			oMsgs.style.top = topFind + 'px';
			oMsgs.style.left = leftFind + 'px';
		}
		/*alert('oSrc.y (e) = ' + e.y + '\n' +
			'oSrc.x (e)= ' + e.x + '\n' +
			'oSrc.y (using find) = ' + yfind + '\n' +
			'oSrc.x (using find) = ' + xfind + '\n' +
			'oMsgs.style.pixelTop = ' + oMsgs.style.pixelTop + '\n' +
			'oMsgs.style.pixelLeft = ' + oMsgs.style.pixelLeft + '\n'+
			'oMsgs.style.pixelTop (using find)= ' + topFind + '\n' +
			'oMsgs.style.pixelLeft(using find) = ' + leftFind + '\n'+
			'sMsgHTML = ' + sMsgHTML + '\n' );*/
				
		oMsgs.style.position = 'absolute';		
		oMsgs.style.visibility = "visible";
		oMsgs.innerHTML ='<table border=1 width=200px borderColor="#000000" bgColor="#FCDADA" cellspacing=0 cellpadding=0><tr><td>' + sMsgHTML + '</td></tr></table>';
		//alert("Attempting to focus on error top...(a)");
		var errorTop = document.getElementById('txtErrorTop')
		//For some reason it switches back to its previous focus control
		// So calling focus twice fixes it.
		errorTop.focus();errorTop.focus();
	}else{
		if(!(bNoFloat)) alert('The oSrc element was null...(Text: ' + sValue + ')');	
		var oMsgs = $('ErrorMsgs');
		if(!(oMsgs == null)) {
			//alert('Setting oMsg properties...');
			if(document.all){
				oMsgs.style.top = $('brand-logo').offsetTop + 'px';			
				oMsgs.style.left = $('GeneralInfo').offsetLeft + $('content-all').offsetWidth + 50  + 'px';
			}else{
				oMsgs.style.top = 43 + 'px';
				oMsgs.style.left = 1186 + 'px';
			}
			oMsgs.style.width = 200 + 'px';
			/*alert('oMsgs settings: ' + '\n' +
				' left = ' + oMsgs.style.left + '\n' +
				' top = ' + oMsgs.style.top + '\n' +
				' width = ' + oMsgs.style.width + '\n' +
				' height = ' + oMsgs.style.height + '\n' +
				' clientleft = ' + oMsgs.clientLeft + '\n' +
				' clienttop = ' + oMsgs.clientTop + '\n' +
				' clientwidth = ' + oMsgs.clientWidth + '\n' +
				' clientheight = ' + oMsgs.clientHeight + '\n' +
				' offsetleft = ' + oMsgs.offsetLeft + '\n' +
				' offsettop = ' + oMsgs.offsetTop + '\n' +
				' offsetwidth = ' + oMsgs.offsetWidth + '\n' +
				' offsetheight = ' + oMsgs.offsetHeight 
			)*/
			oMsgs.style.visibility = "";
			oMsgs.innerHTML = sMsgHTML;
			//alert("Attempting to focus on error top...(b)");
			//alert("sMsgHTML=" + sMsgHTML);
			var errorTop = document.getElementById('txtErrorTop')
			//For some reason it switches back to its previous focus control
			// So calling focus twice fixes it.
			errorTop.focus(); errorTop.focus(); 
		}else{
			alert(sValue);
		}
	}
	
	return true;
}

//-->
