function valida_texto(id, nome)
{
	var ret = "";
	if(document.getElementById(id))
	{
		if(document.getElementById(id).value == "")
		{
			ret = "Por favor, preencha o campo ["+nome+"].";
		}
	}

	return ret;

}

function valida_select(id, nome)
{
	var ret = "";
	if(document.getElementById(id))
	{
		if(document.getElementById(id).value == 0)
		{
			ret = "Por favor, selecione um ["+nome+"].";
		}
	}

	return ret;
}

function valida_senha(senha, senha_conf, nome)
{
	var ret = "";
	if(document.getElementById(senha))
	{
		if(document.getElementById(senha).value == "")
		{
			ret = "Por favor, preencha o campo ["+nome+"].";
		}
		else if(document.getElementById(senha).value != document.getElementById(senha_conf).value)
		{
			ret = "Senha não confere. Por favor, confirme se sua senha foi digitada corretamente.";
		}

	}

	return ret;
}

String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function valida_email(id)
{
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

	var ret = "";
	if(document.getElementById(id))
	{
		var email = document.getElementById(id).value;

		if(typeof(email) == "string" || typeof(email) == "object")
		{
			if(!er.test(email))
			{
				ret = "Por favor, verifique o Email.";
			}
		}
	}

	return ret;

}

function marca_desmarca_linha(td, controle)
{
	var color = '#C9DFCC';

	if(controle == 0 && td.id == '')
	{
		color='';
	}

	if(controle == 2)
	{
		if(td.id == '')
		{
			td.id = '_marcado';
		}
		else
		{
			td.id = '';
		}
	}

	var obj = td;

	while(obj.previousSibling)
	{
		obj = obj.previousSibling;
		if(obj.tagName=='TD')
		{
			obj.style.background = color;
			if(controle == 2)
			{
				if(obj.id == '')
				{
					obj.id = '_marcado';
				}
				else
				{
					obj.id = '';
				}
			}

		}
	}

	obj = td;
	while(obj.nextSibling)
	{
		obj = obj.nextSibling;
		if(obj.tagName=='TD')
		{
			obj.style.background = color;
			if(controle == 2)
			{
				if(obj.id == '')
				{
					obj.id = '_marcado';
				}
				else
				{
					obj.id = '';
				}
			}
		}
	}

	td.style.background = color;
}

function valida_data(id,nome)
{
	if(!document.getElementById(id))
	{
		return '0';
	}

	var ret = "";
	var data = document.getElementById(id).value;

	if(data != "00/00/0000" && data.length == 10)
	{
		var vet_data = data.split("/");
		if(vet_data.length == 3)
		{
			var dia = vet_data[0];
			var mes = vet_data[1];
			var ano = vet_data[2];

			var fim_mes = [];
			fim_mes[1] = 31;
			fim_mes[2] = 28;
			fim_mes[3] = 31;
			fim_mes[4] = 30;
			fim_mes[5] = 31;
			fim_mes[6] = 30;
			fim_mes[7] = 31;
			fim_mes[8] = 31;
			fim_mes[9] = 30;
			fim_mes[10] = 31;
			fim_mes[11] = 30;
			fim_mes[12] = 31;

			if(ano%4 == 0)
				fim_mes[2] = 29;

			if ((mes*1) > 12)
			{
				mes = 12;
			}
			if ( dia > fim_mes[(mes*1)] )
			{
				dia = fim_mes[(mes*1)];
			}

			document.getElementById(id).value = dia+"/"+mes+"/"+ano;
		}
	}
	else
	{
		ret = "Por favor, verifique o campo ["+nome+"].";
	}

	return ret;
}

function InicializarIndices()
{
	return;
	if (document.CargaInicial==null)
	{
		document.CargaInicial=false;		// Seta para só fazer uma vez por documento
		var ctrlAnterior=null;
		var IndAnt=0;
		for ( var i=0; i < document.forms[0].elements.length; i++)
		{
			var e=document.forms[0].elements[i];
			if ( e.type!="hidden" && e.type!="image" )
			{
				if ( ctrlAnterior != null )
					ctrlAnterior.IndicePosterior=i;
				ctrlAnterior=e;
				e.Indice=i;
				e.IndiceAnterior=IndAnt;
			}
		}
		//if ( ctrlAnterior!=null )
		//{
		//	ctrlAnterior.IndicePosterior=i-1;
		//}
	}
}

