﻿/*
	function ValidaRadio(Campo, Opcoes)
	by Bruno Pereira
	updated 2004-04-07
 */
	function ValidaRadio(Campo, Opcoes) {
		var CampoChecked = 0;
		for (var i = 0; i < document.SAPForm.length; i++) {
			var z= document.SAPForm.elements[i];
			if (z.name == Campo) {
				if (!z.checked) { CampoChecked++; }
				if (CampoChecked >= Opcoes) { return false; }
			 }
		 }
	 }

/*
	function DevolveValor(Campo)
	by Bruno Pereira
	updated 2004-04-07
 */
	function DevolveValor(Campo) {
		var CampoChecked = 0;
		for (var i = 0; i < document.SAPForm.length; i++) {
			var z= document.SAPForm.elements[i];
			if (z.name == Campo) { if (z.checked || z.type == "hidden") { return z.value; }  }
		 }
	 }

/*
	function Trim(string)
	eats whitespace in the front and end of a string
 */
	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 && "\r" != c) {
				if (i < start) { start = i; }
				else {
					if (i > end) {
						end = i;
					 }
				 }
			 }
		 }
		return s.substring(start, end+1);
	 }

/*
	function TrimTextField(field)
	Trim a form text field
 */
	function TrimTextField(field) {
		field.value = Trim(field.value); }

		// START Validate.js

		// 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 validate(theForm, expectEverything)
			{
				var msg = "";
				var emptyFields = "";
				var emptyFieldsNum = 0;
				var nonNumericFields = "";
				var emailFields = "";
				var maxLengthFields = "";
				var minLengthFields = "";
				var dateFields = "";
				var categoryFields = "";
				var errorFields = "";
				var igender = 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" || e.type == "hidden") &&
									((expectEverything && !e.optional) || e.required)) {
						if (isBlank(e.value)) {
							emptyFields += "\n        " + description;
							emptyFieldsNum += 1; }
					}

					if ((e.type == "select-one") && ((expectEverything && !e.optional) || e.required)) {
									if (e.value == "") {
									emptyFields += "\n        " + description;
									emptyFieldsNum += 1; }
					}

					if ((e.type == "select-multiple") && ((expectEverything && !e.optional) || e.required)) {
									if (e.value == "" || isBlank(e.value)) {
									emptyFields += "\n        " + description;
									emptyFieldsNum += 1; }
					}

					if (e.type == "radio") {
									if (e.name == "Gender") {
										if (!e.checked) {
											igender++;
											if (igender >= 2) {
											emptyFields += "\n        " + description;
											emptyFieldsNum += 1;
											}
										}
									}
					}

					if (validationRequired && e.value != "" &&
						(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 + " deve conter apenas " +
										(e.integer ? "números" : "números");
							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.value != "" &&
						(e.texto && !isValidText(e.value))) {
						emailFields += "- O campo " + description + " tem caracteres inválidos\n";
					}
					if (validationRequired && e.value != "" &&
						(e.email && !isValidEmail(e.value))) {
						emailFields += "- O campo " + description + " deve ser um endereço válido\n";
					}
					if (validationRequired &&
						(e.maxlength && e.maxlength != null && e.value)) {
						if (e.value.length > e.maxlength) {
							maxLengthFields += "- O campo " + description + " deve ter no máximo " + e.maxlength +
												" caracteres\n";
						}
					}
					if (validationRequired &&
						(e.minlength && e.minlength != null && e.value)) {
						if (e.value.length < e.minlength) {
							minLengthFields += "- O campo " + description + " deve ter pelo menos " + e.minlength +
												" caracteres\n";
						}
					}
					if (validationRequired &&
						(e.date && !isValidDate(e.value))) {
						dateFields += "- O campo " + description + " deve ser uma data válida\n";
					}
					if (validationRequired &&
						(e.category && !isStringCategory(e.value, e.category))) {
						categoryFields += "- O campo " + description + " não pertence à " +
											"categoria" + (e.categoryName != null ? e.categoryName :
																						e.category) + "\n";
					}
					if (e.error) {
						errorFields += "- " + e.error + "\n";
					}

				}

				if (!emptyFields && !nonNumericFields && !emailFields && !maxLengthFields && !minLengthFields &&
						!dateFields && !categoryFields && !errorFields)
					return true;

				msg += "O formulário não pode ser enviado devido aos seguintes erros.\n";
				msg += "Corrija-os e volte a enviar.\n\n";

				if (emptyFields)

					if (emptyFieldsNum > 1) {msg += "- Os seguintes campos têm que ser preenchidos:"+ emptyFields + "\n";}
					else {msg += "- O seguinte campo tem que ser preenchido:" + emptyFields + "\n";}

				msg += nonNumericFields;
				msg += emailFields;
				msg += maxLengthFields;
				msg += minLengthFields;
				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 isValidText(str) {
				var a = str.length;
				var invalidchar = "/'"
				for (var i = 0; i < a; i++) {
					if (invalidchar.indexOf(str.substr(i,1)) > 0) { 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";
			}
		// END Validate.js

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
<!-- Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
<!-- Changes:
/* 1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
international characters) were allowed.

1.1.3: Added the restriction to only accept addresses ending in two
letters (interpreted to be a country code) or one of the known
TLDs (com, net, org, edu, int, mil, gov, arpa), including the
new ones (biz, aero, name, coop, info, pro, museum).  One can
easily update the list (if ICANN adds even more TLDs in the
future) by updating the knownDomsPat variable near the
top of the function.  Also, I added a variable at the top
of the function that determines whether or not TLDs should be
checked at all.  This is good if you are using this function
internally (i.e. intranet site) where hostnames don't have to
conform to W3C standards and thus internal organization e-mail
addresses don't have to either.
Changed some of the logic so that the function will work properly
with Netscape 6.

1.1.2: Fixed a bug where trailing . in e-mail address was passing
(the bug is actually in the weak regexp engine of the browser; I
simplified the regexps to make it work).

1.1.1: Removed restriction that countries must be preceded by a domain,
so abc@host.uk is now legal.  However, there's still the
restriction that an address must end in a two or three letter
word.

1.1: Rewrote most of the function to conform more closely to RFC 822.

1.0: Original  */
// -->

<!-- Begin
function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

//alert("O seu endereço de E-mail está incorrecto.");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
//alert("O seu endereço de e-mail contem caracteres inválidos.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
//alert("O seu endereço de e-mail contem caracteres inválidos.");
return false;
   }
}

// See if "user" is valid

if (user.match(userPat)==null) {

// user is not valid

//alert("O seu endereço de e-mail não é válido.");
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
//alert("O endereço IP de destino não é válido.");
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.

var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
//alert("O seu endereço de e-mail não é válido.");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 &&
domArr[domArr.length-1].search(knownDomsPat)==-1) {
//alert("O endereço de e-mail deve terminar com um domínio conhecido ou com as duas que identificam o país.");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
//alert("Falta um servidor no seu enderço de e-mail.");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

//  End -->
