// function for validating form entries.
// Use: call validate(<your_form_here>)
//    Function will validate every element in the form.  If any problems are
//       detected, an alert indicating the problem will be displayed.
//    Returns: true if validation suceeds, false otherwise.
//    Elements should implement the following properities as needed:
//			optional - an entry is not required in this field.)
//			required - an entry is required (only necessary if !expectEverything)
//			(if any of the next four properties are present, the field is treated as numeric)
//			numeric  - this entry is a numeric-only field
//			integer  - this entry is an positive integer-only field
//			min      - min value for this numeric entry
//			max      - max value for this numeric entry
//			email    - this entry is an email address
//			maxlength- max number of characters for this entry
//			description - A readable name describing the field
//			date     - this entry is a date in the format m/d/y
//			category - a list of possible strings that the value can have (like timezones)
//                     separated by commas (if you use this you also should use categoryName)
//			categoryName - the name of the category for the alert message
//			error	 - we know there is an error, just display the string


function isBlank(s)
{
	for (var i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t'))
			return false;
	}
	return true;
}

// old version of validate
function validate(theForm) {
	return validate(theForm, true);
}

function showAlert (e,message)
{
	var msg = message;
	var emptyFields = "";
	var nonNumericFields = "";
	var emailFields = "";
	var maxLengthFields = "";
	var dateFields = "";
	var categoryFields = "";
	var errorFields = "";
	var isalutation = 0;
	var irelation = 0;
	var expectEverything = false;
	
	var validationRequired =
		(expectEverything && !e.optional) ||
		(e.required && e.required == true) ||
		((e.type == "text" || e.type == "textarea" || e.type == "password") && !isBlank(e.value));

	var description = (e.description ? e.description : e.name);

	// expectEverything - all fields should be filled in unless specified optional
	// otherwise all fields optional unless specified required
	if ((e.type == "text" || e.type == "textarea" || e.type == "password") &&
					((expectEverything && !e.optional) || e.required)) {
		if (isBlank(e.value))
			emptyFields += "\n        " + description;
	}


	if ((e.type == "select-one") && ((expectEverything && !e.optional) || e.required)) {
					if (e.value == "")
					emptyFields += "\n        " + description;
	}
	
	if ((e.ftype == "CHECKBOX" || e.ftype == "RADIO") && ((expectEverything && !e.optional) || e.required)) {
		var cnt = e.flength;
		var found = false;
	
		// determine if any checkboxes are checked
		for(var j = 0; j < cnt-1; j++)
		{
			if (e[j].checked)								
				found = true;
		}
	
		// if no boxes were checked add to the emptyfields
		if (!found)
			emptyFields += "\n        " + description;
	}

	if (validationRequired &&
		(e.numeric || e.integer || (e.min != null) || (e.max != null))) {
		var v = parseFloat(e.value);
		if (isNaN(v) || (e.integer && !isIntegerString(e.value)) ||
			((e.min != null) && (v < e.min)) ||
			((e.max != null) && (v > e.max))) {
			nonNumericFields += "- The field " + description + " must be " +
						(e.integer ? "an integer" : "a number");
			if (e.min != null)
				nonNumericFields += " that is greater than or equal to " + e.min;
			if (e.max != null && e.min != null)
				nonNumericFields += " and less than or equal to " + e.max;
			else if (e.max != null)
				nonNumericFields += " that is less than or equal to " + e.max;
			nonNumericFields += "\n";
		}
	}
	if (validationRequired &&
		(e.email && !isValidEmail(e.value))) {
		emailFields += "- The field " + description + " must be a valid e-mail address\n";
	}
	if (validationRequired &&
		(e.maxlength && e.maxlength != null && e.value)) {
		if (e.value.length > e.maxlength) {
			maxLengthFields += "- The field " + description + " can be at most " + e.maxlength +
								" characters long\n";
		}
	}
	if (validationRequired &&
		(e.date && !isValidDate(e.value))) {
		dateFields += "- The field " + description + " must be a valid date\n";
	}
	if (validationRequired &&
		(e.category && !isStringCategory(e.value, e.category))) {
		categoryFields += "- The field " + description + " does not belong to the " +
							" category " + (e.categoryName != null ? e.categoryName :
																		e.category) + "\n";
	}
	if (e.error) {
		errorFields += "- " + e.error + "\n";
	}

	msg += emptyFields;
	msg += nonNumericFields;
	msg += emailFields;
	msg += maxLengthFields;
	msg += dateFields;
	msg += categoryFields;
	msg += errorFields;
	
	return msg;
}//end function