// Verificar qual navegador
function QualNavegador()
{
	var s = navigator.appName;
	if ( s == "Microsoft Internet Explorer" )
		return "IE";
	else if ( s == "Netscape" )
		return "NE";
	else
		return "";
}

// Verificar qual a versão do navegador
function QualVersao()
{
	var s = navigator.appVersion;
	if ( QualNavegador() == "IE" )
	{
		var i = s.search("MSIE");
		s=s.substring(i+5);
		i=s.search(".");
		return parseInt(s.substring(0,i+1));
	}
	else if ( QualNavegador() == "NE" )
		return parseInt(s.substring(0,1));
	else
		return 0;
}

var dicionario_caracter = "";

function ValidaCampo(ctrl, tam, tipo, autoSkip, caracteres){

	dicionario_caracter = caracteres;

	var s = QualNavegador();
	if (s.length == 0)
		return;
	if ((s == "IE") && (QualVersao() > 6))
		return;
	if ((s == "NE") && (QualVersao() > 5))
		return;

	if (ctrl.onkeypress==null){
		if (autoSkip==null)
			autoSkip=true;
		if (tipo!=null)
			tipo.toUpperCase();
		ctrl.tam=tam;
		ctrl.tipo=tipo;
		ctrl.autoSkip=true;
		ctrl.Saltar=false;
		InicializarIndices();
		ctrl.onkeypress = ValidarTecla;
	}
}


function CorrigeCampo(campo, tipo, caracteres){
	var texto = campo.value;
	var texto_limpo = "";
	var pode = true;
	var c;

	for (var i=0; i < texto.length; i++){
		pode = true;

		tk = texto.charCodeAt(i);

		switch (tipo){
			case "D": // Digitos
				if ((tk < 48) || (tk > 57))
					pode = false;
			break;
			case "V": // Digitos separados por virgula
			case "M": // Digitos separados por virgula
				if (((tk < 48) || (tk > 57)) && (tk != 44) && (tk != 45)) //48 = 0, 57 = 9, 44 = , e 45 = -
					pode = false;
				if ((tk == 44)){
					while(substr_count(texto, ',') > 1){
						var pos = texto.search(',');
						texto = texto.substring(0, pos)+texto.substring(pos+1, texto.length);
						if(pode)
							i--;
						pode = false;
					}
				}
			break;
			case "P": // Digitos separados por ponto
//				alert("quantos: "+this.value.search(","));
				if (((tk < 48) || (tk > 57)) && (tk != 46) && (tk != 45))
					pode = false;
//		if ((tk == 46) && ((this.value.search(".") > 0) || (this.value.length==0))){ naum funfo
				if ((tk == 46)){
					while(substr_count(texto, '.') > 1){
						var pos = retorna_pos(texto, '.');
						texto = texto.substring(0, pos)+texto.substring(pos+1, texto.length);
						if(pode)
							i--;
						pode = false;
					}
				}
			break;
			case "C": // Letras
				if ((tk > 96) && (tk < 123)) //97 = a && 122 = z
					tk = tk - 32;
				if(!((tk > 64) && (tk < 91)) && (tk != 32))
					pode = false;
			break;
			case "Dt": // Datas
				if (((tk < 48) || (tk > 57)) && (tk != 47))
					pode = false;
				else{
					if(tk == 47) {
						switch(texto_limpo.length){
							case 1:
								texto_limpo = "0"+texto_limpo.slice(0,1);
							break;
							case 4:
								texto_limpo = texto_limpo.slice(0,3)+"0"+texto_limpo.slice(3,4);
							break;
							case 2:
							break;
							case 5:
							break;
							default :
								pode = false;
						}
					}
					else{
						if((texto_limpo.length == 2) || (texto_limpo.length == 5))
							texto_limpo += "/";
					}
				}
				if(texto_limpo.length > 9)
					pode = false;
			break;
			case "AN": // Alpha Numerico
				if ((tk > 96) && (tk < 123)) //97 = a && 122 = z
					tk = tk - 32;
				if(!(((tk > 47) && (tk < 58)) || ((tk > 64) && (tk < 91))) && (tk != 32)) // Valido p/ numeros e letras
					pode = false;
			break;
			case "AX": // Alpha Numerico completo acentos ï¿?e outros
				if((tk < 42) || ( (tk > 90) && (tk < 97) ) || (tk > 122) && ((tk > 146) && (tk < 152)) )
				{
					if( (tk!=231) && (tk!=94) && (tk!=95) && (tk!=227) && (tk!=245) && (tk!=32))
					{
						pode = false;
					}
				}
			break;
			case "CNPJ": // para arquivos c/ numeros, ".", "/", "-"
				if ((tk < 45) || (tk > 57))
					pode = false;
			break;
			case "Dic": // os caracteres possiveis sao determinados pela variavel caracteres
				c = String.fromCharCode(tk);
				if(caracteres.search(c) < 0){
					pode = false;
				}
			break;
			case "NDic": // os caracteres descartados sao determinados pela variavel caracteres
				c = String.fromCharCode(tk);
				if(caracteres.search(c) > -1){
					pode = false;
				}
			break;
		}

		if(pode){
			texto_limpo += texto.charAt(i);
		}
	}
	if(tipo == "M")
		texto_limpo = format(unformat(texto_limpo));

	campo.value = texto_limpo;
}

