 /*--------------Indice de Funções-------------------------------------------------
FormatDate(i, delKey,direction)
CheckDate(dtaDate)
FormatCGC(i, delKey,direction)
FormatCPF(i, delKey,direction)
FormatCEP(i, delKey,direction)
FormatIE(i, delKey,direction)
CheckNum()
IsNumeric(strNumber)
IsDate(strDate)
LTrim(String)
RTrim(String)
Trim(String)
Len(String)
Left(str, n)
Right(str, n)
Mid(str, start, len)
InStr(strSearch, charSearchFor)
FormatNumber(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit,UseParensForNegativeNumbers, GroupDigits)
FormatCurrency(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit,UseParensForNegativeNumbers, GroupDigits)
autoTab(input,len, e)
emailCheck (emailStr)
function maxLength(textAreaField, limit)//habilita valor maximo de caracteres no campo textarea
*/

//fun'cao p/ trazer a data no formato ano/mes/dia
function convertDate(data)
{
	var dPromoDe,mPromoDe,aPromoDe
	//alert(data);			
	dPromoDe = data.substr(0, 2);
	mPromoDe = data.substr(3, 2);
	aPromoDe = data.substr(6, 4);
	dtPromoDe = (aPromoDe + mPromoDe + dPromoDe);
	data = dtPromoDe;
	//alert(data.length);
	if(data.length = 8)
	{
		return data;
	}
	else
	{
	return false;
	}
	
}

/*------------------------------------------------------------------------------------------
Função: FormatDate(i, delKey,direction) 
		CheckDate(dtaDate)
Objetivo: Faz a formatação da data numa caixa de texto
		  Esta função deve ser utilizada em conjunto com a função CheckDate
Exemplo: onchange="CheckDate(this)" onkeydown="FormatDate(this, window.event.keyCode,'down')" onkeyup="FormatDate(this, window.event.keyCode,'up')"
Retorno: Data formatada e mensagem de erro.
------------------------------------------------------------------------------------------*/

	function FormatDate(i, delKey,direction)
	{
		if (i.value.length < 10) 
		{
			if (delKey!=9) 
			{ // se for tab
				if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41))
				{ //teclas delete, backspace, shift, nao disparam o evento
					var fieldLen = i.value.length
					if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) 
					{
						if (fieldLen == 2 || fieldLen == 5) 
						{
							i.value = i.value + "/";
						}
					} 
					else 
					{
						if (direction == "up") 
						{
							if (i.value.length == 0) 
							{
								i.value = "";
							} 
							else 
							{
								i.value = i.value.substring(0,i.value.length-1);
							}
						}
					}
					i.focus();
				}
			} 
			else 
			{
				if (direction == "down") 
				{
					CheckDate(i);
				}
			}
		}
	}
	//---------------------------------

	function CheckDate(dtaDate) 
	{
		if (dtaDate.value == "" ) //verifica se a data foi digitada
		{
		return false;
		}
		var err=0;
		dtaValue=dtaDate.value;
		if (dtaValue.length != 8 && dtaValue.length != 10 ) err=1
		mm = dtaValue.substring(3, 5);
		dd = dtaValue.substring(0, 2);
		yy = dtaValue.substring(6, 10);
		if (mm<1 || mm>12) err = 1
		if (dd<1 || dd>31) err = 1
		if (yy.length == 4){
			if (yy<1900) err = 1
		}
		else {
			//se ano for inferior a 30 se entende 20??
			//se for maior que 29 se entende 19??
			yy=parseInt(yy,10)
			yy += yy<30?2000:1900
		}
		if (mm==4 || mm==6 || mm==9 || mm==11)
		{
			if (dd==31) err=1
		}
		if (mm==2)
		{
			var dtaYear=parseInt(yy/4);
			if (isNaN(dtaYear)) 
			{
				err=1;
			}
			if (dd>29) err=1
			if (dd==29 && ((yy/4)!=parseInt(yy/4))) err=1
		}
		dtaDate.value = dd + '/' + mm + '/' + yy

		if (err==1) 
		{
			if (dtaValue.length < 8) //verifica se a data digitada está completa
			{
				dtaDate.value = ""
			}
			else
			{
				//alert('O valor ' + dtaDate.value + ' não é uma data válida!');
				alert('Data invalida!\nFormato de data valida: DD/MM/YYYY!');
				dtaDate.value = "";
				dtaDate.focus();
				return false;
			}
		}
		return true;
	}

