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 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;
}

// verifica se o arquivo tem a extensao solicitada
// passar vazio 1 se quiser que verifique se esta vazio tambem
function verificaExtensao(obj,exts,vazio) {
	var pos;
	var ext;
	if (!obj.value && vazio) {
		return false;
	}
	pos = obj.value.lastIndexOf('.'); 	
	ext = obj.value.substring(pos+1,obj.value.length);
	if (exts.indexOf(ext) == -1) {
		return false;
	}
	else {
		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 remList(origem) {
	orig	=	document.getElementById(origem);
	orig.options[orig.selectedIndex] = null;
}

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 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;
	return false;
}

function aguarde(param) {
	var acao = param == true?loading.popup():loading.fechar();
}

function validacao(campo,msg)
{
	limpaJanelas();
	alerta.mensagem 		= msg;
//	alerta.tempoMensagem 	= 3;
	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.");
		}
	}
}



function formataData(val)
{
   	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;				
 				  continue;			
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
				 	var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;			
				}
		
				if	((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
   		  }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>10)
		val.value = val.value.substring(0, 10);
	 	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;
}

function validamail (email) {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))) {
			alert("Email invalido, digite novamente por favor.");
			email.focus();
			return false;
		}
		return true;
}

function validaCNPJ(campo) {
	var CNPJ = campo.value;
	var erro = new String;
	if (CNPJ.length < 14) { alert("Preencha corretamente o campo CNPJ!"); return false; }
	//substituir os caracteres que nao sao numeros
	campo.value = CNPJ.replace(".","");
	campo.value = CNPJ.replace(".","");
	campo.value = CNPJ.replace("-","");
	campo.value = CNPJ.replace("/","");
	
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) { alert('Preencha corretamente o campo CNPJ!'); return false; }
	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])){
		alert("Preencha corretamente o campo CNPJ!"); return false;
	}
	if (erro.length > 0){
		alert(erro);
		return false;
	} 
	else {
		return true;
	}
}



/* 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.tempoMensagem 	= 3;
	alerta.acaoSim			= 'focoJan';
	alerta.acaoSimParam		= campo;
	alerta.popup();
	return false;
}

function FormataCNPJ(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
}

function TelefoneFormat(Campo, e) {
	var key = '';
	var len = 0;
	var strCheck = '0123456789';
	var aux = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13 || whichCode == 8 || whichCode == 0)
	{
		return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico
	}
	key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1){
		return false;  //NÃO E VALIDO
	}
	
	aux =  Telefone_Remove_Format(Campo.value);
	
	len = aux.length;
	if(len>=8)
	{
		return false;	//impede de digitar um telefone maior que 10
	}
	aux += key;
	
	Campo.value = Telefone_Mont_Format(aux);
	return false;
}

function  Telefone_Mont_Format(Telefone)
{
	var aux = len = '';
	
	len = Telefone.length;
	if(len<=9)
	{
		tmp = 5;
	}
	else
	{
		tmp = 6;
	}
	
	aux = '';
	for(i = 0; i < len; i++)
	{
		if(i==0){
			//aux = '(';
		}
		aux += Telefone.charAt(i);
		if(i+1==2)
		{
			//aux += ')';
		}
		
		if(i+2==tmp)
		{
			aux += '-';
		}
	}
	return aux ;
}


function  Telefone_Remove_Format(Telefone)
{
	var strCheck = '0123456789';
	var len = i = aux = '';
	len = Telefone.length;
	for(i = 0; i < len; i++)
	{
		if (strCheck.indexOf(Telefone.charAt(i))!=-1)
		{
			aux += Telefone.charAt(i);
		}
	}
	return aux;
}



function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY){
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	if(yScroll < windowHeight) pageHeight = windowHeight;
	else pageHeight = yScroll;
	if(xScroll < windowWidth) pageWidth = windowWidth;
	else pageWidth = xScroll;
	arrayPageSize = {pageWidth:pageWidth,pageHeight:pageHeight,windowWidth:windowWidth,windowHeight:windowHeight}
	return arrayPageSize;
}

function abrirImagem(caminho,altura,largura,legenda)
{
	//pegando altura do body - ie6
	var pageSize = getPageSize();
	document.getElementById('mascara').style.height = (pageSize.pageHeight + 'px');
	
	var textoLegenda = (legenda!=''?legenda:'Clique na imagem para fechar');
	
	document.getElementById('caixaImg').innerHTML 		= '<img src="'+caminho+'" height="'+altura+'" width="'+largura+'" alt="Clique na imagem para fechar"><div id="caixa_legenda">'+textoLegenda+'</div>';
	
	document.getElementById('caixaImg').style.width 	= largura+'px';
	
	n_altura = parseInt(altura) + 20;

	document.getElementById('caixaImg').style.height 	= n_altura +'px';
	

	if (typeof document.body.style.maxHeight != "undefined")
	{
		document.getElementById('caixaImg').style.margin = "-"+ altura/2 + "px 0 0 -" + largura/2 + "px";	
	}
	else
	{
		var alturaScroll = document.documentElement.scrollTop;
		diferencaIE = alturaScroll - altura/2;
		document.getElementById('caixaImg').style.marginLeft = -largura/2 + "px";
		document.getElementById('caixaImg').style.marginTop = diferencaIE + "px";
	}

	
	document.getElementById('mascara').style.display 	= '';
	
	document.getElementById('caixaImg').style.display 	= '';
}

function fechar()
{
	document.getElementById('caixaImg').innerHTML 		= '';
	document.getElementById('mascara').style.display 	= 'none';
	document.getElementById('caixaImg').style.display 	= 'none';
}
function limpaNewsletter() {
	if ( document.getElementById('email').value == 'Digite seu e-mail' ) {
		document.getElementById('email').value = '';
		document.getElementById('email').removeAttribute('onclick');
	}
}
function limpaNome() {
	if ( document.getElementById('nome').value == 'Digite seu nome' ) {
		document.getElementById('nome').value = '';
		document.getElementById('nome').removeAttribute('onclick');
	}
}
function resetaNewsletter() {
	if ( document.getElementById('email').value == '' )
	document.getElementById('email').value = 'Digite seu e-mail';
	document.getElementById('email').setAttribute('onclick','limpaNewsletter()');
}
function resetaNome() {
	if ( document.getElementById('nome').value == '' )
	document.getElementById('nome').value = 'Digite seu nome';
	document.getElementById('nome').setAttribute('onclick','limpaNome()');
}
function adicionarNewsletter() {
	var fNome = document.getElementById('nome');
	var fEmail = document.getElementById('email');
	if ( fEmail.value != '' && fNome.value != '' ) {
		if ( validamail(fEmail) ) {
			document.getElementById('btEnviar').disabled = 1;
			executar('modulos/newsletters/bd.php?acao=adicionar','email='+fEmail.value+'&nome='+fNome.value,newslettersRe);
		}
	}
}
function newslettersRe() {
	if ( xhReq.readyState == 4 ) {
		var dados = xhReq.responseXML;
		var mensagem = dados.getElementsByTagName('mensagem')[0].firstChild.nodeValue;
		alert(mensagem);
		document.getElementById('btEnviar').disabled = 0;
		document.getElementById('newsletters').reset();
	}
}