///////////////////////////////////////////
// VALIDAR INPUT DE CARACTERES
///////////////////////////////////////////

// forma de uso: onkeypress="javascript:vldKey(this,keyCharExp);"

var keyChar		= new keybEdit('abcdefghijklmnopqrstuvwxyz0123456789_','Caractere inválido. Utilize apenas caracteres alfanuméricos e "_"');
var keyCharExp 	= new keybEdit('aáàâãbcçdeéèêfghiíìjklmnoóòõôpqrstuúùüvwxyz0123456789_-()[]{}:/|\.,;+=@*%$#!ºª ','Caractere inválido.');
var keyNum		= new keybEdit('0123456789','Utilize apenas números inteiros positivos');
var keyNumM		= new keybEdit('-0123456789','Utilize apenas números inteiros (positivos ou negativos)');
var keyNumX		= new keybEdit('-,0123456789','Utilize apenas números (positivos ou negativos e/ou com ponto flutuante)');
var keyDec		= new keybEdit('0123456789.','Utilize apenas números (inteiros ou decimais)');
var keyDate 	= new keybEdit('0123456789/','Utilize apenas números e "/"');
var keyEmail 	= new keybEdit('abcdefghijklmnopqrstuvwxyz0123456789_.@-','Caractere inválido.');
var keyLogin 	= new keybEdit('abcdefghijklmnopqrstuvwxyz0123456789_','Caractere inválido.');

function keybEdit(strValid, strMsg) {
	var reWork = new RegExp('[a-z]','gi');		//	Regular expression\
	if(reWork.test(strValid))
		this.valid = strValid.toLowerCase() + strValid.toUpperCase();
	else
		this.valid = strValid;

	if((strMsg == null) || (typeof(strMsg) == 'undefined'))
		this.message = '';
	else
		this.message = strMsg;

	this.getValid 	= keybEditGetValid;
	this.getMessage = keybEditGetMessage;
	
	function keybEditGetValid() {
		return this.valid.toString();
	}
	
	function keybEditGetMessage() {
		return this.message;
	}
}

void function vldKey(objForm, objKeyb) {
	strWork = objKeyb.getValid();
	strMsg = '';							// Error message
	blnValidChar = false;					// Valid character flag

	if (window.event.keyCode != 13){
		if(!blnValidChar)
			for(i=0;i < strWork.length;i++)
				if(window.event.keyCode == strWork.charCodeAt(i)) {
					blnValidChar = true;
					break;
				}
	
		if(!blnValidChar) {
			if(objKeyb.getMessage().toString().length != 0)
				alert('Erro: ' + objKeyb.getMessage());
	
			window.event.returnValue = false;		// Clear invalid character
			objForm.focus();						// Set focus
		}
	}
}

///////////////////////////////////////////
// LIMITAR CAMPO TEXTO
///////////////////////////////////////////
//onKeyUp="limitaText(this.value.length,this,2000);"
function limitaText(TAMANHO,CAMPO,MAX){
	var TEXTO
	TEXTO = CAMPO.value
	if (TAMANHO > MAX){
		alert ('Texto muito longo!');
		CAMPO.value=TEXTO.substring(0,MAX);
	}
}

///////////////////////////////////////////
// POPUP
///////////////////////////////////////////
var popWin=0;
function popup(URLStr, width, height, scrolls, menu, janela){
	if(popWin){
		if(!popWin.closed) popWin.close();
	}
	if (!width){width = 400};
	if (!height){height = 300};	
	if (!janela){janela = 'popWin'}
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	popWin = open(URLStr, janela, 'toolbar=no,location=no,directories=no,status=no,menubar='+menu+',scrollbars='+scrolls+',resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}


///////////////////////////////////////////
// VALIDA DIGITACAO DE DATA NO CAMPO
///////////////////////////////////////////

//Exemplo: onchange="CheckDate(this)" onkeydown="FormatDate(this, window.event.keyCode,'down')" onkeyup="FormatDate(this, window.event.keyCode,'up')"

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) || (delKey >= 37 && delKey <= 40)) 
				{
					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(dtaDate.value + ' é uma data inválida !');
		dtaDate.value = "";
		return false;
		}
	}
	return true;
}
////////////////////////////////////////////////////
/// CALENDARIO
////////////////////////////////////////////////////
// Title: Tigra Calendar
// URL: http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.2 (European date format)
// Date: 10/14/2002 (mm/dd/yyyy)
// Note: Permission given to use this script in ANY kind of applications if
//    header lines are left unchanged.
// Note: Script consists of two files: calendar?.js and calendar.html

// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;

var calendars = [];
var RE_NUM = /^\-?\d+$/;

function calendar1(obj_target) {

	// assigning methods
	this.gen_date = cal_gen_date1;
	this.gen_time = cal_gen_time1;
	this.gen_tsmp = cal_gen_tsmp1;
	this.prs_date = cal_prs_date1;
	this.prs_time = cal_prs_time1;
	this.prs_tsmp = cal_prs_tsmp1;
	this.popup    = cal_popup1;

	// validate input parameters
	if (!obj_target)
		return cal_error("Error calling the calendar: no target control specified");
	if (obj_target.value == null)
		return cal_error("Error calling the calendar: parameter specified is not valid target control");
	this.target = obj_target;
	this.time_comp = BUL_TIMECOMPONENT;
	this.year_scroll = BUL_YEARSCROLL;
	
	// register in global collections
	this.id = calendars.length;
	calendars[this.id] = this;
}

function cal_popup1 (str_datetime) {
	this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.target.value);
	if (!this.dt_current) return;

	var obj_calwindow = window.open(
		'/calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id,
		'Calendar', 'width=170,height=150,status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
	);
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}

// timestamp generating function
function cal_gen_tsmp1 (dt_datetime) {
	return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}

// date generating function
function cal_gen_date1 (dt_datetime) {
	return (
		(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "/"
		+ (dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1) + "/"
		+ dt_datetime.getFullYear()
	);
}
// time generating function
function cal_gen_time1 (dt_datetime) {
	return (
		(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
		+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
		+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}

// timestamp parsing function
function cal_prs_tsmp1 (str_datetime) {
	// if no parameter specified return current timestamp
	if (!str_datetime)
		return (new Date());

	// if positive integer treat as milliseconds from epoch
	if (RE_NUM.exec(str_datetime))
		return new Date(str_datetime);
		
	// else treat as date in string format
	var arr_datetime = str_datetime.split(' ');
	return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}

// date parsing function
function cal_prs_date1 (str_date) {

	var arr_date = str_date.split('/');

	if (arr_date.length != 3) return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is dd/mm/yyyy.");
	if (!arr_date[0]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	if (!RE_NUM.exec(arr_date[0])) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[1]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[1])) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[2]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[2])) return cal_error ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[1] < 1 || arr_date[1] > 12) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[1]-1);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
	dt_date.setDate(arr_date[0]);
	if (dt_date.getMonth() != (arr_date[1]-1)) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

	return (dt_date)
}

// time parsing function
function cal_prs_time1 (str_time, dt_date) {

	if (!dt_date) return null;
	var arr_time = String(str_time ? str_time : '').split(':');

	if (!arr_time[0]) dt_date.setHours(0);
	else if (RE_NUM.exec(arr_time[0]))
		if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
		else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
	else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");
	
	if (!arr_time[1]) dt_date.setMinutes(0);
	else if (RE_NUM.exec(arr_time[1]))
		if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
		else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");

	if (!arr_time[2]) dt_date.setSeconds(0);
	else if (RE_NUM.exec(arr_time[2]))
		if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
		else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");

	dt_date.setMilliseconds(0);
	return dt_date;
}

function cal_error (str_message) {
	alert (str_message);
	return null;
}

///////////////////////////////////////////
// limpa caracters invalidos nos campos de texto
///////////////////////////////////////////
//onBlur="cleanData(this);" 

