///////////////////////////////////////////
// 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 "/"');

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
///////////////////////////////////////////
// BASTA incluir uma tag frm_valid="texto que ser apresentado" no form object.
function valida(theForm){
	for (i = 0; i < theForm.length; i++){
		validStr = theForm.elements[i].frm_valid;
		if (!!validStr){
			if (validStr == 'cep'){
				frmObj = theForm.elements[i];
				if (frmObj.value == ''){
					alert('Especifique o CEP');
					frmObj.focus();
					return (false)					
				} else if (frmObj.value.lenght < 9 || frmObj.value.substr(5,1) != '-'){
					alert('CEP inválido. Utilize o formato XXXXX-XXX');
					frmObj.focus();
					return (false)															
				}
			} else if (validStr == 'email'){
				frmObj = theForm.elements[i];
				if (frmObj.value == ''){
					alert('Especifique o E-mail');
					frmObj.focus();
					return (false)					
				} else {				
				
					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 {
				frmObj = theForm.elements[i];
				frmTyp = theForm.elements[i].type;		
				if (frmTyp == 'text' || frmTyp == 'password' || frmTyp == 'textarea'){
					if (frmObj.value == ""){
						alert(validStr);
						frmObj.focus();
						return (false);
					}
				} else if (frmTyp == 'select-one'){
					if (frmObj.selectedIndex <= 0){
						alert(validStr);
						frmObj.focus();
						return (false);
					}
				}			
			}
		}
	}
	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;
			}
		}
	}
}


///////////////////////////////////////////
// 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);
}

///////////////////////////////////////////
// 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 '';
}

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);
	}
}

