/* 
Data validation utility functions.

Contents:
validation functions(thisform)
isNumber()
confirmChoice(message)
trimAll(string). See also the three other trim functions here.
chkForm() checks ebulletin logic.
	12sep09, rak. Removed, since not used now. See backups to retrieve this if needed.
stopRKey() to prevent use of Enter.
checkEmail() to check for an email address when a check box is clicked.
three more trim functions acquired 31oct09 from http://www.somacon.com/p355.php
upperCase(this.id)
*/

function validate_form(thisform){
	/* 
	Called by form onSubmit event
	*/
	var bData = true;
	var sNum = '0123456789'
	
	with (thisform){
		/*
		// write a list of info about the elements -- for testing
		msg = "";
		msg = msg + 'Validate' + '\n';
		msg = msg + 'length of this form ' + length + '\n\n';
		for (var i=0;i<length;i++){
			with(elements[i]){
				//document.write(value);
				msg = msg + name + ' | ';
				msg = msg + type + ' | ';
				if (type=='checkbox'){msg = msg + checked + '\n';}
				else {msg = msg + value + '\n';}
			}
		}
		alert(msg);
		// end of test list
		*/
		//check if required
		for (var i=0;i<length;i++){
			with (elements[i]){
				if (id.search(/_require_/i) >= 0){
					alerttxt = "A required field is empty."
					if (validate_required(thisform.elements[i], alerttxt) == false){
						document.getElementById(id).focus();
						bData=false;
						break;
					}
				}
			}
		}
		if (bData == true){
			// validate dates
			for (var i=0;i<length;i++){
				with (elements[i]){
					if (id.search(/_date_/i) >= 0){
						if (elements[i].value==null||elements[i].value==""){
							//allow a blank date
						}
						else{
							if (validateDate(thisform.elements[i]) == false){
								document.getElementById(id).focus();
								bData=false;
								break;						
							}					
						}
					}
				}
			}
		}
		if (bData == true){
			// validate times
			for (var i=0;i<length;i++){
				with (elements[i]){
					if (id.search(/_time_/i) >= 0){
						if (elements[i].value==null||elements[i].value==""){
							//allow a blank time
						}
						else{
							if (validateTime(thisform.elements[i]) == false){
								document.getElementById(id).focus();
								bData=false;
								break;						
							}					
						}
					}
				}
			}
		}
		if (bData == true){
			//validate phone
			for (var i=0;i<length;i++){
				with (elements[i]){
					if (id.search(/_phone_/i) >= 0){
						if (elements[i].value==null||elements[i].value==""){
							//allow a blank field
						}
						else{
							if (validatePhone(elements[i].value) == false){
								document.getElementById(id).focus();
								bData=false;
								break;						
							}					
						}
					}
				}
			}
		}
		if (bData == true){
			//validate email
			for (var i=0;i<length;i++){
				with (elements[i]){
					if (id.search(/_email_/i) >= 0){
						if (elements[i].value==null||elements[i].value==""){
							//allow a blank field
						}
						else{
							alerttxt = "Please enter a valid Email address."
							if (validateEmail(thisform.elements[i], alerttxt) == false){
								document.getElementById(id).focus();
								bData=false;
								break;						
							}					
						}
					}
				}
			}
		}
		if (bData == true){
			// validate zip
			for (var i=0;i<length;i++){
				with (elements[i]){
					if (id.search(/_zip_/i) >= 0){
						if (elements[i].value==null||elements[i].value==""){
							//allow a blank field
						}
						else{
							if (validZip(elements[i].value) == false){
								document.getElementById(id).focus();
								bData=false;
								break;
							}
						}
					}
				}
			}
		}
		if (bData == true){
			// validate for positive number
			for (var i=0;i<length;i++){
				with (elements[i]){
					if (id.search(/_posnum_/i) >= 0){
						if (elements[i].value==null||elements[i].value==""){
							//allow a blank field
						}
						else{
							if (isNumber(elements[i].value) == false){
								document.getElementById(id).focus();
								bData=false;
								break;
							}
						}
					}
				}
			}
		}
	}

	if (bData == true){
		//alert('bData is true');
		return true;
	}
	else{
		//alert('bData is false');
		return false;
	}
}

function validate_required(field,alerttxt){
	//check for null or empty data
	with (field){
		//alert('in required func');
		if (value==null||value==""){alert(alerttxt); return false;}
		else {return true}
	}
}