// Setar o evento
function SetarEvento(ctrl, Tam, Tipo, AutoSkip )
{
	// Filtra navegadores conhecidos
	var s = QualNavegador();

	if (s.length == 0)
		return;
	if ((s == "IE") && (QualVersao() > 8))
		return;
	if ((s == "NE") && (QualVersao() > 5))
		return;

	if (ctrl.onkeypress==null)
	{
		if (AutoSkip==null)
			AutoSkip=true;
		if (Tipo!=null)
			Tipo.toUpperCase();
		ctrl.tam=Tam;
		ctrl.tipo=Tipo;
		ctrl.autoSkip=true;
		ctrl.Saltar=false;
		InicializarIndices();
		ctrl.onkeypress=ValidarTecla;
	}
}

function SaltarCampo(ctrl)
{
	if (ctrl==null)
		ctrl=this;
	if ( ctrl.AutoSkip && ctrl.Saltar)
		if (ctrl.Saltar)
		{
			ctrl.Saltar=false;
			if ( ctrl.IndicePosterior != null )
				SetarFoco(ctrl.IndicePosterior);
		}
}

function ValidarTecla (evnt){
	var tk;
	var c;

	tk = ( (QualNavegador()=="IE") ? event.keyCode : evnt.which);

	// Sï¿?aceita teclas alfanumï¿?icas. Nï¿? aceita teclas de controle
	if (tk < 32)
		return true;
/*
		if (tk > 127)
			return false;
*/
//alert(tk);

	switch (this.tipo){
		case "D": // Digitos
			if ((tk < 48) || (tk > 57))
				return false;
		break;
		case "V": // Digitos separados por virgula
		case "M": // Digitos separados por virgula
			if (((tk < 48) || (tk > 57)) && (tk != 44) && (tk != 45)) //48 = 0, 57 = 9, 44 = , e 45 = -
				return false;
			if ((tk == 44) && ((this.value.search(",") > -1) || (this.value.length == 0)))
				return false;
			if ((tk == 45) && (this.value.search("-") > -1)){
				return false;
			}
			else{
				if(tk == 45){
					this.value = "-"+this.value;
					return false;
				}
			}
		break;
		case "P": // Digitos separados por ponto
//			alert("quantos: "+this.value.search(","));
			if (((tk < 48) || (tk > 57)) && (tk != 46) && (tk != 45))
				return false;
//		if ((tk == 46) && ((this.value.search(".") > 0) || (this.value.length==0))){ naum funfo
			if ((tk == 46) && ((retorna_pos(this.value, '.') > -1) || this.value.length==0)){
				return false;
			}
			if ((tk == 45) && (this.value.search("-") > -1)){
				return false;
			}
			else{
				if(tk == 45){
					this.value = "-"+this.value;
					return false;
				}
			}
		break;
		case "C": // Letras
			if ((tk > 96) && (tk < 123)) //97 = a && 122 = z
				tk = tk - 32;
			if(!((tk > 64) && (tk < 91)) && (tk != 32))
				return false;
		break;
		case "CEP": // Datas
			if ((tk < 48) || (tk > 57))
				return false;
			else
			{
				if(this.value.length == 2)
				{
					this.value += ".";
				}

				if( this.value.length == 6)
				{
					this.value += "-";
				}
			}
		break;
		case "Dt": // Datas
			if (((tk < 48) || (tk > 57)) && (tk != 47))
				return false;
			else
				if(tk == 47) {
					switch(this.value.length){
						case 1:
							this.value = "0"+this.value.slice(0,1);
						break;
						case 4:
							this.value = this.value.slice(0,3)+"0"+this.value.slice(3,4);
						break;
						case 2:
						break;
						case 5:
						break;
						default :
							return false;
					}
				}
				else
					if((this.value.length == 2) || (this.value.length == 5))
						this.value += "/";
		break;
		case "TEL": // Telefone
			if (((tk < 48) || (tk > 57)) && (tk != 40) && (tk != 41))
				return false;
			else
			{
				switch(tk)
				{
					case 40:
						if(this.value.length != 0)
						return false;
					break;
					case 41:
						if(this.value.length != 3)
						return false;
					break;
					default :
						if(this.value.length == 4)
						this.value += "-";
				}
			}
		break;
		case "AN": // Alpha Numerico
			if ((tk > 96) && (tk < 123)) //97 = a && 122 = z
				tk = tk - 32;
			if(!(((tk > 47) && (tk < 58)) || ((tk > 64) && (tk < 91))) && (tk != 32)) // Valido p/ numeros e letras
				return false;
		break;
		case "AX": // Alpha Numerico completo acentos ï¿?e outros
			if((tk < 42) || ( (tk > 90) && (tk < 97) ) || (tk > 122) && ((tk > 146) && (tk < 152)) )
			{
				if( (tk!=231) && (tk!=94) && (tk!=95) && (tk!=227) && (tk!=245) && (tk!=32))
				{
					return false;
				}
			}
		break;
		case "CNPJ": // para arquivos c/ numeros, ".", "/", "-"
			if ((tk < 45) || (tk > 57))
				return false;
		break;
		case "Dic": // os caracteres possiveis sao determinados pela variavel dicionario_caracter
			c = String.fromCharCode(tk);
			if(dicionario_caracter.search(c) < 0){
				return false;
			}
		break;
		case "NDic": // os caracteres descartados sao determinados pela variavel dicionario_caracter
			c = String.fromCharCode(tk);
			if(dicionario_caracter.search(c) > -1){
				return false;
			}
		break;
	}

	if(this.Tam != 0)
		this.Saltar=(QualNavegador()=="IE")? (this.value.length>this.Tam-1) : (this.value.length>this.Tam-2);
		if(this.Saltar)
			SaltarCampo(this);

	return true;
}

function corrige_texto(campo, tipo){
	var texto = campo.value;
	var texto_limpo = "";
	var pode = true;

	for (var i=0; i < texto.length; i++){
		pode = true;
		// pega o char da string
		// texto.charAt(i)
		// pega o ASCII do char da string
		tk = texto.charCodeAt(i);

		switch (tipo){
			case "D": // Digitos
				if ((tk < 48) || (tk > 57))
					pode = false;
			break;
			case "V": // Digitos separados por virgula
			case "M": // Digitos separados por virgula
				if (((tk < 48) || (tk > 57)) && (tk != 44) && (tk != 45)) //48 = 0, 57 = 9, 44 = , e 45 = -
					pode = false;
				if ((tk == 44)){
					while(substr_count(texto, ',') > 1){
						var pos = texto.search(',');
						texto = texto.substring(0, pos)+texto.substring(pos+1, texto.length);
						if(pode)
							i--;
						pode = false;
					}
				}
			break;
			case "P": // Digitos separados por ponto
//				alert("quantos: "+this.value.search(","));
				if (((tk < 48) || (tk > 57)) && (tk != 46) && (tk != 45))
					pode = false;
//		if ((tk == 46) && ((this.value.search(".") > 0) || (this.value.length==0))){ naum funfo
				if ((tk == 46)){
					while(substr_count(texto, '.') > 1){
						var pos = retorna_pos(texto, '.');
						texto = texto.substring(0, pos)+texto.substring(pos+1, texto.length);
						if(pode)
							i--;
						pode = false;
					}
				}
			break;
			case "C": // Letras
				if ((tk > 96) && (tk < 123)) //97 = a && 122 = z
					tk = tk - 32;
				if(!((tk > 64) && (tk < 91)) && (tk != 32))
					pode = false;
			break;
			case "Dt": // Datas
				if (((tk < 48) || (tk > 57)) && (tk != 47))
					pode = false;
				else{
					if(tk == 47) {
						switch(texto_limpo.length){
							case 1:
								texto_limpo = "0"+texto_limpo.slice(0,1);
							break;
							case 4:
								texto_limpo = texto_limpo.slice(0,3)+"0"+texto_limpo.slice(3,4);
							break;
							case 2:
							break;
							case 5:
							break;
							default :
								pode = false;
						}
					}
					else{
						if((texto_limpo.length == 2) || (texto_limpo.length == 5))
							texto_limpo += "/";
					}
				}
				if(texto_limpo.length > 9)
					pode = false;
			break;
			case "AN": // Alpha Numerico
				if ((tk > 96) && (tk < 123)) //97 = a && 122 = z
					tk = tk - 32;
				if(!(((tk > 47) && (tk < 58)) || ((tk > 64) && (tk < 91))) && (tk != 32)) // Valido p/ numeros e letras
					pode = false;
			break;
			case "AX": // Alpha Numerico completo acentos ï¿?e outros
				if((tk < 42) || ( (tk > 90) && (tk < 97) ) || (tk > 122) && ((tk > 146) && (tk < 152)) )
				{
					if( (tk!=231) && (tk!=94) && (tk!=95) && (tk!=227) && (tk!=245) && (tk!=32))
					{
						pode = false;
					}
				}
			break;
			case "CNPJ": // para arquivos c/ numeros, ".", "/", "-"
				if ((tk < 45) || (tk > 57))
					pode = false;
			break;
		}

		if(pode){
			texto_limpo += texto.charAt(i);
		}
	}
	if(tipo == "M")
		texto_limpo = format(unformat(texto_limpo));

	campo.value = texto_limpo;
}