function cleanData(campo) {
	var rex1 = /^[\r\n\s*]+|[\r\n\s*]+$/g; // trim CrLf's
	var rex2 = /(\r\n\s*){2,}/g; // 2max CrLf's
	var data = campo.value;
	if (data != "") {
		var what;
		//* remove leading and trailing CrLf's from "textarea":
		what = data.replace(rex1,"");
		//* replace 3+ consecutive CrLf's with 2 in "textarea":
		what = what.replace(rex2,"\r\n\r\n");
		if (what != data) {
			campo.value = what;
		}
	}
}


///////////////////////////////////////////
// VALIDAR FORMULRIO
///////////////////////////////////////////
// Versão 2.0 - 14/03/2009
/*
Como usar:
1. colocar no <form method="post" action="..." name="..." onSubmit="return valida(this);">
2. para cada campo text, memo, hidden a ser validado colocar: <input type="text" ... frm_valid="Especifique o valor para ..."> 
3. para select colocar <select frm_valid="Especifique uma opção..."> - atenção: a primeira opção não vale como seleção.
4. para radio/checkbox colocar na primeira opção apenas: <input type="radio" value="..." frm_valid="Especifique uma opção...">
5. Campos especiais: valida o formato também (para validar SOMENTE o formato inclua frm_obriga='livre' : 

	e-mail: frm_valid="email"
	<input name="Email" class="frmTxt" value="<%=Email%>" size="40" maxlength="100" frm_valid="email">

	cep: frm_valid="cep"
	<input name="Cep_1" type="text" value="<%=Cep(0)%>" size="5" maxlength="5" frm_valid="cep" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 5)" onFocus="PararTAB(this)" >
	<input name="Cep_2" type="text" value="<%=Cep(1)%>" size="3" maxlength="3" onkeypress="javascript:return vldKey(this,event,keyNum);">
		
	cpf: frm_valid="cpf":
	<input name="Cpf_1" value="<%=Cpf(0)%>" type="text" size="3" maxlength="3" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 3)" onFocus="PararTAB(this)" frm_valid="cpf">&nbsp;
	<input name="Cpf_2" value="<%=Cpf(1)%>" type="text" size="3" maxlength="3" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 3)" onFocus="PararTAB(this)">&nbsp;
	<input name="Cpf_3" value="<%=Cpf(2)%>" type="text" size="3" maxlength="3" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 3)" onFocus="PararTAB(this)">&nbsp;
	<input name="Cpf_4" value="<%=Cpf(3)%>" type="text" size="2" maxlength="2" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 2)" onFocus="PararTAB(this)">
	
	cnpj: frm_valid="cnpj"
	<input name="Cnpj_1" value="<%=Cnpj(0)%>" type="text" size="2" maxlength="3" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 2)" onFocus="PararTAB(this)" frm_valid="cnpj">&nbsp;
	<input name="Cnpj_2" value="<%=Cnpj(1)%>" type="text" size="3" maxlength="3" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 3)" onFocus="PararTAB(this)">&nbsp;
	<input name="Cnpj_3" value="<%=Cnpj(2)%>" type="text" size="3" maxlength="3" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 3)" onFocus="PararTAB(this)">&nbsp;
	<input name="Cnpj_4" value="<%=Cnpj(3)%>" type="text" size="3" maxlength="2" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 3)" onFocus="PararTAB(this)">&nbsp;	
	<input name="Cnpj_5" value="<%=Cnpj(4)%>" type="text" size="2" maxlength="2" onKeyPress="ChecarTAB();vldKey(this,event,keyNum);" onKeyUp="Mostra(this, 2)" onFocus="PararTAB(this)">		
	
6. Para monstrar o texto da mensagem de acordo com o nome do campo, use frm_valid="*". Para um campo chamado "Telefone", o texto da validação será "Especifique um valor para o campo Telefone"

7. Se precisar de validações customizadas no mesmo formulário, inclua uma função "valida_custom" na pagina, retornando true ou false:

	function valida_custom(theForm){
		if (theForm.ExeInd[0].checked && theForm.ExeInd0.value == ''){
			alert ('Especifique quem foi o APG Senior.')
			theForm.ExeInd0.focus();
			return false;
		}
		return true;
	}
	
*/

