// by Ricardo Falasca <falasca at jurid.com.br>

var URL = "http://jornal.jurid.com.br";
//var URL = document.getElementsByTagName('base')[0].href;

var meses = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
var semana = ['Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado','Domingo'];

function OpenCertDetails(){
  thewindow = window.open('https://www.thawte.com/cgi/server/certdetails.exe?code=BRJURI1-4', 'anew', config='height=566,width=516,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=yes');
}

function trim(str){return str.replace(/^\s+|\s+$/g,"");}

function criaAjax(){
	var ajax = null;	
	try	{
    ajax = new XMLHttpRequest();
	 }	catch (e){
		ajax = new ActiveXObject("Microsoft.XMLHTTP"); 
	}
	return ajax;
}

function mostrar (div,valor){
	if (valor == "1"){
		document.getElementById(div).style.display = "block";
		}else{
			document.getElementById(div).style.display = "none";
		}
}

function enviaRequisicao(url, params, metodo, assincrono){
  var x = criaAjax();  
  
  if (x){
    x.open(metodo, url, assincrono);
    x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    x.setRequestHeader("charset", "iso-8859-1"); // ISO-8859-1
  
    if (assincrono){ x.onreadystatechange = function(){ if (x.readyState == 4) {var resultado = x.responseText; } } }
    
    x.send(params);
    if (!assincrono) { return x.responseText; } else { return ""; }  
    } else {
    return "NAO_INICIALIZADO";
  }
}

function hexToString(h){
  var r = "";
  for (var i= (h.substr(0, 2)=="0x")?2:0; i<h.length; i+=2) {r += String.fromCharCode (parseInt (h.substr (i, 2), 16));}
  return r;
}

function retornavalor(vetor, name){
  if (!vetor) return null;
  
	var i = 0;
	var aux = null;

	for (i=0;i<vetor.length;i++){
		aux = vetor[i].split("=");
		if (aux[0] == name)//evitando problemas qdo tem um "=" no texto...
		  return (aux.length > 2)?aux.slice(1).join("="):aux[1]; 		
	}
	return null;
}

function criaCookie(name,value,days) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+days);
  document.cookie=name+"="+escape(value)+((days==null)?"":";expires="+exdate.toGMTString());	
}

function leCookie(name) {
  if (document.cookie.length>0){
    c_start=document.cookie.indexOf(name + "=");
    if (c_start!=-1){
      c_start=c_start + name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
      }
    }
  return "";
}

function apagaCookie(name) {
	criaCookie(name,"",-1);
}

function validaEmail(email){  
  var filtro = /(^[a-zA-Z0-9]([a-zA-Z0-9_\.]*)@([a-zA-Z0-9_\.]*)([.][a-zA-Z0-9]{2,4})$)|(^[a-zA-Z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{2,4})(\.[a-z]{2})*$)/i;
  return (filtro.test(email))?email:false; 
}

function setaValorCampo(formname,fieldname,fieldvalue){
  var field = document.getElementById(fieldname);

  if ((!fieldvalue)||(fieldvalue==null)) return fieldvalue;
  
  try {
    if ((typeof(field) == "undefined")||(field == null)){
      var f = document.getElementById(formname);

      field = document.createElement("input");     
      field.type = "hidden";
      field.name = fieldname;
      field.id   = fieldname;
      field.value = fieldvalue;
      (f)?f.appendChild(field):alert('Objeto não encontrado! :('); 
      } else {
      field.value = fieldvalue;
    }
    return field;    
    } catch(error) {
    return false;
  }    
}

function pegaValorCampo(fieldname,defaultvalue,errorvalue){
  var field = document.getElementById(fieldname);  
  var value = (field)?field.value:defaultvalue;
  return (value != errorvalue)?value:false;
}

function pegaValorRadio(div_group,groupname){
  var i = 0;
  var coll = document.getElementById(div_group).getElementsByTagName('input');

  for (i=0;i<coll.length;i++){
    if (coll[i].type == "radio"){
      if (coll[i].name == groupname)
        if (coll[i].checked) return coll[i].value;
    }
  }    
  return false;
}