function validate(theForm, expectEverything)
{
	var msg = "";
	var emptyFields = "";
	var nonNumericFields = "";
	var emailFields = "";
	var maxLengthFields = "";
	var dateFields = "";
	var categoryFields = "";
	var errorFields = "";
	var isalutation = 0;
	var irelation = 0;

	for (var i = 0; i < theForm.length; i++) {

		var e = theForm.elements[i];

		var validationRequired =
			(expectEverything && !e.optional) ||
			(e.required && e.required == true) ||
			((e.type == "text" || e.type == "textarea" || e.type == "password") && !isBlank(e.value));

		var description = (e.description ? e.description : e.name);

		// expectEverything - all fields should be filled in unless specified optional
		// otherwise all fields optional unless specified required
		if ((e.type == "text" || e.type == "textarea" || e.type == "password") &&
						((expectEverything && !e.optional) || e.required)) {
			if (isBlank(e.value))
				emptyFields += "\n        " + description;
		}


		if ((e.type == "select-one") && ((expectEverything && !e.optional) || e.required)) {
						if (e.value == "")
						emptyFields += "\n        " + description;
		}


		if ((e.type == "checkbox" || e.type == "radio") && ((expectEverything && !e.optional) || e.required)) {
							if (!e.checked) {								
								e.fieldcounter++;
								if (e.fieldcounter >= e.fieldcount) {
								emptyFields += "\n        " + description;
								}
							}
		}

		if (validationRequired &&
			(e.numeric || e.integer || (e.min != null) || (e.max != null))) {
			var v = parseFloat(e.value);
			if (isNaN(v) || (e.integer && !isIntegerString(e.value)) ||
				((e.min != null) && (v < e.min)) ||
				((e.max != null) && (v > e.max))) {
				nonNumericFields += "- The field " + description + " must be " +
							(e.integer ? "an integer" : "a number");
				if (e.min != null)
					nonNumericFields += " that is greater than or equal to " + e.min;
				if (e.max != null && e.min != null)
					nonNumericFields += " and less than or equal to " + e.max;
				else if (e.max != null)
					nonNumericFields += " that is less than or equal to " + e.max;
				nonNumericFields += "\n";
			}
		}
		if (validationRequired &&
			(e.email && !isValidEmail(e.value))) {
			emailFields += "- The field " + description + " must be a valid e-mail address\n";
		}
		if (validationRequired &&
			(e.maxlength && e.maxlength != null && e.value)) {
			if (e.value.length > e.maxlength) {
				maxLengthFields += "- The field " + description + " can be at most " + e.maxlength +
									" characters long\n";
			}
		}
		if (validationRequired &&
			(e.date && !isValidDate(e.value))) {
			dateFields += "- The field " + description + " must be a valid date\n";
		}
		if (validationRequired &&
			(e.category && !isStringCategory(e.value, e.category))) {
			categoryFields += "- The field " + description + " does not belong to the " +
								" category " + (e.categoryName != null ? e.categoryName :
																			e.category) + "\n";
		}
		if (e.error) {
			errorFields += "- " + e.error + "\n";
		}
	}

	// State Validaton if country is US or CA, state is required

	if (!emptyFields && !nonNumericFields && !emailFields && !maxLengthFields &&
			!dateFields && !categoryFields && !errorFields)
		return true;

	msg += "The form could not be submitted due to the following errors.\n";
	msg += "Please correct and re-submit.\n\n";

	if (emptyFields)
		msg += "- The following field(s) are blank and require a value:" + emptyFields + "\n";

	msg += nonNumericFields;
	msg += emailFields;
	msg += maxLengthFields;
	msg += dateFields;
	msg += categoryFields;
	msg += errorFields;

	alert(msg);
	return false;
}

function isIntegerString(str) {
	if (null == str || "undefined" == str || "" == str)	// 6299
		return false;
	x = parseInt(new Number(str));
	if (isNaN(x))
		return false;
	if (str.indexOf(".") != -1)
		return false;
	return true;
//		return (parseFloat(str) % 1) == 0 && parseInt(str, 10) >= 0 && parseInt(str, 10) == (str - 0);
}