function valida(theForm){


	//confirmação de submissão do formulário. caso negativo, cancela tudo:
	validQst = theForm.getAttribute('frm_valid');
	if (!!validQst){
		question = confirm(validQst);
		if (question == 0){
			return false;	
		}
	}
	
	//passa por todos os campos:
	for (i = 0; i < theForm.length; i++){
		//para cada campo, verifica se tem a tag frm_valid:
		validStr = theForm.elements[i].getAttribute('frm_valid');
		//para cada campo onde valida formato (cep, cpf, cnpj, email) verifica se tem a tag frm_obriga:		
		validObr = theForm.elements[i].getAttribute('frm_obriga');		

		if (!!validStr){
			frmObj = theForm.elements[i];
			frmObjName = theForm.elements[i].name;

			// VALIDAÇÃO DE CEP.
			// Essa rotina valida o formato do CEP. 
			// Se não for necessário validar a existencia do CEP, coloque frm_obriga = 'livre'

			if (validStr == 'cep'){
				
				var theCEP = frmObjName;
				var theCEP2 = frmObjName.split('_');				
				var theCEPNm = theCEP2[0]+'_';
				var CEP = theForm[theCEPNm+'1'].value+'-'+theForm[theCEPNm+'2'].value;

				if (CEP != '-'){
					if (CEP.substr(5,1) != '-'){
						alert('CEP inválido. Utilize o formato XXXXX-XXX');
						frmObj.focus();
						return (false)
					}
				} else {
					if (validObr != 'livre'){
						alert('Especifique o CEP');
						frmObj.focus();
						return (false)
					}
				}
				
				
			// VALIDAÇÃO DE LOGIN.

			} else if (validStr == 'login'){
				
				if (frmObj.value == ''){
					alert('Especifique o Login');
					frmObj.focus();
					return (false)
				}			
				
			// VALIDAÇÃO DE SENHA.				
				
			} else if (validStr == 'senha'){
				
				if (frmObj.value == ''){
					alert('Especifique a Senha');
					frmObj.focus();
					return (false)
				}
			
			// VALIDAÇÃO DE CPF.
			// Essa rotina valida o formato e a existencia do CPF. 
			// Se não for necessário validar a existencia do CPF, coloque frm_obriga = 'livre'
				
			} else if (validStr == 'cpf'){
				var theCpf = frmObjName;
				var theCpf2 = frmObjName.split('_');				
				var theCpfNm = theCpf2[0]+'_';
				var CPF = theForm[theCpfNm+'1'].value+''+theForm[theCpfNm+'2'].value+''+theForm[theCpfNm+'3'].value+''+theForm[theCpfNm+'4'].value;
				if (CPF != ''){
					res = validaCPF(CPF);
					if (res != ''){
						alert(res);
						frmObj.focus();
						return (false)
					}
				} else {
					if (validObr != 'livre'){
						alert('Especifique o CPF');
						frmObj.focus();
						return (false)
					}					
				}

			// VALIDAÇÃO DE CNPJ.
			// Essa rotina valida o formato e a existencia do CNPJ. 
			// Se não for necessário validar a existencia do CPF, coloque frm_obriga = 'livre'

			} else if (validStr == 'cnpj'){
				var theCnpj = frmObjName;
				var theCnpj2 = frmObjName.split('_');				
				var theCnpjNm = theCnpj2[0]+'_';
				var CNPJ = theForm[theCnpjNm+'1'].value+''+theForm[theCnpjNm+'2'].value+''+theForm[theCnpjNm+'3'].value+''+theForm[theCnpjNm+'4'].value+''+theForm[theCnpjNm+'5'].value;
				if (CNPJ != ''){
					res = validaCNPJ(CNPJ);
					if (res != ''){
						alert(res);
						frmObj.focus();
						return (false)
					}
				} else {
					if (validObr != 'livre'){
						alert('Especifique o CNPJ');
						frmObj.focus();
						return (false)
					}					
				}

			// VALIDAÇÃO DE E-MAIL.
			// Essa rotina valida o formato e a existencia do EMAIL. 
			// Se não for necessário validar a existencia do EMAIL, coloque frm_obriga = 'livre'

			} else if (validStr == 'email'){
				
				if (frmObj.value != ''){
					var str=frmObj.value;
					var at="@";
					var dot=".";
					var lat=str.indexOf(at);
					var lstr=str.length;
					var ldot=str.indexOf(dot);
					var erro = '';

					if (str.indexOf(at)==-1) erro = '1';
					if (erro == '' && str.substring(lstr-1,lstr) == dot)  erro = '1';
					if (erro == '' && str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) erro = '1';
					if (erro == '' && str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) erro = '1';
					if (erro == '' && str.indexOf(at,(lat+1))!=-1) erro = '1';
					if (erro == '' && str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) erro = '1';
					if (erro == '' && str.indexOf(dot,(lat+2))==-1) erro = '1';
					if (erro == '' && str.indexOf(" ")!=-1) erro = '1';
					if (erro == '1'){
						alert("E-mail inválido");
						frmObj.focus();
						return false
					}
				} else {
					if (validObr != 'livre'){
						alert('Especifique o E-mail');
						frmObj.focus();
						return (false)
					}
				}
			} else {
				//Aqui valida somente a existencia de valores em campos diversos: 	
				//recupera o tipo de campo
				frmTyp = theForm.elements[i].type;
				
				if (frmTyp == 'text' || frmTyp == 'password' || frmTyp == 'textarea'){
					if (frmObj.value == ''){
						if (validStr == '*'){
							alert('Especifique um valor para o campo "'+frmObjName+'"');	
						} else {
							alert(validStr);
						}
						frmObj.focus();
						return (false);
					}
				} else if (frmTyp == 'hidden'){
					if (frmObj.value == ''){
						if (validStr == '*'){
							alert('Especifique um valor para o campo "'+frmObjName+'"');	
						} else {
							alert(validStr);
						}
						return (false);
					}
				} else if (frmTyp == 'radio' || frmTyp == 'checkbox'){
					var noCheck = true;
					var radioGrp = theForm[frmObjName];
					if (radioGrp.length) {
						var max = radioGrp.length;
						for (var idx = 0; idx < max; idx++) {
							if (radioGrp[idx].checked) {
								noCheck = false;
							}
						}
					} else {
						if (radioGrp.checked) {
							noCheck = false;
						}
					}

					if (noCheck){
						if (validStr == '*'){
							alert('Especifique um valor para o campo "'+frmObjName+"'");	
						} else {
							alert(validStr);
						}
						frmObj.focus();
						return (false);
					}

				} else if (frmTyp == 'select-one'){
					if (frmObj.selectedIndex <= 0){
						if (validStr == '*'){
							alert('Especifique um valor para o campo "'+frmObjName+'"');	
						} else {
							alert(validStr);
						}
						frmObj.focus();
						return (false);
					}
				}
			}
		}
	}
	
	if(typeof valida_custom == 'function') { 
		return valida_custom(theForm); 
	} 
	
	return (true);
}