function substr_count(str_original, find)
{
	num_ocorrencia = 0;
	str = str_original;
	while ( retorna_pos(str, find) != -1 )
	{
		num_ocorrencia++;
		str = str.substring(retorna_pos(str, find) + find.length, str.length);
	}
	return num_ocorrencia;
}

function retorna_pos(str_original, find)
{
	for (var i=0; i<str_original.length; i++)
	{
		if (str_original.substring(i, i+1) == find)
		{
			return i;
		}
	}
	return -1
}

function format(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";

	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var 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);
}

function unformat(num)
{
	num = num.replace(/\$|\./g,'');
	num = num.replace(/\$|\,/g,'.');
	return num;
}

function format_inteiro(num)
{
	num = num.toString();
	var tam = num.length;
	if(isNaN(num))
		num = "0";

	sign = (num == (num = Math.abs(num)));

	num = Math.floor(num).toString();

	var falta = tam - num.length;
	if (!sign)
	{
		falta--;
	}
	while (falta > 0)
	{
		num = "0"+num;
		falta--;
	}

	return (((sign)?'':'-')+num);
}

function unformat_inteiro(num)
{
	return format_inteiro(num);
}

// Fazer o salto de campo
function __ValidarTecla (evnt)
{
	var tk;
    var c;
	// Recebe a tela pressionada
	tk = ( (QualNavegador()=="IE") ? event.keyCode : evnt.which);
    c=String.fromCharCode(tk);
	c=c.toUpperCase();

	// -- Este trecho faz com que o <Enter> tenha a função de <Tab>, mas acho inviável, pois não é possível
	//       colocar o foco em campos do Tipo "image", e, neste caso, nunca seria possível fazer a submissão
	//       do formulário
	// if ( tk == 13 )
	// {
	//	this.Saltar=true;
	//	SaltarCampo(this);
	//	return false;
	// }

	// Só aceita teclas alfanuméricas. Não aceita teclas de controle
    if ( tk < 32 )
		return true;

	switch ( this.Tipo )
	{
	case "M":
		if ( c<"0" || c>"9" )
			return false;
		break;
	case "N":
		if ( (c<"0" || c>"9") && (c!=",") && (c!=".") )
			return false;
		if ( (c==",") && ((this.value.search(",")>-1) || (this.value.length==0)) )
			return false;
		break;
	case "P":
		if ( (c<"0" || c>"9") && (c!=".") )
			return false;
		if ( (c==",") && ((this.value.search(",")>-1) || (this.value.length==0)) )
			return false;
		break;
	case "C":
		if ( c<"A" || c>"Z" )
			return false;
		break;
	default:
		break;
	}

	this.Saltar=(this.value.length==this.Tam-1);
	if ( ((QualNavegador()=="IE") && QualVersao()<5) || (QualNavegador()!="IE") )
		SaltarCampo(this);

	return true;
}

