//Valor da cor usada nos campos de form, sempre que houver erro de preenchimento
var bgErrado = "#FFCC00";

//Rotina que muda a cor de um campo que esteja apresentando erro de preenchimento
function setColor(el, bg) {
  if (el.style) el.style.backgroundColor = bg;
}

// Emite mensagem de erro
function erro(campo, texto, complemento, tamanho)
{
	if (complemento == "")
   	{
		if (tamanho == "")
		{
      		alert("O campo " + texto + " deve estar preenchido.");
	  		setColor(campo, bgErrado);
	  		campo.focus();
  	  		//campo.value = "";
	 	}
		else
		{
      		alert("O campo " + texto + " deve estar preenchido com no máximo " + tamanho + " caracteres.");
	  		setColor(campo, bgErrado);
	  		campo.focus();
  	  		//campo.value = "";
		}
   }
   else
   {
      alert(complemento);
	  setColor(campo, bgErrado);
	  campo.focus();
   }
}


// Função que valida o email caso txtemail tenha sido preenchido
function ValidaEmail(email)
{
	var contarrouba = 0;
	var caracter    = "";
	var strEMAIL    = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    strEMAIL   += "@._ -";
					
	//verifica se existe espaco em branco
	for (var i=1; i < email.length-1; i++)
	{
		if(email.charAt(i) == " ")
		{
			return false;
		}
	}
	
	// verifica se o endereco tem acentos
  	for (var i = 0; i < document.forms[0].txtemail.length; i++)
    {   
    	if ((document.forms[0].txtemail.value.charCodeAt(i) <= "255") && (document.forms[0].txtemail.value.charCodeAt(i) >= "192") &&
		    (document.forms[0].txtemail.value.charCodeAt(i) != "199") && (document.forms[0].txtemail.value.charCodeAt(i) != "231") &&
			(document.forms[0].txtemail.value.charCodeAt(i) != "215"))
	    {
	     	erro(document.forms[0].txtemail, "" , "Email Inválido", "");
			return false;
        }
 	}
	
	// verifica se existe um arroba
	if (email.indexOf("@",0) != -1)
	{
		indicearrouba = email.indexOf("@",0);
	}
		
	// percorre todos os caracteres do email e compara com o array de caracteres validos
	for (var i=0; i < email.length; i++)
	{
			caracter = email.charAt(i);
				
			if (strEMAIL.indexOf(caracter,0) == -1)
			{
				document.forms[0].txtemail.focus();
				document.forms[0].txtemail.select();
				erro(document.forms[0].txtemail, "" , "Email Inválido", "");
				return false;
			}
		
			if (email.charAt(i)=="@")
			{
				contarrouba = contarrouba + 1;
			}
		
			var procura = email.substring(i,i+2);
			if ((procura=="..")||(procura==".@"))
			{
				document.forms[0].txtemail.focus();
				document.forms[0].txtemail.select();
				erro(document.forms[0].txtemail, "" , "Email Inválido", "");
				return false;
			}
	}
	
	// verifica a composição do endereco do email
	if (email.value != "")
	{
		if ((email.indexOf("@",0) < 1)||(email.indexOf("@",1) == -1)||
			(email.lastIndexOf("@",0) == email.length-1)||(contarrouba > 1)||
			(email.charAt(email.length-1) == ".")||(email.indexOf(".",indicearrouba) == -1)||
			(email.charAt(indicearrouba-1) == ".")||(email.charAt(indicearrouba+1) == ".")||
			(email.indexOf(".",0) < 1))
			{
				document.forms[0].txtemail.focus();
				document.forms[0].txtemail.select();
				erro(document.forms[0].txtemail, "" , "Email Inválido", "");
				return false;
			}
	}
	return true;
}

// Funcao que valida os dados do form de cadastro
function ValidaCadastro(cadastro) 
{
	var dia;
	var mes;
	var ano;
	var estado;
	var profissao;
	
	dia    		= cadastro.txtdianasc.selectedIndex;
	mes    		= cadastro.txtmesnasc.selectedIndex;
	ano    		= cadastro.txtanonasc.selectedIndex;
	estado 		= cadastro.txtestado.selectedIndex;
	profissao 	= cadastro.txtprofissao.selectedIndex;
	
	if ((cadastro.txtemail.value == "") || (cadastro.txtemail.value.length > 100))
	{
		erro(cadastro.txtemail, "" , "O campo email deve ser preenchido corretamente e no máximo com 100 caracteres.");
		return false;
	}
	else
	{
		if (!ValidaEmail(cadastro.txtemail.value))
		{
			erro(cadastro.txtemail, "" , "O campo email deve ser preenchido corretamente.");
			return false;
		}
	}
	if ((cadastro.txtsenha.value == "") || (cadastro.txtsenha.value.length > 10))
	{
		erro(cadastro.txtsenha, "" , "O campo senha deve ser preenchido e no máximo com 10 caracteres.");
		return false;
	}
	if ((cadastro.txtsenhaconf.value == "") || (cadastro.txtsenhaconf.value.length > 10))
	{
		erro(cadastro.txtsenhaconf, "" , "O campo de confirmação da senha deve ser preenchido e no máximo com 10 caracteres.");
		return false;
	}
	if ((cadastro.txtnome.value == "") || (cadastro.txtnome.value.length > 100))
	{
		erro(cadastro.txtnome, "" , "O campo nome deve ser preenchido e no máximo com 100 caracteres.");
		return false;
	}
	if (estado == 0)
	{
		erro(cadastro.txtestado, "" , "Selecione um estado", "" );
		return false;
	}
	if ((cadastro.txtcurso.value == "") || (cadastro.txtcurso.value.length > 100))
	{
		erro(cadastro.txtcurso, "" , "O campo curso deve ser preenchido e no máximo com 100 caracteres.");
		return false;
	}
	if (profissao == 0)
	{
		erro(cadastro.txtprofissao, "" , "Selecione uma profissão");
		return false;
	}
	if (dia == 0)
	{
		erro(cadastro.txtdianasc, "" , "Selecione um dia", "" );
		return false;
	}
	if (mes == 0)
	{
		erro(cadastro.txtmesnasc, "" , "Selecione um mês", "" );
		return false;
	}
	if (ano == 0)
	{
		erro(cadastro.txtanonasc, "" , "Selecione um ano", "" );
		return false;
	}
	return true;
}	

// Funcao que valida os dados do form de noticia
function ValidaNoticia(noticia) 
{
	var dia;
	var mes;
	var ano;
	var local;
	
	dia    	= noticia.txtdia.selectedIndex;
	mes    	= noticia.txtmes.selectedIndex;
	ano    	= noticia.txtano.selectedIndex;
	local  	= noticia.txttarget.selectedIndex;
	
	if ((noticia.txttitulo.value == "") || (noticia.txttitulo.value.length > 255))
	{
		erro(noticia.txttitulo, "" , "O campo título deve ser preenchido corretamente e no máximo com 255 caracteres.");
		return false;
	}
	if ((noticia.txtsubtitulo.value.length > 255))
	{
		erro(noticia.txtsubtitulo, "" , "O campo sub-título deve ser preenchido no máximo com 255 caracteres.");
		return false;
	}
	if ((noticia.txtfonte.value.length > 255))
	{
		erro(noticia.txtfonte, "" , "O campo fonte deve ser preenchido no máximo com 255 caracteres.");
		return false;
	}
	if (dia == 0)
	{
		erro(noticia.txtdia, "" , "Selecione um dia.", "" );
		return false;
	}
	if (mes == 0)
	{
		erro(noticia.txtmes, "" , "Selecione um mês.", "" );
		return false;
	}
	if (ano == 0)
	{
		erro(noticia.txtano, "" , "Selecione um ano.", "" );
		return false;
	}
	if (mes == 2)
	{
		if ((ano != 0) & (ano % 4 != 0))
		{
			if(dia > 28)
			{
				erro(noticia.txtdia, "", "Data inválida. Este ano não é bissexto.", "");
				return false;
			}
		}
	}
	if ((mes == 04) || 
		(mes == 06) ||
		(mes == 09) || 
		(mes == 11))
	{
		if (dia > 30)
		{
			erro(noticia.txtdia, "", "Data inválida. Este mês contém apenas 30 dias.", "");
			return false;
		}
	}	
	if (local == 0)
	{
		erro(noticia.txttarget, "" , "Selecione um tipo de link.", "" );
		return false;
	}
	else
	{
		if ((local == 1) && (noticia.txtconteudo.value == ""))
		{
			erro(noticia.txtconteudo, "" , "O campo conteúdo da notícia deve ser preenchido.", "" );
			return false;
		}
		else
		{
			if ((local == 2) && ((noticia.txtpagina.value == "") || (noticia.txtpagina.value.length > 100)))
			{
				erro(noticia.txtpagina, "" , "O campo página deve ser preenchido no máximo com 100 caracteres.", "" );
				return false;
			}
		}
	}

	return true;
}	

// Funcao que valida os dados do form de curso
function ValidaCurso(curso) 
{
	var diaini;
	var mesini;
	var anoini;
	var diafim;
	var mesfim;
	var anofim;
	var estado;
	var local;
	
	diaini    	= curso.txtdiaini.selectedIndex;
	mesini    	= curso.txtmesini.selectedIndex;
	anoini    	= curso.txtanoini.selectedIndex;
	diafim    	= curso.txtdiafim.selectedIndex;
	mesfim    	= curso.txtmesfim.selectedIndex;
	anofim    	= curso.txtanofim.selectedIndex;
	estado		= curso.txtestado.selectedIndex;
	
	if ((curso.txttitulo.value == "") || (curso.txttitulo.value.length > 255))
	{
		erro(curso.txttitulo, "" , "O campo título deve ser preenchido corretamente e no máximo com 255 caracteres.");
		return false;
	}
	if ((curso.txtlocal.value == "") || (curso.txtlocal.value.length > 255))
	{
		erro(curso.txtlocal, "" , "O campo local deve ser preenchido no máximo com 255 caracteres.");
		return false;
	}
	if ((curso.txtendereco.value == "") || (curso.txtendereco.value.length > 255))
	{
		erro(curso.txtendereco, "" , "O campo endereço deve ser preenchido no máximo com 255 caracteres.");
		return false;
	}
	if (estado == 0)
	{
		erro(curso.txtestado, "" , "Selecione um estado.", "" );
		return false;
	}
	/*if (curso.txtddd.value == "")
	{
		erro(curso.txtddd, "" , "O campo DDD deve ser preenchido no máximo com 3 caracteres.");
		return false;
	}
	if (curso.txttelefone.value == "")
	{
		erro(curso.txttelefone, "" , "O campo telefone deve ser preenchido no máximo com 8 caracteres.");
		return false;
	}
	if (diaini == 0)
	{
		erro(curso.txtdiaini, "" , "Selecione um dia.", "" );
		return false;
	}
	if (mesini == 0)
	{
		erro(curso.txtmesini, "" , "Selecione um mês.", "" );
		return false;
	}
	if (anoini == 0)
	{
		erro(curso.txtanoini, "" , "Selecione um ano.", "" );
		return false;
	}*/
	if (mesini == 2)
	{
		if ((anoini != 0) & (anoini % 4 != 0))
		{
			if(diaini > 28)
			{
				erro(curso.txtdiaini, "", "Data inválida. Este ano não é bissexto.", "");
				return false;
			}
		}
	}
	if ((mesini == 04) || 
		(mesini == 06) ||
		(mesini == 09) || 
		(mesini == 11))
	{
		if (diaini > 30)
		{
			erro(curso.txtdiaini, "", "Data inválida. Este mês contém apenas 30 dias.", "");
			return false;
		}
	}
	/*if (diafim == 0)
	{
		erro(curso.txtdiafim, "" , "Selecione um dia.", "" );
		return false;
	}
	if (mesfim == 0)
	{
		erro(curso.txtmesfim, "" , "Selecione um mês.", "" );
		return false;
	}
	if (anofim == 0)
	{
		erro(curso.txtanofim, "" , "Selecione um ano.", "" );
		return false;
	}*/
	if (mesfim == 2)
	{
		if ((anofim != 0) & (anofim % 4 != 0))
		{
			if(diafim > 28)
			{
				erro(curso.txtdiafim, "", "Data inválida. Este ano não é bissexto.", "");
				return false;
			}
		}
	}
	if ((mesfim == 04) || 
		(mesfim == 06) ||
		(mesfim == 09) || 
		(mesfim == 11))
	{
		if (diafim > 30)
		{
			erro(curso.txtdiafim, "", "Data inválida. Este mês contém apenas 30 dias.", "");
			return false;
		}
	}
	if (curso.txtdescricao.value == "")
	{
		erro(curso.txtdescricao, "" , "O campo Descrição deve ser preenchido.");
		return false;
	}
	return true;
}

// Funcao que valida os dados do form de login
function ValidaLogin() 
{
	if ((login.txtemail.value == "") || (login.txtemail.value.length > 100))
	{
		erro(login.txtemail, "" , "O campo email de ser preenchido e no máximo com 100 caracteres.");
		return false;
	}
	if ((login.txtsenha.value == "") || (login.txtsenha.value.length > 10))
	{
		erro(login.txtsenha, "" , "O campo senha de ser preenchido e no máximo com 10 caracteres.");
		return false;
	}
	return true;
}	

function Esqueci()
{
	var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,scrollbars=0,width=350,height=150,top=50,left=50';
	window.open('esqueci.php','JanelaAbandono',param);
}

