// 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, O campo 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 O campo
//			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;
}

function validate(theForm, expectEverything){
		var msg = "";
		var emptyFields = "";
		var nonNumericFields = "";
		var emailFields = "";
		var maxLengthFields = "";
		var dateFields = "";
		var categoryFields = "";
		var errorFields = "";
		var iTratamento = 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 == "radio") {
							if (e.name == "Tratamento") {
								if (!e.checked) {
									iTratamento++;
									if (iTratamento >= 2) {
									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 += "- O campo: " + 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 += "- O campo " + description + " deve conter um endereço de e-mail válido\n";
			}
			if (validationRequired &&
				(e.maxlength && e.maxlength != null && e.value)) {
				if (e.value.length > e.maxlength) {
					maxLengthFields += "- O campo " + description + " deve conter no máximo " + e.maxlength +
										" caracteres\n";
				}
			}
			if (validationRequired &&
				(e.date && !isValidDate(e.value))) {
				dateFields += "- O campo " + description + " deve conter uma data válida\n";
			}
			if (e.error) {
				errorFields += "- " + e.error + "\n";
			}
		}

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

		msg += "O formulário não pode ser enviado devido ao(s) seguinte(s) erro(s).\n";
		msg += "Por favor corrija e o reenvie.\n\n";

		if (emptyFields)
			msg += "- O seguintes campo(s) são obrigatórios:" + 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 (Comentario)
	// Comentario <address>
	// Comentario [address]
	// <address> Comentario
	// [address] Comentario
	// 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 day = parseInt(a[0], 10);
		var month = 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){
//			return false;
//			year += (year < 70 ? 2000 : 1900);
//		}
//		if (year < 1970) return false;
		return true;
}	

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";
}