/*-------------------------------------------------------------------------------------------------
Função: FormatCGC(i, delKey,direction)
Objetivo: Cria máscara para digitação de CGC
Exemplo: onkeydown="FormatCGC(this, window.event.keyCode,'down')" onkeyup="FormatCGC(this, window.event.keyCode,'up')"
Retorno: Retorna o CGC Formatado
-------------------------------------------------------------------------------------------------*/

	function FormatCGC(i, delKey,direction)
	{
		if (i.value.length < 19) 
		{
			if (delKey!=9) 
			{ // se for tab
				if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41))
				{ //teclas delete, backspace, shift, nao disparam o evento
					var fieldLen = i.value.length
					if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) 
					{
						if ((fieldLen == 2) || (fieldLen == 6)) 
						{
							i.value = i.value + ".";
						}
						if (fieldLen == 10) 
						{
							i.value = i.value + "/";
						}
						if (fieldLen == 15) 
						{
							i.value = i.value + "-";
						}
					} 
					else 
					{
						if (direction == "up") 
						{
							if (i.value.length == 0) 
							{
								i.value = "";
							} 
							else 
							{
								i.value = i.value.substring(0,i.value.length-1);
							}
						}
					}
					i.focus();
				}
			} 
		}
	}

/*-------------------------------------------------------------------------------------------------
Função: FormatCEP(i, delKey,direction)
Objetivo: Cria máscara para digitação de CEP
Exemplo: onkeydown="FormatCEP(this, window.event.keyCode,'down')" onkeyup="FormatCEP(this, window.event.keyCode,'up')"
Retorno: Retorna o CEP Formatado
-------------------------------------------------------------------------------------------------*/

	function FormatCEP(i, delKey,direction) 
	{

		if (delKey!=9) 
		{ // se for tab
			if(delKey!=8 && delKey!=46 && delKey!=16 && delKey!=37)
			{ //teclas delete, backspace, shift, e % nao disparam o evento
				var fieldLen = i.value.length;

				if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <= 107)) 
				{
					if (fieldLen == 5) 
					{
						i.value = i.value + "-";
					}
				} 
				else 
				{
					if (direction == "up") 
					{
						if (i.value.length == 0) 
						{
							i.value = "";
						} 
						else 
						{
							i.value = i.value.substring(0,i.value.length-1);
						}
					}
				}
				i.focus();
			}
		} 
	}

/*-------------------------------------------------------------------------------------------------
Função: FormatIE(i, delKey,direction)
Objetivo: Cria máscara para digitação de Inscrição Estadual
Exemplo: onkeydown="FormatIE(this, window.event.keyCode,'down')" onkeyup="FormatIE(this, window.event.keyCode,'up')"
Retorno: Retorna a IE Formatada
-------------------------------------------------------------------------------------------------*/

	function FormatIE(i, delKey,direction) 
	{
		if (i.value.length < 11) 
		{
			if (delKey!=9) 
			{ // se for tab
				if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41))
				{ //teclas delete, backspace, shift, nao disparam o evento
					var fieldLen = i.value.length
					if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) 
					{
						if ((fieldLen == 3) || (fieldLen == 7)) 
						{
							i.value = i.value + ".";
						}
					} 
					else 
					{
						if (direction == "up") 
						{
							if (i.value.length == 0) 
							{
								i.value = "";
							} 
							else 
							{
								i.value = i.value.substring(0,i.value.length-1);
							}
						}
					}
					i.focus();
				}
			} 
		}
	}