function pegaValorRadioEx(nomeGrupo){
  var i = 0;
  var coll = document.getElementsByName(nomeGrupo);

  for (i=0;i<coll.length;i++){
    if (coll[i].checked) return coll[i].value;    
  }    
  return false;
}

function pegaValorCheck(fieldname,defaultvalue){
  var f = document.getElementById(fieldname);
  if (!f) return defaultvalue;
  return (f.checked)?f.value:defaultvalue;
}

function setaFocoCampo(fieldname){  
  var field = document.getElementById(fieldname);
  if (field){
    if(field.title != "") alert(field.title);
    field.focus();    
  }
  return;    
}

function trataTexto(texto){
  var straux= texto + '#';
  var straux2='';
  var i=0;
  while (straux.charAt(i)!='#') {
    if ((straux.charAt(i)=="'")||(straux.charAt(i)=='"')||(straux.charAt(i)=='(')||(straux.charAt(i)==')'))
      straux2=straux2 + ' ';
      else
      straux2=straux2 + straux.charAt(i);
    i++;
  }
  return straux2;
}

function ehNumerico(valor){
  /*var validChars = "0123456789.";
  var isNumber=true;
  var Char;
 
  for (i = 0; i < valor.length && isNumber == true; i++){ 
    Char = valor.charAt(i); 
    if (validChars.indexOf(Char) == -1) isNumber = false;
  }
  return isNumber; */
  var numeros = /\D/;  
  return (!numeros.test(valor)); 
}

function validaCPF(cpf){
  valor = true;
 
  if ((!ehNumerico(cpf))||(cpf.length != 11)){
    //alert("CPF inválido! Por favor, digite apenas os números corretamente!");
    return false;
  }  
 
  if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
    //alert("CPF inválido! Por favor, digite apenas os números corretamente!");
    return false;
  }
  
  var a = [];
  var b = new Number;
  var c = 11;
  
  for (i=0; i<11; i++){ a[i] = cpf.charAt(i); if (i < 9) b += (a[i] * --c); }  
  if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }  
  b = 0;
  c = 11;
  for (y=0; y<10; y++) b += (a[y] *  c--);
  if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
  if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
    //alert("CPF inválido! Por favor, digite apenas os números corretamente!");
    return false;
  }
  
  return true;
}
 
function validaCNPJ(cnpj) {
  erro = new String;
  v    = new String;

  if (!ehNumerico(cnpj)){
    //alert("CNPJ inválido! Por favor, digite apenas os números corretamente!");
    return false;
  }

  if ((cnpj.length > 15) || (cnpj == "") || (cnpj.length < 13)){
    //alert("CNPJ inválido! Por favor, digite apenas os números corretamente!");
    return false;
  }
  if (cnpj.length == 15){ for (i=1; i<cnpj.length; i++) v = v + cnpj.charAt(i); }
  if (v.length > 0) cnpj = v;

  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("CNPJ inválido! Por favor, digite apenas os números corretamente!");
    return false;
  }
  
  return true;
}
 
function validaData(dateStr) {
  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
  var matchArray = dateStr.match(datePat);

  if (matchArray == null){
    //alert("Data incorreta! Por favor, preencha a data corretamente.");
    return false;
  }
  
  day = matchArray[1];
  month = matchArray[3];
  year = matchArray[4];
  if (month < 1 || month > 12) {
    //alert("Mês incorreto.");
    return false;
  }
  if (day < 1 || day > 31) {
    //alert("Dia incorreto.");
    return false;
  }
  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    //alert("Mês "+month+" não tem 31 dias!")
    return false;
  }
  if (month == 2) {
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap)) return false;
  }

  return true;
}
 