function isFloatString(str) {
	x = parseFloat(new Number(str));
	if (isNaN(x))
		return false;
	return true;
}

// email can be in one of the following formats:
// address
// address (comment)
// comment <address>
// comment [address]
// <address> comment
// [address] comment
// address, address
function isValidEmail(str) {
	var allAddrs = str.split(',');
	if (allAddrs.length == 0) return false;
	if (str.charAt(str.length - 1) == ',') return false;
	for (var i = 0; i < allAddrs.length; i++) {
		current = allAddrs[i];
		var index = current.indexOf('(');
		if (index != -1) {
			var head = current.substring(0, index-1);
			index = current.indexOf(')');
			if (index == -1) return false;
			var tail = Trim(current.substring(index + 1, current.length));
			if (tail != "") return false;
			current = head;
		} else if ((index = current.indexOf('<')) != -1) {
			var index2 = current.indexOf('>');
			if (index2 == -1) return false;
			current = current.substring(index + 1, index2);
		} else if ((index = current.indexOf('[')) != -1) {
			var index2 = current.indexOf(']');
			if (index2 == -1) return false;
			current = current.substring(index + 1, index2);
		}
		if (!isValidEmailAddr(Trim(current))) return false;
	}
	return true;
}

function isValidEmailAddr(str) {
	if (str.indexOf(' ') != -1) return false;
	var a = str.split("@");
	if (a.length != 2 || str.charAt(str.length-1) == '@') return false;
	var b = a[1].split(".");
	if (b.length < 2) return false;
	return true;
}

function isValidDate(str) {
/*
	var	currentDate = Date.parse(str);
	if (isNaN(currentDate))
		return false;
	return true;
*/
	var a = str.split("/");
	if (a.length != 3) return false;
	for (var i = 0; i < 3; i++) {
		if (!isIntegerString(a[i])) return false;
	}
	var month = parseInt(a[0], 10);
	var day = parseInt(a[1], 10);
	var year = parseInt(a[2], 10);
	if (month < 1 || month > 12) return false;
	if (day < 1 || day > 31) return false;

	// assumes 2 digit years are 1970-2069
	if (a[2].length == 2){
		year += (year < 70 ? 2000 : 1900);
	}
//		if (year < 1970) return false;
	return true;
}

function isStringCategory(str, categories) {
	var a = categories.split(",");
	for (var i = 0; i < a.length; i++) {
		if (str == a[i]) return true;
	}
	return false;
}

function Trim(s) {
	var start = s.length;
    var	end   = 0;
    var c     = "";

    for (var i = 0; i < s.length; i++)
    {
        c = s.substring(i, i+1);
        if (" " != c && "\t" !=c && "\n" !=c)
            if (i < start)
                start = i;
        else
            if (i > end)
                end = i;
    }
    return s.substring(start, end+1);
}

//	the types are defined in remote/kcKanaFieldInterface.java
//	1 = text field
//	2 = date field
//	3 = integer
//	4 = decimal
//	5 = boolean
//  6 = message
//  7 = contactType
function ValidateTypedValue(type, value) {
	var retString = "You must type in a valid " + TypeToString(type) + " value for the criteria";
	if (type == 1)		//	text
		return "";
	else if (type == 2)	//	date
	{
		if (isValidDate(value) == true) return "";
	}
	else if (type == 3) // integer
	{
		if (isIntegerString(value) == true)
		{
			if (value < 1000000000)
			{
				return "";
			}
			else
			{
				retString = "The value '" + value + "' is too large. Please use an integer less than 1,000,000,000.";
			}
		}
	}
	else if (type == 4)	//	decimal
	{
		if (isFloatString(value) == true) return "";
	}
	else if (type == 5)	//	boolean
		return "";
	else if (type == 6)	//	message
		return "";
	else if (type == 7) // contactType
		return "";
	return retString;
}

function TypeToString(type) {
	if (type == 1)		//	text
		return "text";
	else if (type == 2)	//	date
		return "date";
	else if (type == 3)	//	integer
		return "integer";
	else if (type == 4)	//	decimal
		return "decimal";
	else if (type == 5)	//	boolean
		return "boolean";
	return "undefined";
}