/*-------------------------------------------------------------------------------------------------
Função: FormatCPF(i, delKey,direction)
Objetivo: Cria máscara para digitação de CPF
Exemplo: onkeydown="FormatCPF(this, window.event.keyCode,'down')" onkeyup="FormatCPF(this, window.event.keyCode,'up')"
Retorno: Retorna o CPF Formatada
-------------------------------------------------------------------------------------------------*/
	function FormatCPF(i, delKey,direction)
	{
		if (i.value.length < 15) 
		{
			if (delKey!=9) 
			{ // se for tab
				if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41))
				{ //teclas delete, backspace, shift, nao disparam o evento
					var fieldLen = i.value.length
					if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) 
					{
						if ((fieldLen == 3) || (fieldLen == 7)) 
						{
							i.value = i.value + ".";
						}
						if (fieldLen == 11) 
						{
							i.value = i.value + "-";
						}
					} 
					else 
					{
						if (direction == "up") 
						{
							if (i.value.length == 0) 
							{
								i.value = "";
							} 
							else 
							{
								i.value = i.value.substring(0,i.value.length-1);
							}
						}
					}
					i.focus();
				}
			}
		}
		else
		{
			i.value = i.value.substring(0,14);
		} 
	}

/*-------------------------------------------------------------------------------------------------
Função: CheckNum()
Objetivo: Faz a validação para permitir apenas ser digitado números numa caixa de texto.
OBS: Esta função permite digitar vírgulas
Exemplo: onKeyPress = "return CheckNum()"
Retorno: A função barra a digitação
-------------------------------------------------------------------------------------------------*/
	
	function CheckNum()
	{
	//alert(event.keyCode)
		if ((event.keyCode < 48) || (event.keyCode > 57))
		{
			if ((event.keyCode != 44) && (event.keyCode != 46) && (event.keyCode != 45))
			{
				return false;
			}
		}
		return true;
	}

/*-------------------------------------------------------------------------------------------------
Função: IsNumeric(strNumber)
Objetivo: Verifica se a informação de entrada da função é numérico
		  Esta função é usada na função IsDate, mas pode ser utilizada separadamente.
Retorno: True ou False
-------------------------------------------------------------------------------------------------*/

	function IsNumeric(strNumber)
	{
		strTemp = "";
		if (strNumber == "")
		{
			return false;
		}
		
		for( i = 0; i < (strNumber.length); i++)
		{
			strChar = strNumber.charAt(i);
			if ( !( strChar >= "0" && strChar <= "9" || strChar == "," || strChar == "." ) )
			{
				if ( !(i == 0 && strChar == "-") )
				{
					strTemp += strChar;
				}
			}
		}
		return (strTemp == "");
	}

/*-------------------------------------------------------------------------------------------------
Função: IsDate(strDate)
Objetivo: Verifica se a informação de entrada é uma data.
Exemplo: onKeyPress = "return CheckNum()"
Retorno: True ou False
-------------------------------------------------------------------------------------------------*/

	function IsDate(strDate)
	{
		if (!IsNumeric(strDate.charAt(1)) )
		{
			strDate = "0" + strDate;
		}
		
		if (!IsNumeric(strDate.charAt(4)) )
		{
			strDate = strDate.substring(0,3) + "0" + strDate.substring(3,strDate.length);
		}

		if ( !(strDate.length == 8 || strDate.length == 10) )
		{
			return (false);
		}
		
		strDay = strDate.charAt(0) + strDate.charAt(1);
		strMonth = strDate.charAt(3) + strDate.charAt(4);
		strYear = strDate.charAt(6) + strDate.charAt(7);

		if (strDate.length == 10)
		{
			strYear += strDate.charAt(8) + strDate.charAt(9);
		}

		numDay = 0;
		numMonth = 0;
		numYear = 0;
		
		if (IsNumeric(strDay))
		{
			numDay = parseInt(strDay,10);
		}
		else
		{
			return (false);
		}

		if (IsNumeric(strMonth))
		{
			numMonth = parseInt(strMonth,10);
		}
		else
		{
			return (false);
		}

		if (IsNumeric(strYear))
		{
			numYear = parseInt(strYear,10);
			if (numYear < 100 )
			{
				numYear += numYear<30?2000:1900;
			}
		}
		else
		{
			return false;
		}

		blnBissexto = ((numYear % 4) == 0);

		if (numMonth == 0 || numMonth > 12)
		{
			return (false);
		}

		if (numMonth == 2)
		{
			if (blnBissexto)
			{
				if (numDay > 29)
				{
					return (false);
				}
			}
			else
			{
				if (numDay > 28)
				{
					return (false);
				}
			}
		}
		else if (numMonth == 4 || numMonth == 6 || numMonth == 9 || numMonth == 11)
		{
			if (numDay > 30)
			{
				return (false);
			}
		}
		else
		{
			if (numDay > 31)
			{
				return (false);
			}
		}
		return (true);
	}

