// Form validation utility functions

var date_punct = /[\.\-/]/;

// Trim whitespace from beginning and end of string
// This should be in a more general util file, but unfortunately Javascript doesn't allow us to include a javascript file
// directly.
function trim(str) {

	str = str.replace(/^\s+/, ""); 
	str = str.replace(/\s+$/, "");
	return str;
}

// Returns true iff an option has been selected in a set of radio buttons or checkboxes.
function optionSelected(formObj, elementName) {
	for (i = 0; i < formObj[elementName].length; i++) {
		// return i + 1, not i, since i == 0 if the first element is selected
		if (formObj[elementName][i].checked) return (i + 1);
	}
	return false;
}

// Returns true iff string s contains only whitespace (spaces, tabs, and newlines).
function allblanks (s) {
	for (var i=0; i < s.length; i++) {
		var c = s.charAt(i);
	    if ((c != ' ') && (c != '\n') && (c != '\t')) {
	      return false;
	    }
	}
	return true;
}


// Returns true iff string s is empty or contains only whitespace.	
function isblank (s) {
	return (s == null || s.length == 0 || allblanks(s));
}

function is_numeric(n) {
	return !isNaN(n);
}


function isValidState(state) {
	var state_format = /^[A-Za-z][A-Za-z]$/;
	//var z = state.format.test(state); alert("state="+state+", z="+z);
	return state_format.test(state);
	//return true;
}

// Returns true iff string email is a valid email address.
// The email_format regexp is adapted from http://javascript.internet.com/forms/email-validation---basic.html
// The list of valid TLDs is from http://javascript.internet.com/forms/email-address-validation.html and
// http://www.icann.org/tlds/. The former also provides a more detailed email validation routine.
function isValidEmail(email) {

	var email_format = /^\w+([\.-]\w+)*@\w+([\.-]\w+)*\.([A-Za-z]{2}|com|edu|gov|int|mil|net|org|aero|arpa|biz|coop|info|name|pro|museum)$/;

	email = trim(email);

	// return email.search(email_format) + 1;
	return email_format.test(email);

}

// Returns true iff string zipcode is a valid zipcode.
function isValidZipcode(zipcode) {

	var zipcode_format = /^\d{5}(-\d{4})?$/;
	
	zipcode = trim(zipcode);
	
	//return zipcode.search(zipcode_format) + 1;
	return zipcode_format.test(zipcode);

}

// Returns true iff string number is a 10-digit telephone number. 
// This is a simplified validation in which separators () - . / and space are simply stripped out and ignored, and the 
// remaining string validates iff it consists of 10 digits.
// Therefore, it doesn't check for consistency of separators, although certain types of mixing are allowed anyway, e.g., 607/255-3456. 
// Doesn't work for international phone numbers
function isValidPhoneNumber(number) {

	var phone_number = /^\d{10}$/;  // a 10-digit string
	var short_phone_number = /^\d{7}$/;  // a 7-digit string

	number = trim(number);
	// strip out all phone number punctuation
	number = number.replace(/[\(\)\/\.\- ]/g, ""); 

	//return number.search(phone_number) + 1;
	return phone_number.test(number) || short_phone_number.test(number);
	
}

// Returns true iff string year is a valid year. Used in date processing, so only accepts years 1900-2099.
function isYear(year) {

	var year_format = /^(19|20)\d{2}$/;
	year = trim(year);
	//return year.search(year_format) + 1;
	return year_format.test(year);

}

// Returns true iff date is a date in mm-yyyy format
function isDate_mmyyyy(date) {

	date = trim(date);
	var dateArray = date.split(date_punct);  // strip out date punctuation

	if (dateArray.length != 2) { 
		return false; 
	}
	// Works in Perl
	// var (month, year) = dateArray; 
	var month = dateArray[0];
	var year = dateArray[1];
	
	if (month > 12 || month < 1) { 
		return false;
	}
	return isYear(year);
}

// Returns true iff month and day are valid month and day values.
// Break this out into a separate function in case we want to validate mmdd, ddmmyyyy formats, etc.
function isMonthDay(month, day) {

	if (month > 12 || month < 1) { 
		return false;
	}
	if (day > 31 || day < 1) {
		return false;
	}	
	if (day == 31) {
		if (month == 4 || month == 6 || month == 9 || month == 11) {
			return false;
		}
	}
	if (month == 2) {
		// we're not dealing with leap year vs. non-leap year
		if (day > 29) {
			return false;
		}
	}
	return true;	
}


// Returns true iff date is a date in mm-dd-yyyy format
function isDate_mmddyyyy(date) {

	// Tried to define date_punct as a string, then use the string to define date_format, 
	// but can't get the escape sequences right
	// var date_punct = "[\.\-/]";
	// var date_format = new RegExp("^\d{2}(" + date_punct + ")\d{2}\1\d{4}$");
	var date_format = /^\d{2}([\.\-/])\d{2}\1\d{4}$/;
	
	if (!date_format.test(date)) {
		return false;
	}
	
	var dateArray = date.split(date_punct);  // strip out date punctuation	
	
	// The regexp test above already ensures this
	/* if (dateArray.length != 3) { 
		return false; 
	} */
	
	// Works in Perl: var (month, day, year) = dateArray; 
	var month = dateArray[0];
	var day = dateArray[1];
	var year = dateArray[2];
	if (!isMonthDay(month, day)) {
		return false;
	}
	return isYear(year);
}

// Returns true iff num is an integer
function isInt(num) {

	return num == parseInt(num, 10);
	
}

// Returns true iff num is a float
function isFloat(num) {
	
	return num == parseFloat(num, 10);
	
}

function removeerror(e) {
	//var i = e.className.indexOf("error");
	//var i = e.className.search(/error$/);
	//if (i >= 0) e.className = e.className.substring(0, i);
	b4=e.className
	e.className = e.className.replace(/\berror\b/,"");
	//alert(b4+" "+e.className);
}

function addErrorToNearestLabel(e) {
//alert("addtonearest"+e.name);
	var n = e;
	var l = 0;
	var l1 = n.getElementsByTagName('label');
	var l2 = n.getElementsByTagName('h6');
	while ((l1.length == 0) && (l2.length == 0)) {
		n = n.parentNode;
		l1 = n.getElementsByTagName('label');
		l2 = n.getElementsByTagName('h6');
	}
	if (l1.length) {l = l1.item(0);} else {l = l2.item(0);}
	l.className += " error";
}

function removeErrorFromNearestLabel(e) {

	var n = e;
	var l = 0;
	var l1 = n.getElementsByTagName('label');
	var l2 = n.getElementsByTagName('h6');
	while ((l1.length == 0) && (l2.length == 0)) {
		n = n.parentNode;
		l1 = n.getElementsByTagName('label');
		l2 = n.getElementsByTagName('h6');
	}
	if (l1.length) l = l1.item(0); else l = l2.item(0);
	removeerror(l);
}