function validaTelefone(telefone) {
  straux = telefone + '#';

  if (telefone.length < 8) return false;
  i = 0;
  while (straux.charAt(i)!='#') {
    if (((straux.charAt(i)>='0') && (straux.charAt(i)<='9')) || ((straux.charAt(i)==' ') || (straux.charAt(i)=='-') || (straux.charAt(i)=='+') || (straux.charAt(i)=='.') || (straux.charAt(i)=='(') || (straux.charAt(i)==')')))
      i++;
      else 
      return false;
  }
  return true;
}

function validaCEP(cep){
  var filtro = /^[0-9]{5}-[0-9]{3}$/;
  return (filtro.test(cep))?cep:false; 
}

function validaNomeCompleto(nome){
  var s = trim(nome);  
  s = s.split(" ");
  return (s.length > 1);
}

function validaSenhaCadastro(senha1,senha2){  
  return ((((senha1 != "")&&(senha2 != ""))&&(senha1==senha2))&&((senha1.length>=4)||(senha2.length>=4)));
}

//Verifica CAPS-LOCK ativado
function checar_caps_lock(ev) {
	var e = ev || window.event;
	codigo_tecla = e.keyCode?e.keyCode:e.which;
	tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)?true:false);
	if(((codigo_tecla >= 65 && codigo_tecla <= 90) && !tecla_shift) || ((codigo_tecla >= 97 && codigo_tecla <= 122) && tecla_shift)) {
		document.getElementById('aviso_caps_lock').style.visibility = 'visible';
	}
	else {
		document.getElementById('aviso_caps_lock').style.visibility = 'hidden';
	}
}

/* função sprintf() .. sprintf("%s%d...", args...); */
sprintfWrapper = {
	init : function () {

		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }

		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;

		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }

			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);

			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);

		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }

		var code = null;
		var match = null;
		var i = null;

		for (i=0; i<matches.length; i++) {

			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}

			newString += strings[i];
			newString += substitution;

		}
		newString += strings[i];

		return newString;

	},

	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}
sprintf = sprintfWrapper.init;

//Efeito hover nas imagens
function mouseOver(obj,img) { 
  obj.src = "images/" + img; 
}

function mouseOut(obj,img) { 
  obj.src = "images/" + img; 
}

// rotinas para envio de contato...
function enviaContatoJornal(campocaptcha, ns){
	captcha = document.getElementById(campocaptcha);
	
	if (!captcha) return false;
	
	if (!validaCaptchaJurid(captcha.value, false, ns)){
		alert('Por favor, digite o código de segurança corretamente!');
		captcha.focus();
		return false;
		} else {
		enviaContato();
	}
	
	return true;
}

function enviaContato(){
	var nome		 = document.getElementById('contato_nome');			if (nome.value == ''){ alert('Por favor, digite seu nome corretamente!'); nome.focus(); return false; }
	var email		 = document.getElementById('contato_email');		if (!validaEmail(email.value)){ alert('Por favor, digite seu e-mail corretamente!'); email.focus(); return false; }
	var assunto	 = document.getElementById('contato_assunto');	if (assunto.value == ''){ alert('Por favor, digite o assunto que deseja tratar!'); assunto.focus(); return false; }
	var mensagem = document.getElementById('contato_mensagem'); if (mensagem.value == ''){ alert('Por favor, digite a mensagem corretamente!'); mensagem.focus(); return false; }
	var captcha	 = document.getElementById('contato_captcha');  if (captcha.value == ''){ alert('Por favor, digite o texto da imagem de segurança corretamente!'); captcha.focus(); return false; }
	
	var parametros = sprintf("nome=%s&email=%s&assunto=%s&mensagem=%s&ns=fccaptcha&acao=envia&captcha=%s", 
													 nome.value,
													 email.value,
													 assunto.value,
													 mensagem.value,
													 captcha.value);
													 
	var resultado = enviaRequisicao(URL + '/contato', parametros, 'POST', false);
	resultado = resultado.split("\r\n");
	
	nome.value = 'seu nome';
	email.value = 'seu e-mail (não será divulgado)';
	assunto.value = 'assunto à tratar';	
	mensagem.value = 'Digite aqui sua mensagem!';
	captcha.value = '';
	
	geraCaptchaJurid('captchacontato', 34, 90, 'azulescuro', 'cinzaspider', 'fccaptcha');
	
	alert(retornavalor(resultado, "MSG"));
	
	return true;
}