/*---------------------------------------------------------------------------------------------
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
PURPOSE: Remove	leading	blanks from	our	string.
IN:	str	- the string we	want to	LTrim

RETVAL:	An LTrimmed	string!
---------------------------------------------------------------------------------------------*/
	function LTrim(str)
	{
		var	whitespace = new String(" \t\n\r");

		var	s =	new	String(str);

		if (whitespace.indexOf(s.charAt(0))	!= -1) {
			// We have a string	with leading blank(s)...

			var	j=0, i = s.length;

			// Iterate from	the	far	left of	string until we
			// don't have any more whitespace...
			while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
				j++;

			// Get the substring from the first	non-whitespace
			// character to	the	end	of the string...
			s =	s.substring(j, i);
		}

		return s;
	}

/*---------------------------------------------------------------------------------------------
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
PURPOSE: Remove	trailing blanks	from our string.
IN:	str	- the string we	want to	RTrim

RETVAL:	An RTrimmed	string!
---------------------------------------------------------------------------------------------*/
	function RTrim(str)
	{
		// We don't	want to	trip JUST spaces, but also tabs,
		// line	feeds, etc.	 Add anything else you want	to
		// "trim" here in Whitespace
		var	whitespace = new String(" \t\n\r");

		var	s =	new	String(str);

		if (whitespace.indexOf(s.charAt(s.length-1)) !=	-1)	{
			// We have a string	with trailing blank(s)...

			var	i =	s.length - 1;		// Get length of string

			// Iterate from	the	far	right of string	until we
			// don't have any more whitespace...
			while (i >= 0 &&	whitespace.indexOf(s.charAt(i))	!= -1)
				i--;

			// Get the substring from the front	of the string to
			// where the last non-whitespace character is...
			s =	s.substring(0, i+1);
		}

		return s;
	}

/*---------------------------------------------------------------------------------------------
Trim(string) : Returns a copy of a string without leading or
			   trailing spaces
=============================================================
PURPOSE: Remove	trailing and leading blanks	from our string.
IN:	str	- the string we	want to	Trim

RETVAL:	A Trimmed string!
---------------------------------------------------------------------------------------------*/
	function Trim(str)
	{
			return RTrim(LTrim(str));
	}

/*---------------------------------------------------------------------------------------------
Len(String) : Returns the number of characters in a string
===========================================================
IN: str - the string whose length we are interested in

RETVAL: The number of characters in the string
---------------------------------------------------------------------------------------------*/

	function Len(str)
	{  return String(str).length;  }

/*---------------------------------------------------------------------------------------------
Left(string, length): Returns a	specified number of	characters from	the
					  left side	of a string
========================================================================
IN:	str	- the string we	are	LEFTing
	n -	the	number of characters we	want to	return

RETVAL:	n characters from the left side	of the string
---------------------------------------------------------------------------------------------*/

	function Left(str, n)
	{
		if (n <= 0)	   // Invalid bound, return	blank string
				return "";
		else if	(n > String(str).length)	  // Invalid bound,	return
				return str;				   // entire string
		else //	Valid bound, return	appropriate	substring
				return String(str).substring(0,n);
	}

/*---------------------------------------------------------------------------------------------
Right(string, length): Returns a specified number of characters from the
					   right side of a string
========================================================================
IN:	str	- the string we	are	RIGHTing
	n -	the	number of characters we	want to	return

RETVAL:	n characters from the right	side of	the	string
---------------------------------------------------------------------------------------------*/

	function Right(str, n)
	{
		if (n <=	0)		// Invalid bound, return	blank string
			return "";
		else if	(n >	String(str).length)	  // Invalid bound,	return
			return str;					   // entire string
		else { // Valid	bound, return appropriate substring
			var iLen	= String(str).length;
			return String(str).substring(iLen, iLen - n);
		}
	}

