var msgCampoVazio = "Por favor preencha o campo ";

// passar somente nome do formulario.
// pega todos texts e verifica se s�o vazios - APENAS TEXTS
function verificaTextVazio(formulario) {
	var elementos = formulario.elements.length;
	for (i = 0;i<elementos;i++) 
		{
			if (formulario.elements[i].value == '' && formulario.elements[i].type == 'text') 
			{
				alert('Por gentileza preencha o campo ' + formulario.elements[i].title + ' para continuar');
				formulario.elements[i].focus();
				return false;
			}
		}	
}
// passar como document.getElement. Valida email.

function validaEmailBO (email) {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))) {
			return false;
		}
		return true;
}
function verificaVazio(obj) {
	if (obj.value == "") {
		alert('Aten��o:\n Campo '+obj.name+' n�o pode estar em branco.');
		obj.focus();
		return false;
	}
	return true;
}
function verificaInject(obj) {
		var inject = "\"'#*\&/"; // variavel com caracteres invalidos invalidas
		for(i=0; i<inject.length; i++)
		{
			if(obj.value.indexOf(inject.charAt(i)) >= 0)
			{
			alert("Car�cteres inv�lidos no campo ''"+obj.name+"'',\n favor corrigir. (Ex.\",',#,*,\\,& e /)");
			obj.focus();
			return false;
			}
		}
		return true;
}

function verificaNumero(texto)
{
	var checkOK = "0123456789";
	var checkStr = texto;
	var allValid = true;
	for (i = 0; i < checkStr.length; i++) {
		ch = checkStr.charAt(i);
		for (j = 0; j < checkOK.length; j++)
			if (ch == checkOK.charAt(j))
			break;
			if (j == checkOK.length) {
				allValid = false;
				break;
			}
		}
		if (!allValid) {
			return (false);
		}
		return true;
}
// verifica se o arquivo tem a extens�o solicitada
// passar vazio 1 se quiser que verifique se est� vazio tamb�m
function verificaExtensao(obj,exts,vazio) {
	var pos;
	var ext;
	if (obj.value == '' && vazio == 1) {
		return false;
	}
	pos = obj.value.lastIndexOf('.'); 	
	ext = obj.value.substring(pos+1,obj.value.length);
	if (exts.indexOf(ext) == -1) {
		return false;
	}
	return true;
}
// verifica se o campo Atual tem Chars caracteres, se tiver vai para PARA
function mudaPara(atual,para,chars) {
	var para = document.getElementById(para);
	if (atual.value.length >= chars) {
		para.focus();
	}
} 
// muda campos do formul�rio para inativos se for 0 e ativos se for 1
function mudaCampos(formulario,acao)
{
	var action
	action = acao == '0'?true:false;
	for (i = 0; i < formulario.length; i++)
	{
		formulario.elements[i].disabled = action;	
	}
}

function moveList(origem,destino,limite) {
	dest 	= 	document.getElementById(destino);
	orig	=	document.getElementById(origem);
	if (document.getElementById(origem).value == '') {
		return false;
	}
	else {
		if (limite == '' || dest.length < limite) {
			txt 	=	document.getElementById(origem).options[document.getElementById(origem).selectedIndex].text;
			valor 	= 	document.getElementById(origem).value;
			orig.options[orig.selectedIndex] = null;
			dest.options[dest.length] = new Option(txt,valor);
		}
		else {
			alert('Este campo permite no m�ximo '+limite+' �tens');
		}
	}
}

function removeTodosOptions(selectName) {
  var selecte = document.getElementById(selectName);
  for (var i = selecte.options.length-1; i>=0; i--) {
      selecte.options[i] = null;
  }
  addList("-","","listaEnviados");
}


function remList(origem) {
	orig	=	document.getElementById(origem);
	orig.options[orig.selectedIndex] = null;
}

function remSelectedList(origem) {
	orig	=	document.getElementById(origem);
	if (orig.options != null) {
		for (var i=(orig.options.length-1); i>=0; i--) { 
			var o=orig.options[i]; 
			if (o.selected) { 
				orig.options[i] = null; 
			} 
		}
		orig.selectedIndex = -1; 
	}
}

function limpaList(list,limite)
{
	listbox = document.getElementById(list);
	for (i = listbox.length;i >= limite; i--) {
		listbox.options[i] = null;
	}
}

function addList(texto,valor,destino) {
	var dest 	= 	document.getElementById(destino);
	dest.options[dest.length] = new Option(texto,valor);
}

// passar o no e o valor caso seja vazio.
function validaNoXml(no,valor)
{
	if (no.firstChild == null) return valor; 
	else 
	{
		if (no.childNodes.length > 1)
		{
			var texto = '';
			for (c = 0; c < no.childNodes.length; c++)
            {
                texto += no.childNodes[c].data;
            }
			return texto;
		}
		else
			return no.firstChild.nodeValue;
	}
}


/* funcoes para controle das janelas */
function limpaJanelas()
{
	try 
	{
		confirma.acaoSim 		= null;
		confirma.acaoSimParam 	= null;
		confirma.mensagem 		= null;
	}
	catch(e) {}
	try
	{
		alerta.mensagem 		= null;
		alerta.tempoMensagem 	= null;
	}
	catch(e){}
	try
	{
		ok.mensagem 			= null;
		ok.tempoMensagem 		= null;
	}
	catch(e) {}
}

function validacao(campo,msg)
{
	limpaJanelas();
	alerta.mensagem 		= msg;
	alerta.acaoSim			= 'focoJan';
	alerta.acaoSimParam		= campo;
	alerta.popup();
	return false;
}