// rotinas para envio dos comentários e réplicas... com verificação de captcha!
function enviaComentarioJornal(campocaptcha, nomeFuncaoSucesso, ns){
  captcha = document.getElementById(campocaptcha);
  if (!captcha) return false;
  
  if (!validaCaptchaJurid(captcha.value, false, ns)){
    alert('Por favor, digite o código de segurança corretamente!');
    return false;
    } else {
    eval(nomeFuncaoSucesso + "();");
  }
  
  return true;
}

function enviaComentario(){
  var nome      = document.getElementById('comentario_nome');       if (nome.value == ''){ alert('Por favor, digite seu nome corretamente!'); nome.focus(); return false; }
  var email     = document.getElementById('comentario_email');      if (!validaEmail(email.value)){ alert('Por favor, digite seu e-mail corretamente!'); email.focus(); return false; }
  var profissao = document.getElementById('comentario_profissao');  if (profissao.value == ''){ alert('Por favor, digite sua profissão corretamente!'); profissao.focus(); return false; }
  var texto     = document.getElementById('comentario_texto');      if ((texto.value == '')||(texto.value == 'Digite aqui sua opinião!')){ alert('Por favor, digite sua opinião!'); texto.focus(); return false; }
  var captcha   = document.getElementById('comentario_captcha');    if (captcha.value == ''){ alert('Por favor, digite o texto da imagem de segurança corretamente!'); captcha.focus(); return false; }
  var idmateria = document.getElementById('idmateria');             if (idmateria.value == 0){ alert('Matéria não identificada! Por favor, recarregue a página e tente novamente!'); return false; }

  var parametros = sprintf("nome=%s&email=%s&profissao=%s&texto=%s&captcha=%s&ns=cjcaptcha&idmateria=%s&acao=adiciona",
                           nome.value,
                           email.value,
                           profissao.value,
                           texto.value,
                           captcha.value,
                           idmateria.value);

  var resultado = enviaRequisicao(URL + '/comentario', parametros, 'POST', false);

  nome.value = "seu nome";
  email.value = "seu e-mail (não será divulgado)";
  profissao.value = "sua profissão";
  texto.value = "Digite aqui sua opinião!";
  captcha.value = "";
  window.location.reload(false);
  
  return true;
}

function enviaReplicaComentario(){
  var nome      = document.getElementById('replica_nome');       	if (!validaNomeCompleto(nome.value)){ alert('Por favor, digite seu nome corretamente!'); nome.focus(); return false; }
  var email     = document.getElementById('replica_email');      	if (!validaEmail(email.value)){ alert('Por favor, digite seu e-mail corretamente!'); email.focus(); return false; }
  var profissao = document.getElementById('replica_profissao');  	if (profissao.value == ''){ alert('Por favor, digite sua profissão corretamente!'); profissao.focus(); return false; }
  var texto     = document.getElementById('replica_texto');      	if ((texto.value == '')||(texto.value == 'Digite aqui sua opinião!')){ alert('Por favor, digite sua opinião!'); texto.focus(); return false; }
  var captcha   = document.getElementById('replica_captcha');    	if (captcha.value == ''){ alert('Por favor, digite o texto da imagem de segurança corretamente!'); captcha.focus(); return false; }
  var idmateria = document.getElementById('idmateria');          	if (idmateria.value == 0){ alert('Matéria não identificada! Por favor, recarregue a página e tente novamente!'); return false; }
  var idcomentario = document.getElementById('idcomentario');    	if (idcomentario.value == 0){ alert('Comentário não identificado! Por favor, recarregue a página e tente novamente!'); return false; }
   
  var parametros = sprintf("nome=%s&email=%s&profissao=%s&texto=%s&captcha=%s&ns=rcjcaptcha&idmateria=%s&idcomentario=%s&acao=adiciona",
                           nome.value,
                           email.value,
                           profissao.value,
                           texto.value,
                           captcha.value,
                           idmateria.value,
                           idcomentario.value);
                           
  var resultado = enviaRequisicao(URL + '/comentario', parametros, 'POST', false);

  nome.value = "seu nome";
  email.value = "seu e-mail (não será divulgado)";
  profissao.value = "sua profissão";
  texto.value = "Digite aqui sua opinião!";
  captcha.value = "";
  window.location.reload(false);

  return true;
}