/*---------------------------------------------------------------------------------------------
Mid(string,	start, length):	Returns	a specified	number of characters from a
							string
============================================================================
IN:	str	- the string we	are	LEFTing
	start -	our	string's starting position (0 based!!)
	len	- how many characters from start we	want to	get

RETVAL:	The	substring from start to	start+len

---------------------------------------------------------------------------------------------*/
	function Mid(str, start, len)
	/***
	***/
	{
		// Make	sure start and len are within proper bounds
		if (start < 0 || len < 0) return "";

		var	iEnd, iLen = String(str).length;
		if (start +	len > iLen)
			iEnd = iLen;
		else
			iEnd = start + len;

		return String(str).substring(start,iEnd);
	}

/*------------------------------------------------------------------------------------------------------
InStr(str, SearchForStr) : Returns the location	a character	(charSearchFor)
						   was found in	the	string str
========================================================================
InStr(strSearch, charSearchFor)	: Returns the first	location a substring (SearchForStr)
						   was found in	the	string str.	 (If the character is <B>not</B>
						   found, -1 is	returned.)
------------------------------------------------------------------------------------------------------*/
	function InStr(strSearch, charSearchFor)
	{
		for (i=0; i < Len(strSearch); i++)
		{
			if (charSearchFor == Mid(strSearch, i, 1))
			{
				return i;
			}
		}
		return -1;
	}

/*------------------------------------------------------------------------------------------------------
FormatNumber(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit,
             UseParensForNegativeNumbers, GroupDigits)
======================================================================
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 ------------------------------------------------------------------------------------------------------*/

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
{ 
	if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign

	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)

			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

/*------------------------------------------------------------------------------------------------------
FormatCurrency(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit,
               UseParensForNegativeNumbers, GroupDigits)
/**********************************************************************
IN:
	NUM - the number to format
	decimalNum - the number of decimal places to format the number to
	bolLeadingZero - true / false - display a leading zero for
									numbers between -1 and 1
	bolParens - true / false - use parenthesis around negative numbers
	bolCommas - put commas as number separators.
 
RETVAL:
	The formatted number!
------------------------------------------------------------------------------------------------------*/

	function FormatCurrency(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
	{
		var tmpStr = new String(FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas));

		if (tmpStr.indexOf("(") != -1 || tmpStr.indexOf("-") != -1) {
			// We know we have a negative number, so place '$' inside of '(' / after '-'
			if (tmpStr.charAt(0) == "(")
				tmpStr = "($"  + tmpStr.substring(1,tmpStr.length);
			else if (tmpStr.charAt(0) == "-")
				tmpStr = "-$" + tmpStr.substring(1,tmpStr.length);
				
			return tmpStr;
		}
		else
			return "$" + tmpStr;		// Return formatted string!
	}





/*------------------------------------------------------------------------------------------------------
autoTab(input,len, e)

/*------------------------------------------------------------------------------------------
Função: autoTab(input,len, e)
Objetivo: Tabulação automática quando o tamanho do (em bytes) campo for atingido.
Exemplo: onKeyUp="autoTab(this, 3, event)"
Entradas:
	input - objeto em que tecla foi pressionada. Geralmente this.
	len - tamanho em que o tab é acionado
	e - event 
Retorno: true
------------------------------------------------------------------------------------------*/


// 
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
	
	function autoTab(input,len, e) {
		
		var keyCode = (isNN) ? e.which : e.keyCode; 
		
		var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
		
		if(input.value.length >= len && !containsElement(filter,keyCode))
		{
			input.value = input.value.slice(0, len);
			input.form[(getIndex(input)+1) % input.form.length].focus();
		}
	
		function containsElement(arr, ele) {
			var found = false, index = 0;
			while(!found && index < arr.length)
			if(arr[index] == ele)
				found = true;
			else
				index++;
			return found;
		}

		function getIndex(input) {
			var index = -1, i = 0, found = false;
			while (i < input.form.length && index == -1)
				if (input.form[i] == input)index = i;
				else i++;
				return index;
		}
	
	return true;
	}
	