//SET FOCUS
function setFocus(valor, campo1, campo2){
	vcp1 = eval ('document.all.'+campo1);
	vcp2 = eval ('document.all.'+campo2);
	if (vcp1.value.length == valor){
		vcp2.focus();
	} 
}

function PararTAB(quem) { 
   VerifiqueTAB=false; 
} 

function ChecarTAB() { 
   VerifiqueTAB=true; 
} 
VerifiqueTAB=true;
function Mostra(quem, tammax) {
	if ( (quem.value.length == tammax) && (VerifiqueTAB) ) {
		var i=0,j=0, indice=-1;
		for (i=0; i<document.forms.length; i++) {
			for (j=0; j<document.forms[i].elements.length; j++) {
				if (document.forms[i].elements[j].name == quem.name) {
					indice=i;
					break;
				}
			}
			if (indice != -1)
		         break;
		}
		for (i=0; i<=document.forms[indice].elements.length; i++) {
			if (document.forms[indice].elements[i].name == quem.name) {
				while ( (document.forms[indice].elements[(i+1)].type == "hidden") &&
						(i < document.forms[indice].elements.length) ) {
							i++;
				}
				document.forms[indice].elements[(i+1)].focus();
				VerifiqueTAB=false;
				break;
			}
		}
	}
}


///////////////////////////////////////////
// validar CPF
///////////////////////////////////////////

function validaCPF(CPF){
	erro = new String;
	if (CPF.length > 0){
		if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
			CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
			CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
			CPF == "88888888888" || CPF == "99999999999"){
			erro = "CPF Inválido!";
		}
	
		soma = 0;
		for (i=0; i < 9; i ++)
			soma += parseInt(CPF.charAt(i)) * (10 - i);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)
			resto = 0;
		if (resto != parseInt(CPF.charAt(9))){
			erro = "CPF Inválido!";
		}
	
		soma = 0;
		for (i = 0; i < 10; i ++)
			soma += parseInt(CPF.charAt(i)) * (11 - i);
		resto = 11 - (soma % 11);
	
		if (resto == 10 || resto == 11)
			resto = 0;
	
		if (resto != parseInt(CPF.charAt(10))){
			erro = "CPF Inválido!";
		}
		if (erro.length > 0){
			return (erro);
		}
		return '';		
	}	
}

///////////////////////////////////////////
// validar CNPJ
///////////////////////////////////////////

function validaCNPJ(CNPJ) {
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! (xx.xxx.xxx/xxxx-xx) \n\n"; 
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! (xx.xxx.xxx/xxxx-xx)\n\n";
	}
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x; 
	} else {
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]); 
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="CNPJ Inválido!";
	}
	if (erro.length > 0){
		return (erro);
	//} else {
	//	alert("CNPJ valido!");
	}
	return '';
}


///////////////////////////////////////////
// formatar coampo de moeda
///////////////////////////////////////////
function formatCurrency(num) {
	num = num.toString().replace(/\$|\./g,'');
	num = num.toString().replace(/\$|\,/g,'.');	
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + ',' + cents);
}


var divPosY = 0;
function divPos(act, divScroll){
	if (act == 'set'){
		divPosY = document.getElementById('divList').scrollTop;
		document.getElementById('divPosYfrm').value = divPosY;		
	} else if (act == 'get'){
		setTimeout("document.getElementById('divList').scrollTop = "+divScroll, 500);
	}
}

//AUTO FORM
function autoForm(frmAct, frmTrg, frmCps, frmVlr){
	if (document.getElementById('divAutoForm')){
		document.getElementById('divAutoForm').innerHTML = '<form name="autoForm" method="POST"></form>'
		var oFrm = document.autoForm;
		if (!frmTrg) {frmTrg = '_self'};
		oFrm.target = frmTrg;
		oFrm.action = frmAct;		
		oFrm.method = 'POST';		
		if (frmCps != ''){
			if (frmCps.indexOf('|') >= 0){
				var frmCpsArr = frmCps.split('|');
				var frmVlrArr = frmVlr.split('|');
				if (frmCpsArr.length != frmVlrArr.length){
					alert ("Número de campos não coincide com número de valores.");
					return false;
				} else {
					for (zCp=0;zCp < frmCpsArr.length;zCp++){
						oFrmHtml = oFrm.innerHTML;
						oFrm.innerHTML = oFrmHtml+'<input type="hidden" name="'+frmCpsArr[zCp]+'" value="'+frmVlrArr[zCp]+'">';
					}
				}
			} else {
				oFrm.innerHTML = '<input type="hidden" name="'+frmCps+'" value="'+frmVlr+'">';				
			}
		}
		oFrm.submit();
	} else {
		alert ('Objeto autoForm inexistente.');
		return false;
	}
}