function iniciaPesquisa(){
  var palavras = document.getElementById('pesquisaGeral');  
  
  if (!palavras) return false;
  
  if ((palavras.value == '')||(palavras.value.indexOf('Digite aqui o que procura')>-1)){
    alert('Por favor, digite corretamente o que deseja pesquisar!');
    palavras.focus();
    return false;
  }
  palavras = palavras.value.replace(/\//gi, "");

  // tratamento apenas para casos de pesquisa E, OU!    
  if (palavras.indexOf('"') == -1){
    palavras = palavras.replace(/,/gi, " E ");
    palavras = palavras.replace(/  /gi, " ");
  }  
  tratamento = palavras.toUpperCase();
  palavras = palavras.replace(/\"/gi, "");  
  
  if (tratamento.indexOf('"') > -1)
    tipo = "f"; // Frase "FRASE" 
  else
  if (tratamento.indexOf(' OU ') > -1)
    tipo = "q"; // Qualquer palavra "OU"
  else
    tipo = "t"; // Todas as palavras "E"  
  
  window.location.href = "/pesquisa/texto/" + palavras + "/tipo/" + tipo;
}

/* ****
 * rotinas para indicação de matéria para amigos
 *** */
 
 function acrescentaIndicacoes()
 {
   var tabela = document.getElementById('tabela_indique_campos');
   var cnt = tabela.rows.length - 4;
   var linha = tabela.insertRow(cnt + 1);
   
   
   linha.insertCell(0).innerHTML = "<input id=\"destinatario_nome_" + cnt + "\"  type=\"text\" value=\"Nome do amigo(" + cnt + ")\" class=\"destinatario\" onfocus=\"if (this.value == 'Nome do amigo(" + cnt + ")') this.value=''\" onblur=\"if (this.value == '') this.value = 'Nome do amigo(" + cnt + ")'\"/>";
   linha.insertCell(1).innerHTML = "<input id=\"destinatario_email_" + cnt + "\"  type=\"text\" value=\"E-mail do amigo(" + cnt + ")\" class=\"destinatario\" onfocus=\"if (this.value == 'E-mail do amigo(" + cnt + ")') this.value=''\" onblur=\"if (this.value == '') this.value = 'E-mail do amigo(" + cnt + ")'\"/>";
 }
 
 function limpaIndicacao()
 {
   var tabela = document.getElementById('tabela_indique_campos');
   
   while (tabela.rows.length > 7) 
     tabela.deleteRow(4);

   document.getElementById('remetente_nome').value = 'Seu nome';
   document.getElementById('remetente_email').value = 'Seu e-mail';
   document.getElementById('destinatario_nome_1').value = 'Nome do amigo(1)';
   document.getElementById('destinatario_nome_2').value = 'Nome do amigo(2)';
   document.getElementById('destinatario_email_1').value = 'E-mail do amigo(1)';
   document.getElementById('destinatario_email_2').value = 'E-mail do amigo(2)';
 }

 function enviaIndicacoes()
 {
  var params = "";
  //remetente
   var nome = document.getElementById('remetente_nome');
   var email = document.getElementById('remetente_email');
   
   if (nome.value == 'Seu nome')
   {
    alert('Indique seu nome!');
    nome.focus();
    return;
   }
   
   params += "REMETENTE_NOME=" + escape(nome.value);
    
   if (!validaEmail(email.value))
   {
    alert('Indique seu email corretamente!');
    email.focus();
    return;
   }
   
   params += "&REMETENTE_EMAIL=" + escape(email.value);
   //destinatarios
   var cnt = 1;
   while (true)
   {
     nome = document.getElementById('destinatario_nome_' + cnt);
     email = document.getElementById('destinatario_email_' + cnt);
     
     if ((!nome) || (nome.value == 'Nome do amigo(' + cnt + ')')) break;
     if ((!email) || (!validaEmail(email.value))) break;
     
     params += "&DESTINATARIO_NOME_" + cnt + "=" + escape(nome.value);
     params += "&DESTINATARIO_EMAIL_" + cnt + "=" + escape(email.value);
     
     cnt++;
   }
   
   if (cnt == 1)
   {
    alert('Indique pelo menos um amigo para receber esta matéria!');
    return;
   }
   //enviando...
   params += "&URL=" + escape(URL_MATERIA);
   var resultado = enviaRequisicao(URL + '/indique', params, 'POST', false);
   
   if (!resultado)
     alert('Falha no envio dos dados!');
     else
     {
       alert(retornavalor(resultado.split('\r\n'), "MSG").replace(/\[\#\]/g, '\r\n'));
       if (retornavalor(resultado.split('\r\n'), "ERRO") == "0")
       {
         limpaIndicacao();
         document.getElementById('indique').style.display='none';
       }
     }
 }
 
 
 function enviaCadastroSimples(campocaptcha, ns)
 {
 	var captcha = document.getElementById(campocaptcha);
	
	if (!captcha) return false;
	
	if (!validaCaptchaJurid(captcha.value, false, ns))
  {
		alert('Por favor, digite o código de segurança corretamente!');
		captcha.focus();
		return false;
	}
	
	var nome = document.getElementById('newsletter_nome');
  var email = document.getElementById('newsletter_email');
  
  if ((!nome) || (nome.value == "seu nome"))
  {
    alert('Informe seu nome!');
    nome.focus();
    return;
  }
  
  if ((!email) || (!validaEmail(email.value)))
  {
    alert('Informe seu e-mail');
    email.focus();
    return;
  }
  //tudo OK, posso enviar
  var params = "NOME=" + escape(nome.value) + "&EMAIL=" + escape(email.value) + "&ACTION=cadastrar&CAPTCHA=" + captcha.value + "&NS=" + ns + "&APAGA=0";
	var resultado = enviaRequisicao(URL + '/newsletter', params, 'POST', false);
	
  if (!resultado)
     alert('Falha no envio dos dados!');
    else
    {
     if (retornavalor(resultado.split('\r\n'), "ERRO") == "0")
     {
       document.getElementById('div_confirmacao').style.display = "block";
       document.getElementById('div_dados').style.display = "none";
       document.getElementById('newsletter_titulo').innerHTML = "Cadastro feito com sucesso!";
     }
     else
      alert(retornavalor(resultado.split('\r\n'), "MSG").replace(/\[\#\]/g, '\r\n'));
    }

	return true;
 }
 
 
 function verificaExtensaoArtigo(campo){
	var extensoes = ['doc','docx','pdf','rtf','txt','odt'];
	
	if (campo.value == "") return false;

	var arquivo = campo.value.split(".");
	var extensao = arquivo[arquivo.length-1].toLowerCase();
	
	var permitido = false;
	
	for (i=0;i<extensoes.length;i++)
		if (extensao == extensoes[i]){
		permitido = true;
		break;
	}
	
	if (!permitido){
		alert("São permitidos apenas arquivos nos formatos:\r\n\r\n.doc, .docx, .pdf, .rtf, .txt ou .odt.\r\n\r\nPor favor, tente novamente.");
		campo.value = "";
		return false;
	}
	return true;
}

function fireClickEvent(objetoClicavel){
  if (document.all){ 
    objetoClicavel.fireEvent("onclick"); 
    } else {
    var clickEvent = window.document.createEvent("MouseEvent");
    clickEvent.initEvent("click", false, true);
    objetoClicavel.dispatchEvent(clickEvent);
  }
}