/*------------------------------------------------------------------------------------------
Função: function Verificar()
Objetivo: Essa função não permite que o usuário cole dados no formulário
Exemplo: Dentro do Form, insira: <form name="DataForm"  onKeyDown="Verificar()">
Entradas:
Retorno: true
------------------------------------------------------------------------------------------*/
function Verificar() 
{

var ctrl=window.event.ctrlKey;
var tecla=window.event.keyCode; 
if (ctrl && tecla==67) {event.keyCode=0; event.returnValue=false;}
if (ctrl && tecla==86) {event.keyCode=0; event.returnValue=false;}
}

//---------------------------------
//Função para buscar Estado na página buscaCidade.asp
function openAjax()
{
	var Ajax;
		try
		{
			Ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers mais populares, como: Firefox, Safari, dentre outros.
		}
		catch(ee)
			{
			try {Ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS
			}
		catch(e)
			{
			try {Ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS
			}
		catch(e)
			{
			Ajax = false;
			}
	}
}
return Ajax;
}
//---------------------------------


//exemplo de uso: <form name=emailform onSubmit="return emailCheck(this.email.value)">
<!-- 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 endere\u00e7o de e-mail deve ser preenchido corretamente (verifique o '@' e o '.')");
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 endere\u00e7oo de e-mail deve ser preenchido corretamente.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("O nome do domínio de seu endere\u00e7oo de e-mail contem caracteres invalidos.");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

alert("O endere\u00e7oo de e-mail deve ser preenchido corretamente.");
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\u00e7oo de e-mail deve ser preenchido corretamente");
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 endere\u00e7oo de e-mail deve ser preenchido corretamente.Erro 002");
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\u00e7oo de e-mail deve ser preenchido corretamente " + ".Use apenas letras minusculas e sem caracteres especiais.");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
alert("O endere\u00e7oo de e-mail deve ser preenchido corretamente!");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

//  End -->


/*------------------------------------------------------------------------------------------
Função: function FormataValor()
Objetivo: formata valor em reais
Exemplo: onKeyDown="FormataValor(this,event,17,2);" 
Entradas:
Retorno: true
------------------------------------------------------------------------------------------*/

function FormataReal(nvalor){
nvalor = nvalor.replace(".","");
nvalor = nvalor.replace(",",".");
return nvalor;
}
function FormataValor(objeto,teclapres,tammax,decimais) 
{
	var tecla			= teclapres.keyCode;
	var tamanhoObjeto	= objeto.value.length;
	if ((tecla == 8) && (tamanhoObjeto == tammax))
	{
		tamanhoObjeto = tamanhoObjeto - 1 ;
	}
    if (( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) && ((tamanhoObjeto+1) <= tammax))
	{
		vr	= objeto.value;
		vr	= vr.replace( "/", "" );
		vr	= vr.replace( "/", "" );
		vr	= vr.replace( ",", "" );
		vr	= vr.replace( ".", "" );
		vr	= vr.replace( ".", "" );
		vr	= vr.replace( ".", "" );
		vr	= vr.replace( ".", "" );
		tam	= vr.length;
		if (tam < tammax && tecla != 8)
		{
			tam = vr.length + 1 ;
		}
		if ((tecla == 8) && (tam > 1))
		{
			tam = tam - 1 ;
			vr = objeto.value;
			vr = vr.replace( "/", "" );
			vr = vr.replace( "/", "" );
			vr = vr.replace( ",", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
		}
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
		{
			if (decimais > 0)
			{
				if ( (tam <= decimais) )
				{ 
					objeto.value = ("0," + vr) ;
				}
				if( (tam == (decimais + 1)) && (tecla == 8))
				{
					objeto.value = vr.substr( 0, (tam - decimais)) + ',' + vr.substr( tam - (decimais), tam ) ;	
				}
				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) == "0"))
				{
					objeto.value = vr.substr( 1, (tam - (decimais+1))) + ',' + vr.substr( tam - (decimais), tam ) ;
				}
				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) != "0"))
				{
				    objeto.value = vr.substr( 0, tam - decimais ) + ',' + vr.substr( tam - decimais, tam ) ; 
				}
				if ( (tam >= (decimais + 4)) && (tam <= (decimais + 6)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 3) ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
			 	if ( (tam >= (decimais + 7)) && (tam <= (decimais + 9)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 6) ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
				if ( (tam >= (decimais + 10)) && (tam <= (decimais + 12)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 9) ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
				if ( (tam >= (decimais + 13)) && (tam <= (decimais + 15)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 12) ) + '.' + vr.substr( tam - (decimais + 12), 3 ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
			}
			else if(decimais == 0)
			{
				if ( tam <= 3 )
				{ 
			 		objeto.value = vr ;
				}
				if ( (tam >= 4) && (tam <= 6) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr(0, tam - 3) + '.' + vr.substr( tam - 3, 3 ); 
				}
				if ( (tam >= 7) && (tam <= 9) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 6 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
				}
				if ( (tam >= 10) && (tam <= 12) )
				{
			 		if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
				}

				if ( (tam >= 13) && (tam <= 15) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ) ;
				}			
			}
		}
	}
	else if((window.event.keyCode != 8) && (window.event.keyCode != 9) && (window.event.keyCode != 13) && (window.event.keyCode != 35) && (window.event.keyCode != 36) && (window.event.keyCode != 46))
		{
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
}


//usar no form onsubmit="return verifica_form(this);"
//usar no campo <INPUT name="peso" 
//type="text" class=campos_formulario id="peso" style="width=175" onKeyDown="FormataValor(this,event,17,2);" onKeyPress="desabilita_cor(this)" value="" maxlength="255"  df_verificar="sim"> 
//note que o campo contem df_verificar="sim" que significa obrigatoriedade no campo para apresentar o texto.


function verifica_form(form) {
var passed = false;
var ok = false
var campo
for (i = 0; i < form.length; i++) {
  campo = form[i].name;
  if (form[i].df_verificar == "sim") {
    if (form[i].type == "text"  | form[i].type == "textarea" | form[i].type == "select-one") {
      if (form[i].value == "" | form[i].value == "http://") {
		form[campo].className='campo_alerta'
        form[campo].focus();
        alert("Preencha corretamente o campo");
        return passed;
        stop;
      }
    }
    else if (form[i].type == "radio") {
      for (x = 0; x < form[campo].length; x++) {
        ok = false;
        if (form[campo][x].checked) {
          ok = true;
          break;
        }
      }
      if (ok == false) {
        form[campo][0].focus();
		form[campo][0].select();
        alert("Informe uma das opcões");
        return passed;
        stop;
      }
    }
    var msg = ""
    if (form[campo].df_validar == "cpf") msg = checa_cpf(form[campo].value);
    if (form[campo].df_validar == "cnpj") msg = checa_cnpj(form[campo].value);
    if (form[campo].df_validar == "cpf_cnpj") {
	  msg = checa_cpf(form[campo].value);
	  if (msg != "") msg = checa_cnpj(form[campo].value);
	}
    if (form[campo].df_validar == "email") msg = checa_email(form[campo].value);
    if (form[campo].df_validar == "numerico") msg = checa_numerico(form[campo].value);
    if (msg != "") {
	  if (form[campo].df_validar == "cpf_cnpj") msg = "informe corretamente o número do CPF ou CNPJ";
	  form[campo].className='campo_alerta'
      form[campo].focus();
      form[campo].select();
      alert(msg);
      return passed;
      stop;
    }
  }
}
passed = true;
return passed;
}
//usar no input onKeyPress="desabilita_cor(this)" 
function desabilita_cor(campo) {
	campo.className='textbox'
}

function checa_numerico(String) {
	var mensagem = "Este campo aceita somente números"
	var msg = "";
	if (isNaN(String)) msg = mensagem;
	return msg;
}

//habilita valor maximo de caracteres no campo textarea
function maxLength(textAreaField, limit) {
	var ta = document.getElementById(textAreaField);
	
	if (ta.value.length >= limit) {
		ta.value = ta.value.substring(0, limit-1);
	}
}