//Funcao Semelhante ao document.getElementById();
function $()
{
	var elements = new Array();
	var x = arguments.length;
	for (var i=0; i < x; i++)
	{
		var element = arguments[i];
		if (typeof element.toLowerCase() == 'string')
		{
			element = document.getElementById(element);
		}
		if (arguments.length == 1)
		{
			return element;
		}
		elements.push(element);
	}
}
//	cria_elemento ("pai", "elemento", "name", "valores", "innerHTML");
/*
func?o que faz a cria?o din?ica de um componente html
*/
function cria_elemento (pai, elemento, name, valores, inner)
{
	var nome = (name != "")? " name = '"+name + "' id = '"+name+"'" : "";

	if(valores.search("'radio'") != -1)
		elemento = "radio";
/*
if(elemento == "radio")
	alert(QualNavegador()+" "+elemento+" "+name);
*/

	if(QualNavegador() == "IE"){
		switch(elemento){
			case "radio":
				var aux = document.createElement("<input name = '"+name+"' type = 'radio' id = '"+inner+"' "+valores+">");
			break;
			default:
				var aux = document.createElement("<"+elemento+" "+nome+" "+valores+">");
		}
	}
	else{
		switch(elemento){
			case "tr":
				var aux = document.createElement(elemento);
				aux.id = name;
				aux.name = name;
			break;
			case "option":
				var aux = document.createElement(elemento);
				aux.id = name;

				if(valores.search("selected") != -1){
					aux.selected = true;
				}

				if(valores.search("value") != -1){
					valores = valores.substr(valores.search("value"));
					valores = valores.substr(valores.search("="));
					valores = valores.substr(valores.search("'")+1);
					valores = valores.substring(0, valores.search("'"));
				}
				aux.value = valores;
			break;
			case "radio":
				pai.innerHTML += "<input name = '"+name+"' type = 'radio' id = '"+inner+"' "+valores+">";
				var aux = document.getElementById(inner);
			break;
			default:
				pai.innerHTML += "<"+elemento+" "+nome+" "+valores+">";
				var aux = document.getElementById(name);
		}
	}

	if(inner != "" && elemento != "radio"){
		aux.innerHTML += inner;
	}

	pai.appendChild(aux);

	return aux;
}

function remove_elemento(nom_obj, pergunta)
{
	this.ret = true;

	var tr = document.getElementById(nom_obj);

	if (pergunta != "" && tr)
	{
		if (confirm(pergunta))
		{
			tr.parentNode.removeChild(tr);
		}
		else
		{
			this.ret = false;
		}
	}
	else
	{
		tr.parentNode.removeChild(tr);
	}
	return this.ret;
}