function validateDate(fld){
	// adapted from http://www.expertsrt.com/scripts/Rod/validate_date.php
	var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	errMsg = ''
	errMsg = errMsg + 'Date Error\n\n'
	errMsg = errMsg + 'Please enter valid date as month, day, and four digit year.\n'
	errMsg = errMsg + 'You may use a slash, hyphen or period to separate the values.\n'
	errMsg = errMsg + 'The date must be a real date. 2-30-2000 would not be accepted.\n'
	errMsg = errMsg + 'Format examples: m/d/yyyy, mm/dd/yyyy.';

	if (fld.value == null || fld.value == "") {
		return true;
	}
	else if (fld.value.match(RegExPattern)) {
		//alert('Date is OK'); 
		return true;
	} 
	else {
        	alert(errMsg);
		//fld.focus(); //let the calling function handle the focus
		return false;
	}
}

function validateTime(fld){
	// adapted from http://www.the-art-of-web.com/javascript/validate-date/
	var RegExPattern = /^\d{1,2}:\d{2}([ap]m)?$/; 
	errMsg = ''
	errMsg = errMsg + 'Time Error\n\n'
	errMsg = errMsg + 'Format examples: 07:30, 7:30am, 7:30pm, 14:00.';

	if (fld.value == null || fld.value == "") {
		return true;
	}
	else if (fld.value.match(RegExPattern)) {
		//alert('Time is OK'); 
		return true;
	} 
	else {
        	alert(errMsg);
		//fld.focus(); //let the calling function handle the focus
		return false;
	}
}

function validatePhone(s) {
	// Check for correct phone number
	// for 000-000-0000
	rePhoneNumber = new RegExp(/^\d{3}\-\d{3}\-\d{4}$/);

	if (!rePhoneNumber.test(s)) {
        	//alert("Phone Number Must Be Entered As: (555) 555-1234");
        	alert("Phone Number Must Be Entered As: 555-555-1234");
          	return false;
	}
	return true;
}

function validateEmail(field,alerttxt){
	//copied from w3schools.com
	with (field){
		apos=value.indexOf("@");
		dotpos=value.lastIndexOf(".");
		//alert('In validate_email ' + apos + '\n' + dotpos)
		if (apos<1||dotpos-apos<2) {alert(alerttxt);return false;}
		else {return true;}
	}
}

function validZip(zip){
	/* Original:  Brian Swalwell. 20jul08, rak. Debugged this a bit.
	This script and many more are available free online at
	The JavaScript Source!! http://javascript.internet.com
	*/
	//alert("in validZip func: " + zip);
	var valid = "0123456789-";
	var hyphencount = 0;
	if (zip.length != 5 && zip.length != 10){
		alert("Please enter your 5 digit or 5 digit+4 zip code.");
		return false;
	}
	for (var i=0; i < zip.length; i++){
		temp = "" + zip.substring(i, i+1);
		if (temp == "-") {hyphencount++;}
		//alert(temp);
		if (valid.indexOf(temp) == "-1"){
			alert("Invalid characters are in your zip code. Please try again.");
			return false;
		}
	}
	if (hyphencount > 1 || (zip.length==10 && zip.charAt(5) != "-")){
		str = "Use the hyphen character with a properly"
		str = str + '\n' + "formatted 5 digit+4 zip code, such as '12345-6789'."
		str = str + '\n' + " Please try again."
		alert(str);
		return false;
	}
	return true;
}

function isNumber(val){
	// is val a number and if so, is it > 1
	alerttxt = 'Enter a positive number.'

	if (isNaN(val) == true) {
		alert(alerttxt);
		return false;
	}
	else if (val < 0) {
		alert('Use a positive value here.')
		return false;
	}
	return true;
}

function confirm_choice(msg){
	/*
	Include the symbol, \n, for new lines in your message.
	*/
	bChoice = confirm(msg);
	if (bChoice==true) {
		msg = 'Are you sure?\n\n' + msg
		bChoice = confirm(msg)
	}
	return bChoice;
}

function trimAll(sString){
	//trim a string of leading and trailing blanks
	//from Afzal Aziz, India, collected from web on 29jul09.
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}

	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function stopRKey(evt){
	/* 
	Purpose: Stop use of the enter key.
	Use: 
		1. to affect the whole file: document.onkeypress = stopRKey;. I haven't used this yet.
		2. onKeyPress="return stopRKey(event)". When on the form, works in IE, not in FF. 
			When on the body, works in both. Yeah!

	10jul08, rak. Nabbed this from the web. Works in IE and FF that I have.
	14sep09, rak. This is working in IE and FireFox.
	*/

	//alert('in stopRkey' + evt.keyCode);
	//return false;

	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}

function checkEmail(emailAddr, msg){
	/*
	checks that an email address is present for this member
	allows change to the check box if address is present
	Called by check box onclick events like this:
	onClick='return checkEmail(&quot;" & sEmail & "&quot;, &quot;" & msg & "&quot;)'
	*/
	//alert('in checkEmail')
	var bAddr = true
	if (emailAddr == ''){
		alert(msg)
		bAddr = false
	}
	return bAddr
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function upperCase(id) {
	//alert('in upperCase')
	document.getElementById(id).value = document.getElementById(id).value.toUpperCase()
}