//function alert(msg) {
//	limpaJanelas();
//	alerta.mensagem 		= msg;
	//alerta.tempoMensagem 	= 3;
//	alerta.popup();
//	return false;	
//}

function validaData(data)
{
	var reDate = /^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)?\d{4}$/;
	if (reDate.test(data)) {
		return true;
	} if (data != null && data != "") {
		return false;
	}
}
// data dd/mm 
function validaDataResumida(dados) {
	var er = /([012][0-9]|3[01])\/[01][0-9]/;
	if (er.test(dados)) {
		return true;
	} if (dados != null && dados != "") {
		return false;
	}
} 
function validaHora(hora)
{
	var reHora = /^([0-1]\d|2[0-3]):[0-5]\d$/;
	if (reHora.test(hora)) {
		return true;
	} 
	else if (hora != null && hora != "") {
		return false;
	}
}

// passar hora inicial, minuto inicial, segundos iniciais (nao obrigatorio), hora final, minutos finais, segundos finais
// retorna em SEGUNDOS, para minutos dividir por 60
function diferencaHora(h,m,s,hf,mf,sf)
{
	s 	= s == null?0:s;
	sf 	= sf == null?0:sf;
	
	var data1 = new Date(0,0,0,h,m,0);
	var data2 = new Date(0,0,0,hf,mf,0);
	return ((data2-data1)/1000);
}
// dia/mes/ano, dia/mes/ano finais
function diferencaData(dataIn,dataEn)
{
	dataIn 		= dataIn.split('/');
	dataEn		= dataEn.split('/');
	var data1 = new Date(dataIn[2],(dataIn[1]-1),dataIn[0],0,0,0);
	var data2 = new Date(dataEn[2],(dataEn[1]-1),dataEn[0],0,0,0);
	return ((data2-data1)/1000);
}
// data em formato d/m/a h m s
function diferencaDateTime(dataIn,h,m,s,dataEn,hf,mf,sf)
{
	dataIn 		= dataIn.split('/');
	dataEn		= dataEn.split('/');
	var data1 = new Date(dataIn[2],dataIn[1]-1,dataIn[0],h,m,s);
	var data2 = new Date(dataEn[2],dataEn[1]-1,dataEn[0],hf,mf,sf);
	return ((data2-data1)/1000);
}

function verificaRadio(obj)
{
	for(var i = 0; i < obj.length; i++)
	if (obj[i].checked)  return obj[i].value;
}

function aguarde(param) {
	//var acao = param == true?loading.popup():loading.fechar();
}

function validacao(campo,msg)
{
	limpaJanelas();
	alerta.mensagem 		= msg;
	alerta.acaoSim			= 'focoJan';
	alerta.acaoSimParam		= campo;
	alerta.popup();
	return false;
}

/* get element by id */
function gE(elemento) {
	return document.getElementById(elemento);
}

var campoCidade;
var caminhoLib;
var timeOutCidade;
function listaCidades(valor,objCidades,lib) {
	caminhoLib = lib;
	campoCidade= objCidades;
	try { clearTimeout(timeOutCidade) } catch(e) {}
	if (valor != '-') {
		timeOutCidade 	= setTimeout("executar('"+caminhoLib+"addons/xmlCidades.php','estado="+valor+"',listaCidadesRe)",1000);
		gE(objCidades).options[0].text	= 'Aguarde...';
	}
	else {
		gE(objCidades).options[0].text	= 'Selecione um estado';
	}
	gE(objCidades).disabled = true;
	gE(objCidades).options[0].value = '-';
	limpaList(objCidades,1);
}
function listaCidadesRe() {
	if (xhReq.readyState == 4) {
		if (xhReq.status == 200) {
			var obj = xhReq.responseXML.getElementsByTagName('cidades')[0];
			if (obj) {
				var cidade = obj.getElementsByTagName('cidade');
				gE(campoCidade).options[0].text	= 'Selecione...';
				for(i = 0; i < cidade.length; i++) {
					addList(unescape(cidade[i].getAttribute('nome')),cidade[i].getAttribute('id'),campoCidade)
				}
				gE(campoCidade).disabled = false;
			}
			else
				alert("ERRO ao buscar cidades. Por favor contate o administrador do sistema.");
		}
		else {
			alert("ERRO ao buscar cidades. Por favor contate o administrador do sistema.");
		}
	}
}


/**
 * String unformatNumber(String pNum)
 * String formatCpfCnpj(String pCpfCnpj, boolean pUseSepar, boolean pIsCnpj)
 * String dvCpfCnpj(String pEfetivo, boolean pIsCnpj)
 * boolean isCpf(String pCpf)
 * boolean isCnpj(String pCnpj)
 * boolean isCpfCnpj(String pCpfCnpj)
 */

var NUM_DIGITOS_CPF  = 11;
var NUM_DIGITOS_CNPJ = 14;
var NUM_DGT_CNPJ_BASE = 8;

String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad

String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim

function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber

function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj

function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj

function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida d�gitos verificadores
	if (numero != base + digitos) return false;

	/* N�o ser�o considerados v�lidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf

function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida d�gitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* N�o ser�o considerados v�lidos os CNPJ com os seguintes n�meros B�SICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	/* N�o ser� considerado v�lido CNPJ com n�mero de ORDEM igual a 0000.
	 * N�o ser� considerado v�lido CNPJ com n�mero de ORDEM maior do que 0300
	 * e com as tr�s primeiras posi��es do n�mero B�SICO com 000 (zeros).
	 * Esta cr�tica n�o ser� feita quando o no B�SICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000") return false;
	return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj

function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj

