String.prototype.trim = function(){
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function chkselecao_busca_geral(theform, sessao){
	
	//d = document.busca_geral;
	d = theform;
	if ((d.palavra_chave.value == "") || (d.palavra_chave.value == "Palavra-chave")) {
		alert("O campo de palavra chave\ndeve ser preenchido");
		d.palavra_chave.focus();
		return false;
	} else if(d.palavra_chave.value != "") {
		if(d.palavra_chave.value.length < 4) {
			alert("Por favor, a palavra chave de busca deve ter no minimo 4 caractéres.");
			d.palavra_chave.focus();
			return false;
		}
	}
	if (d.areabusca.value == ""){
		alert("O campo de área \ndeve ser selecionado");
		d.areabusca.focus();	
		return false;
	}
	else {
		switch (d.areabusca.value){
			case "1"://NOTÍCIAS
				d.action='resultado_busca_noticias.php';
				break;
			case "2"://ARTIGOS
				d.action='resultado_busca_artigos.php';
				break;		
			case "3"://FESTAS E EVENTOS
				d.action='resultado_busca_festa_eventos.php';
				break;			
			case "4"://ORAÇÕES
				d.action='resultado_busca_oracoes.php';
				break;			
			case "5"://PARÓQUIAS
				d.action='resultado_busca_paroquias.php';
				break;							
		}
		return true;
	}	
}

function QuestionDetail(question, totalQuestions){
	var divAtual = document.getElementById('resposta' + question);
	var action;
	if (divAtual.style.display == 'block')
		action = 'none';
	else
		action = 'block';
		
	for (i = 1; i <= totalQuestions; i++){
		var div = document.getElementById('resposta' + i);				
		div.style.display = 'none';		
	}	
	divAtual.style.display = action;	
}

function HorarioMissaDetail(id){
	var LIAtual = document.getElementById('Linha' + id);
	var Span = LIAtual.getElementsByTagName('span');
	
	for(var i=0; i<Span.length;i++)
		{
			var divAtual = Span[i];
			if (divAtual.style.display == 'block')
				divAtual.style.display = 'none';
			else
				divAtual.style.display = 'block';
		}
}

function selectPlantabilidadeTipo(element) {
	msg = element.value == 'l' ? 'Número do lote:' : 'Peneira:';
	$j("#termo").removeClass('displaynone')
	$j("#spanTipo").attr({innerHTML: msg});
}

function loadEquipeTecnica(uf) {
	var time = new Date().getTime(); 
	$j(document).ready(function(){
		
		$j("#div_dadosequipe").attr({innerHTML: '<img src="imgs/ajax-loader.gif">'});
		$j.post("equipetecnica_load_equipe.php", { hora: time, uf:  uf}, 
				function(data){
					$j("#div_dadosequipe").attr({innerHTML: data});						
				});
		
	});
}


function loadEquipeComercial(uf) {
	var time = new Date().getTime(); 
	$j(document).ready(function(){
		
		$j("#div_dadosequipe").attr({innerHTML: '<img src="imgs/ajax-loader.gif">'});
		$j.post("equipecomercial_load_equipe.php", { hora: time, uf:  uf}, 
				function(data){
					$j("#div_dadosequipe").attr({innerHTML: data});						
				});
		
	});
}



function loadCidades() {
	var time = new Date().getTime(); 
	$j(document).ready(function(){
		if ($j("estado").val() != "") {
			$j("#div_cidade").attr({innerHTML: '<img src="imgs/ajax-loader.gif">'});
			$j.post("parceiros_load_cidades.php", { hora: time, estado_id:  escape($j("#estado").val())}, 
					function(data){
					 	$j("#div_cidade").attr({innerHTML: data});						
					});
		}
	});
}


function loadParceiros() {
	var time = new Date().getTime(); 
	$j(document).ready(function(){

		if ($j("#estado").val() != '' && $j("#cidade").val() != '') {
			$j("#div_msg").attr({innerHTML: ''});
			$j("#div_resultado").attr({innerHTML: '<img src="imgs/ajax-loader.gif">'});
			$j.post("parceiros_busca.php", { hora: time, estado:  escape($j("#estado").val()), cidade:  escape($j("#cidade").val())}, 
					function(data){
					 	$j("#div_resultado").attr({innerHTML: data});						
					});
		}
		else {
			$j("#div_msg").attr({innerHTML: 'Você deve selecionar um estado e uma cidade'});	
		}
	});
}

function cadastraNews() {
var time = new Date().getTime(); 
	$j(document).ready(function(){
		
		erro = false;					   
		if ($j("#nome").val().trim() == "Nome" || $j("#nome").val().trim() == "") {
			erro = true;
			$j("#span_nome").removeClass('displaynone');
			$j("#span_nome").attr({innerHTML: "Nome é obrigatório"});
		}
		else {
			$j("#span_nome").addClass('displaynone');
			$j("#span_nome").attr({innerHTML: ""});			
		}
			
		if ($j("#email").val().trim() == "E-mail" || $j("#email").val().trim() == "") {
			erro = true;
			$j("#span_email").removeClass('displaynone');
			$j("#span_email").attr({innerHTML: "E-mail é obrigatório"});
		}
		else{
			if ($j("#email").val().search("@") == -1 || $j("#email").val().search("[.*]") == -1) {
				erro = true;
				$j("#span_email").removeClass('displaynone');
           		$j("#span_email").attr({innerHTML: "E-mail inválido"});
			}
			else {
				$j("#span_email").addClass('displaynone');
				$j("#span_email").attr({innerHTML: ""});
			}
		}
	
		if (erro == false) {
			$j.post("action_cadastro_news.php", { nome:  escape($j("#nome").val()), email: $j("#email").val()}, 
			function(data){
							
				if (data == "success") {
					$j("#result_cad_news").attr({innerHTML: "Seu cadastro foi realizado com sucesso!"});
					$j("#nome").attr({value: ""});
					$j("#email").attr({value: ""});
				}
				
				if (data == "exist") {
					$j("#result_cad_news").attr({innerHTML: "O e-mail informado já está cadastrado!"});					
				}	
				
			});		
		}	
	});
}



function cancelaNews() {
var time = new Date().getTime(); 
	$j(document).ready(function(){
			
		erro = false;	
		if ($j("#cancel_news_email").val().trim() == "") {
			erro = true;
			$j("#span_cancel_news_email").attr({innerHTML: "E-mail é obrigatório"});
		}
		else{
			if ($j("#cancel_news_email").val().search("@") == -1 || $j("#cancel_news_email").val().search("[.*]") == -1) {
				erro = true;
           		$j("#span_cancel_news_email").attr({innerHTML: "E-mail inválido"});
			}
			else {
				$j("#span_cancel_news_email").attr({innerHTML: ""});
			}
		}
	
		if (erro == false) {
			$j.post("action_cancel_news.php", {email: $j("#cancel_news_email").val()}, 
			function(data){
								
				if (data == "success") {
					$j("#result_cancelarnews").attr({innerHTML: "Seu e-mail foi retirado de nossa lista com sucesso!"});
					$j("#cancel_news_email").attr({value: ""});
				}
				
				if (data == "not_exist") {
					$j("#result_cancelarnews").attr({innerHTML: "O e-mail informado não está cadastrado em nossa lista!"});					
				}	
				
			});
			
			
		}
	
	});
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-


function openClienteMidia(id, total) {
	for (i = 0; i < total; i++) {
		document.getElementById('midia_'+i).style.display = 'none';
	}
	document.getElementById('midia_'+id).style.display = document.getElementById('midia_'+id).style.display == 'none' ? 'block' : 'none';
}

function openCloseDIV(id){
	document.getElementById(id).style.display=='none' ? document.getElementById(id).style.display='block' : document.getElementById(id).style.display='none';
}


function validaVoto() {
	rd = document.form_enquete.opcao_id;
	opcao_id = - 1;
	for (i=0; i < rd.length; i++) {
		if (rd[i].checked) {
			opcao_id = rd[i].value
		}
	}	
	
	return opcao_id;
}

function votarEnquete(enquete_id) {
	opcao_id = validaVoto();
	if (opcao_id != - 1) {
		xmlhttp.open("GET", "modulos/mod_enquete/action_votar_enquete.php?enquete_id="+enquete_id+"&opcao_id="+opcao_id,true);
		
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4){
				var dados = xmlhttp.responseText;		
				document.getElementById("enquete").innerHTML = dados;
							
			}
		}
		xmlhttp.send(null);	
	}
	else {
		document.getElementById("enquete_error").innerHTML = "Você deve selecionar uma opção de voto!";
	}
	
}