function Suporte()
{
	var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,scrollbars=0,width=350,height=300,top=50,left=50';
	window.open('suporte.php','JanelaAbandono',param);
}

// Funcao que valida os dados do form de cadastro
function ValidaFale() 
{
	var assunto;
	
	assunto = document.forms[0].faleassunto.selectedIndex;
	
	if (document.forms[0].falenome.value == "")
	{
		erro(document.forms[0].falenome, "" , "O campo nome deve ser preenchido.");
		return false;
	}
	if (document.forms[0].falemail.value == "")
	{
		erro(document.forms[0].falemail, "" , "O campo email deve ser preenchido.");
		return false;
	}
	if (assunto == 0)
	{
		erro(document.forms[0].faleassunto, "" , "Selecione um assunto", "" );
		return false;
	}
	if (document.forms[0].faletexto.value == "")
	{
		erro(document.forms[0].faletexto, "" , "O campo descrição deve ser preenchido.");
		return false;
	}
	return true;
}

//função que cria um contado de 1 seg para aguardar que uma determinada janela seja fechada
function FechaJanela(valor)
{
	var timer = setTimeout('self.close()', 1000);
	opener.assinantes.txttotassinantes.value = valor;
}

//função que cria um contado de 1 seg para aguardar que uma determinada janela seja fechada
//
//
// ==>>>> MODIFICAR ESSA FUNCAO ANTES DE COLOCAR NO SITE
//
function FechaJanela2(sid,todos,pagina)
{
	//window.opener.location.href="http://localhost/equoterapia/retaguarda/" + pagina + "?sid=" + sid + "&chktodos=" + todos;
	window.opener.location.href="http://www.equoterapia.com.br/retaguarda/" + pagina + "?sid=" + sid + "&chktodos=" + todos;
	var timer = setTimeout('self.close()', 2000);
}

//função que abre a janela de ajuda do preenchimento da newsletter
function Ajuda()
{
	var param = 'menubar=0,resizable=0,scrollbars=1,status=0,titlebar=0,width=400,height=480,top=50,left=50';
	window.open('ajuda.htm','Ajuda',param);
}

//função que verifica a possibilidade de envio da newsletter
function Envia(botao)
{
	if (botao=="Inicializar Log de Controle de Envios")
	{
		if (confirm("Tem certeza que deseja inicializar o log de controle de envios ?"))
		{
			document.newsletter.action="inicializa_controle_newsletter.php";
			document.newsletter.submit();
		}
	}
	else
	{
		if ((document.newsletter.txtassunto.value.length > 0) && (document.newsletter.txtconteudo.value.length > 0))
		{
			document.newsletter.action="processar_newsletter.php";
			document.newsletter.submit();
		}
		else
		{
			alert("Preencha todos os campos da Newsletter!!!");
		}
	}
}

//função que abre janela com o conteudo a ser enviado da newsletter
function Visualiza()
{
	document.visualiza.txtconteudo.value = document.newsletter.txtconteudo.value;
	document.visualiza.action="visualiza_conteudo.php";
	document.visualiza.submit();
}

//função que abre janela com rotina que consulta o numero de usuarios que podem receber a newsletter
function Verifica()
{
	var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,width=150,height=150,top=50,left=50';
	window.open('verifica_assinantes.php','Ajuda',param);
}	

//função que abre janela com o conteudo a ser enviado da newsletter
function Carrega()
{
	if (confirm("Essa opção recarrega todos os usuários, desconsiderando qualquer envio anterior.\n Tem certeza que deseja carregar o log de controle de envios ?"))
	{
		var estado = document.carrega.txtestado.value;
		var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,width=150,height=150,top=50,left=50';
		var arquivo = 'carrega_assinantes.php?estado=' + estado;
		window.open(arquivo,'carrega',param);
	}
}

function Salva()
{
	if (document.newsletter.txtassunto.value.length == 0)
	{
		alert("Preencha o campo assunto!!!");
		setColor(document.newsletter.txtassunto, bgErrado);
		document.newsletter.txtassunto.focus();
	}
	else
	{
		if (document.newsletter.txtconteudo.value.length == 0)
		{
			alert("Preencha o campo conteúdo!!!");
			setColor(document.newsletter.txtconteudo, bgErrado);
			document.newsletter.txtconteudo.focus();
		}
		else
		{
			document.salva_recupera.txtassunto.value = document.newsletter.txtassunto.value;
			document.salva_recupera.txtconteudo.value = document.newsletter.txtconteudo.value;
			document.salva_recupera.action="salva_newsletter.php";
			document.salva_recupera.target="Rodape";
			document.salva_recupera.submit();
		}
	}
}

function Recupera()
{
	document.salva_recupera.action="recupera_newsletter.php";
	document.salva_recupera.submit();
}

function Limpa()
{
	document.newsletter.txtassunto.value="";
	document.newsletter.txtconteudo.value="";
}

function ApagaNoticia(botao)
{
	var idnoticia = botao.split("_");
	var sid = document.noticias.sid.value;
	var todos = document.noticias.chktodos.value;

	if (confirm("Deseja realmente apagar essa notícia ?"))
	{
		var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,width=150,height=150,top=50,left=50';
		var arquivo = 'apaga_noticia.php?sid=' + sid + '&id=' + idnoticia[1] + "&chktodos=" + todos;
		window.open(arquivo,'noticias',param);
	}
}

function AlteraNoticia(botao)
{
	var idnoticia = botao.split("_");
	var sid = document.noticias.sid.value;
	var todos = document.noticias.chktodos.value;
	
	var param = 'menubar=0,resizable=0,scrollbars=1,status=1,titlebar=0,width=650,height=500,top=100,left=100';
	var arquivo = 'detalhe_noticia.php?sid=' + sid + '&id=' + idnoticia[1] + "&chktodos=" + todos;
	window.open(arquivo,'atualiza',param);
}

function  AtualizaStatusNoticia(botao)
{
	var idnoticia = botao.split("_");
	var sid = document.noticias.sid.value;
	var todos = document.noticias.chktodos.value;
	var nomestatus = "status_" + idnoticia[1];
	var item;
	var status;
	
	for (var i = 0; i < document.noticias.elements.length; i++) 
	{
		if (document.noticias.elements[i].name==nomestatus)
		{
			item = document.noticias.elements[i].selectedIndex;
			if (item==0)
			{
				status = "N";
			}
			else
			{
				status = "S";
			}
		}
	}
	
	if (status=="N")
	{
		msg = "Deseja realmente ativar essa notícia ?";
	}
	else
	{
		msg = "Deseja realmente desativar essa notícia ?";
	}
	
	if (confirm(msg))
	{
		var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,width=150,height=150,top=50,left=50';
		var arquivo = 'atualiza_status_noticia.php?sid=' + sid + '&id=' + idnoticia[1] + "&chktodos=" + todos + "&status=" + status;
		window.open(arquivo,'noticias',param);
	}
}

function ApagaCurso(botao)
{
	var idcurso = botao.split("_");
	var sid = document.cursos.sid.value;
	var todos = document.cursos.chktodos.value;

	if (confirm("Deseja realmente apagar esse curso ?"))
	{
		var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,width=150,height=150,top=50,left=50';
		var arquivo = 'apaga_curso.php?sid=' + sid + '&id=' + idcurso[1] + "&chktodos=" + todos;
		window.open(arquivo,'cursos',param);
	}
}

function  AtualizaStatusCurso(botao)
{
	var idcurso = botao.split("_");
	var sid = document.cursos.sid.value;
	var todos = document.cursos.chktodos.value;
	var nomestatus = "status_" + idcurso[1];
	var item;
	var status;
	
	for (var i = 0; i < document.cursos.elements.length; i++) 
	{
		if (document.cursos.elements[i].name==nomestatus)
		{
			item = document.cursos.elements[i].selectedIndex;
			if (item==0)
			{
				status = "N";
			}
			else
			{
				status = "S";
			}
		}
	}
	
	if (status=="N")
	{
		msg = "Deseja realmente ativar esse curso ?";
	}
	else
	{
		msg = "Deseja realmente desativar esse curso ?";
	}
	
	if (confirm(msg))
	{
		var param = 'menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,width=150,height=150,top=50,left=50';
		var arquivo = 'atualiza_status_curso.php?sid=' + sid + '&id=' + idcurso[1] + "&chktodos=" + todos + "&status=" + status;
		window.open(arquivo,'noticias',param);
	}
}

function Mostra(valor)
{
	//alert(valor);

	if (valor=="I") //se a opcao escolhida foi Site
	{
      L1.style.display = "";
	  L2.style.display = "none";
	}
	else
	{
		if (valor=="E") //se a opcao escolhida foi Janela
		{
      		L1.style.display = "none";
	 		L2.style.display = "";
		}
		else //nenhuma opcao escolhida
		{
			L1.style.display = "none";
			L2.style.display = "none";
		}
	}
}

function FechaDetalheNoticia(sid)
{
	window.opener.location="processar_pesquisa_noticia.php?sid=" + sid + "&chktodos=true";
	self.close();
}