/** valCustomForm(f)
 * Field validation based on form elements in the 'valflds' array, which is set on the page containing the 
 * form (so that it can easily change from form to form. Format: "fldname(0) | Display Name(1) | maxlength(2) (opt)"
 * f = obj; form object being validated
 * Returns boolean true or false 
 **/
function valCustomForm(f) {
	//first, disable the submit button to keep user from submitting twice
	//f.elements['submit'].disabled = true;
	toggleSubmitButton(f,'OFF');
	
	//execute validation routines on all fields in array
	for (i=0; i<valflds.length; i++) {
		/** Separate piped values **/
		fld = valflds[i].split("|");
		fldname		= fld[0];
		fldLabel	= fld[1];
		fldMaxLen	= fld[2];
	
		//determine the element type
		if (!f.elements[fldname][0]) {
			//anything but radios and checkboxes
			elType = f.elements[fldname].type;
		} else {
			//radio and checkbox sets
			elType = f.elements[fldname][0].type;
		}
		
		/** check element to ensure a value has been entered **/
		hasValue = false;
		//any element other than radio or checkbox
		if (elType!=='radio' && elType!=='checkbox') {
			if (f.elements[fldname].value!=='') {
				hasValue = true;
			}
		}
		//checkbox
		if (elType=='checkbox') {
			if (f.elements[fldname].length>1) {
				for (ii=0; ii<f.elements[fldname].length; ii++) {
					hasValue = (f.elements[fldname][ii].checked) ? true : false;
					if (hasValue) { break; }
				}
			} else {
				hasValue = (f.elements[fldname].checked) ? true : false;
			}
		}
		//radio group
		if (elType=='radio') {
			for (ii=0; ii < f.elements[fldname].length; ii++) {
				if (f.elements[fldname][ii].checked==true) {
					hasValue = true;
					break;
				}
			}
		}
			
		/** CHECK FOR EMPTY REQUIRED FIELDS **/
		if (!hasValue) {
			//Reenable Submit button
			//f.elements['submit'].disabled = false;
			toggleSubmitButton(f,'ON');
			
			//Show Alert Message
			if (fldname=='termsagree') {
				//custom field alerts
				alert("You may not continue until you agree to the Terms and Conditions.");
			} else {
				//general field alert
				alert("A value is required for \'" + fldLabel + "\'.");
			}
			//Place focus on empty element; if an array or group for the 
			//element, put focus on the first element in the group.
			if (!f.elements[fldname][0]) {
				f.elements[fldname].focus();
			} else {
				f.elements[fldname][0].focus();
			}
			return false;
		}
		
		/** CUSTOM FIELD DATA CHECKS **/
		//validate Contact E-mail Address fields
		if (fldname.indexOf('email') > -1) {
			if (!isEmail(f.elements[fldname].value)) {
				alert("The e-mail address you entered in \'" + fldLabel + "\' appears to be invalid. Please check your entry.");
				f.elements[fldname].focus();
				//f.elements['submit'].disabled = false;
				toggleSubmitButton(f);
				return false;
			}
		}
		
		/** FIELD LENGTH CHECKS **/
		if (fldMaxLen.length>0) {
			if (f.elements[fldname]) {
				fldMaxLen = parseInt(fldMaxLen);
				fldOver = f.elements[fldname].value.length - fldMaxLen;
				if ( fldOver > 0 ) {
					alert(fldLabel + " must not exceed " + fldMaxLen + " characters. Please shorten it by " + fldOver + " characters.");
					f.elements[fldname].focus();
					//f.elements['submit'].disabled = false;
					toggleSubmitButton(f);
					return false;
				}
			}
		}
	} //flds loop
	
	return true;
}

/** toggleSubmitButton(f)
 * Checks to see that submit button exists before attempting to enabled/disable it.
 * f = obj; form object
 * state = string; 'ON' or 'OFF'
 * returns nothing
 **/
function toggleSubmitButton(f,state) {
	if (f.elements) {
		for (var e=0; e<f.elements.length; e++) {
			if (f.elements[e].name.toLowerCase()=='submit') { 
				f.elements[e].disabled = (state == 'OFF') ? true : false;
				break;
			}
		}
	}
}

/** isEmail()
Validates e-mail addresses
val = string; e-mail address
returns true or false */
function isEmail(val) {
	if (val.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
		return true;
	}
	return false;
}

/** isValidTime()
 * Check input string for valid time format, as defined in function comment at start of processing.
 * timeStr = string
 * returns boolean
 **/
function isValidTime(objfld) {
	// Checks if time is in HH:MM AM/PM format.
	if (objfld.value=='') { return false; }
	timeStr = objfld.value;
	
	hh   = -1;
	mm   = -1;
	ampm = '';
	
	if (timeStr.toUpperCase().indexOf('AM')!==-1) { ampm = 'AM'; }
	if (timeStr.toUpperCase().indexOf('PM')!==-1) { ampm = 'PM'; }
	
	iColon = 0;
	for (i=0; i<timeStr.length; i++) {
		ch = timeStr.charAt(i);
		if (ch==':') { iColon++; }
	}
	
	if (iColon==1) {
		hh = timeStr.substr(0,2);
		hh = hh.replace(':', '');
		hh = hh.replace(' ', '');
		hh = isNaN(hh) ? -1 : parseInt(hh);
		
		mm = timeStr.substr((timeStr.indexOf(':')+1),2);
		mm = mm.replace(' ','');
		mm = (isNaN(mm)) ? -1 : mm;
		if (mm.length<=1 && mm!==-1) { mm = '0'+(mm.toString()); }
	}
	//alert('hh = '+hh+' | mm = '+mm);
	
	//alerts for failed validation
	if ((hh.length>2 || hh<0 || hh>12) || (mm.length>2 || parseInt(mm)<0 || parseInt(mm)>59)) {
		alert(
			"Time must be entered in 'HH:MM am/pm' format, and must be a valid standard 12-hour time.\r\n"
			+"Please check your entry."
			);
		objfld.focus();
		return false;
	}
	if (ampm=='') {
		alert("You must include 'AM' or 'PM' in you time. Please check your entry.");
		objfld.focus();
		return false;
	}
	
	//reassemble timeStr and update the field's value
	if (hh.length==1) { hh = '0'+hh.toString(); }
	if (mm.length==1) { mm = '0'+mm.toString(); }
	
	objfld.value = hh+':'+mm+' '+ampm
	return true;
}

/** valPasswordFormat()
 * Checks to see that all password fields have a value, and that the new password fields match. All 
 * other checks are performed during form processing via the valPassword() vbscript function. Requires 
 * specifically named objects to be present in the form to operate correctly.
 * no parameters
 * returns boolean
 **/
function valPasswordFormat() {
	var f = document.updatePassword;
	var oOldPass = f.elements['oldpass'];
	var oNewPass = f.elements['newpass'];
	var oNewConfirm = f.elements['newpass_confirm'];
	//if (oOldPass.value!=='' || oNewPass.value!=='' || oNewConfirm.value!=='') {
		//check for existance of values
		if (oOldPass.value=='') { 
			alert('If you would like to update your password, the "Old Password" field needs a value.');
			oOldPass.focus();
			return false;
		}
		if (oNewPass.value=='') { 
			alert('If you would like to update your password, the "New Password" field needs a value.');
			oNewPass.focus();
			return false;
		}
		if (oNewConfirm.value=='') { 
			alert('If you would like to update your password, the "Confirm New Password" field needs a value.');
			oNewConfirm.focus();
			return false;
		}
		
		//compare new pass fields
		if (oNewPass.value!==oNewConfirm.value) {
			alert('The value you entered in the "New Password" and "Confirm New Password" fields do not match. Please check your entry and try again.');
			oNewPass.focus();
			return false;
		}
	//}
	return true;
}

/** forceJavascript()
 * replaces the DIV container's default text with the submissions buttons *ONLY* if the user 
 * has javascript enabled. Runs on window load, and requires specifically named objects 
 * to be present on the page.
 * no parameters
 * returns nothing
 **/
function forceJavascript() {
	//hide alert div if js is enabled
	if (document.getElementById("jsAlert")) {
		elAlert = document.getElementById("jsAlert");
		elAlert.innerHTML = '';
		elAlert.style.visibility = 'hidden';
		elAlert.style.display = 'none';
	}
	if (document.getElementById("jsAlert2")) {
		elAlert = document.getElementById("jsAlert2");
		elAlert.innerHTML = '';
		elAlert.style.visibility = 'hidden';
		elAlert.style.display = 'none';
	}
	
	//write profile elements
	if (document.getElementById("formbuttons")) {
		elButtons = document.getElementById("formbuttons");
		elButtons.style.visibility = 'visible';
		elButtons.style.display = 'block';
		/* Disabled...
		elButtons.innerHTML = ''
			+ '<input type="submit" name="submit" value="UPDATE MY PROFILE" class="globalSubmit">'
			+ '<input type="button" name="cancel" value="CANCEL" class="globalSubmit" onclick="window.location.href=\'profile.asp\';">';
		*/
	}
}