function resultadoEnquete(enquete_id) {
	xmlhttp.open("GET", "modulos/mod_enquete/inc_resultado.php?enquete_id="+enquete_id,true);
	
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4){
			var dados = xmlhttp.responseText;		
			document.getElementById("enquete").innerHTML = dados;
						
		}
	}
	xmlhttp.send(null);		
}


//Muda foto da notícia com 3 fotos
function mudaFotoNoticia(id, foto) {
	document.getElementById(id).src = "resources/thumb.php?foto=img_noticia/"+foto+"&amp;x=250&amp;y=250";
}
//Envio form para pop-up
function openFormPopup(){
	window.open("","_popup","toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=no,width=354,height=475");
return true;
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}


//Abrir/fechar box de comentários de artigos
function openCloseBox(id) {
	document.getElementById(id).style.display = document.getElementById(id).style.display == 'block' ? 'none' : 'block';
}

//Abrir pop-up
function janela(file, window, larg, altura){
	window_=open(file,window,'directories=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,width=' + larg + ',height='  + altura);
	window_.moveTo((screen.width-larg)/2,(screen.height-altura)/2-20);  
}


function encode(str){
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}
function decode(str){
    str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}

function albumExibePaginacaoFoto(foto_id, album_id, foto_id_last, foto_id_first){
	alert("entrou na funcao");
	xmlhttp.open("GET", "action_exibe_pag_foto.php?foto_id="+foto_id+"&album_id="+album_id,true);
	alert("chamour open");
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4){
			alert("entrou no sucesso 2");
			var d = xmlhttp.responseText;		
			alert("jogou resultado na var d");
			document.getElementById("paginacao_foto").innerHTML = d;
			alert("setou paginacao na div paginacao_foto");
			
		}
	}
	xmlhttp.send(null);	
	
	if (foto_id < foto_id_last)
		albumPaginarMiniaturas(document.getElementById('paramsNextPage').value);
				
	if (foto_id > foto_id_first)
		albumPaginarMiniaturas(document.getElementById('paramsPreviousPage').value);
}

function albumViewFoto(foto_id, album_id){			
	ultima  = document.getElementById("foto_id_last").value;
	primeira = document.getElementById("foto_id_first").value; 
	
	document.getElementById("foto_det").innerHTML = '<img style="margin-top:120px;" src="../../imgs/loading.gif" />'; 	
	xmlhttp.open("GET", "action_view_foto.php?foto_id="+foto_id,true);
	
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4){
			alert("entrou no sucesso 1");
			var dados = xmlhttp.responseText;	
			alert("jogou resultado no var dados");
			document.getElementById("foto_det").innerHTML = dados;
			alert("jogou resultado na div foto_det e vai chamar funcao albumExibePaginacaoFoto");
			
			alert("após chamada exibePaginacaoFoto");
			alert(document.getElementById("foto_det").innerHTML);
		}
	}
	
	xmlhttp.send(null);		
	albumExibePaginacaoFoto(foto_id, album_id, ultima, primeira);
}

function albumPaginarMiniaturas(parameters){
			
	xmlhttp.open("GET", "action_paginar_miniaturas.php"+parameters,true);
	
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4){
			var dados = xmlhttp.responseText;		
			document.getElementById("navegacao_pop").innerHTML = dados;
		}
	}
	xmlhttp.send(null);	
}

//Chamada de inicio do AJAX
try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}

function chkcurriculo(){
	d = document.form1;
	
	//nome
	if(d.curriculo_nome.value == "")
	{
		alert("O campo Nome deve ser preenchido!");
		d.curriculo_nome.focus();
		return false;
	} else if(d.curriculo_nome.value.length < 4) {
		alert("Por favor, o nome deve ter no minimo 4 caractéres.");
		d.curriculo_nome.focus();
		return false;
	}
	//validar email
	if (d.curriculo_email.value == ""){
		alert("O campo E-mail deve ser preenchido!");
		d.curriculo_email.focus();
		return false;
	}
	var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	var reEmail2 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	var reEmail3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	var reEmail = reEmail3;

	eval("reEmail = reEmail" + 3);
	if (!(reEmail.test(d.curriculo_email.value))) {
		alert("O campo E-mail deve ser conter um endereco eletronico válido!");
		d.curriculo_email.focus();
		return false;
	}
	//tipo de endereço
	if(d.curriculo_telefone.value == "")
	{
		alert("O campo Telefone deve ser preenchido!");
		d.curriculo_telefone.focus();
		return false;
	}
	if(d.area_id.value == "")
	{
		alert("O campo Área de Interesse deve ser selecionado!");
		d.area_id.focus();
		return false;
	}
	if(d.arquivo.value == "")
	{
		alert("O campo Arquivo deve ser preenchido!");
		d.arquivo.focus();
		return false;
	} else {
		d.submit();
	}
}