/* Scripts espeficicos para o form de Abstracts */

//alert('Inicio do Arquivo: abstracts.js');

//declara vars pra não dar erro no IE
var conUrl, imgUrl;


//Define a classe que sera utilizada para indicar o campo que esta preenchido incorretamento
var campoClassNameErro 	= "campo_erro";
//Define a classe que sera utilizada para indicar o campo que esta preenchido corretamento
var campoClassNameOk 	= "campo_ok";
//Define variavel para marcar que geracao de pdf foi abortada e impedir a exibicao da etapa 3
var pdfGenerationAborted = false;


// lpanebr Sat Aug 30 04:23:37 BRT 2008
//
// nome do PR Logado
// registrado globalmenbte para poder
// fazer a melhoria do logged user
var prName;

// variaveis que serão utilizadas para armazenar dados dos envios de arquivos
//var filesSentModel = "<div id='fileSent#{id}'><a href='#{url}' target='_blank'><img id='fileSentIcon#{id}' src='#{img}' /> <span id='fileSentName#{id}'>#{name}</span></a></div>";
var filesSentModel = "<div><a href='#{url}' target='_blank'><img src='"+imgUrl+"filetype_small_#{ext}.gif' /> <span>#{name}</span></a></div>";
var filesSentRemoveModel = "<div id='file#{sid}'><a href='#{url}' target='_blank'><img src='"+imgUrl+"filetype_small_#{ext}.gif' /> <span id='fileSentName#{id}'>#{name}</span></a> <a class='x' href='#del' onClick='removeFile(\"#{sid}\")'><span>del</span></a></div>";
var filesSentResult;

Event.observe(window, 'load', inicial);

function inicial(){

	//alert('Função: inicial');
	
	// Focus no campo inicial
	$('form_pr').focusFirstElement();

	//Busca Email preRegister
	Event.observe($('pr_mail'), 'keyup', function(event){ if(event.keyCode==Event.KEY_RETURN){ findPreRegister(); } });
	Event.observe($('pr_submit'), 'click', function(event){ findPreRegister(); });

	// Processa SENHA
	Event.observe($('campo_pass'), 'keyup', function(event){ if(event.keyCode==Event.KEY_RETURN){ auth(); } });
	Event.observe($('campo_passC'), 'keyup', function(event){ if(event.keyCode==Event.KEY_RETURN){ auth(); } });
	Event.observe($('pass_submit'), 'click', function(event){ auth(); });

	// Forgot Pass
	$$('.link_forgot').each(function(e){
	    Event.observe(e, 'click', function(event){ $('form_forgot').toggle(); });
	});
	Event.observe($('forgot_submit'), 'click', function(event){ forgotPass(); });


	//Instrucoes
	showInstrucoes($('form_abstract'));


/*
	// Limitador: title
	Event.observe($('campo_title'), 'keyup', function(event){ limitaCampo($('campo_title'), limiteTitulo, 'title_left'); });
	Event.observe($('campo_title'), 'blur', function(event){ limitaCampo($('campo_title'), limiteTitulo, 'title_left'); });
	// Limitador: abstract
	Event.observe($('campo_abstract'), 'keyup', function(event){ limitaCampo($('campo_abstract'), limiteAbstract, 'abstract_left'); });
	Event.observe($('campo_abstract'), 'blur', function(event){ limitaCampo($('campo_abstract'), limiteAbstract, 'abstract_left'); });
	// Limitador: img Caption
	Event.observe($('campo_imgCaption'), 'keyup', function(event){ limitaCampo($('campo_imgCaption'), limiteCaption, 'imgCaption_left'); });
	Event.observe($('campo_imgCaption'), 'blur', function(event){ limitaCampo($('campo_imgCaption'), limiteCaption, 'imgCaption_left'); });
*/

	// New Abs
	$('abs_newAbs').observe('click', function(event){ newAbs(); $('abs_form').show(); $('abs_newAbs').hide(); $('form_abstract').focusFirstElement() });
	
	//Add Keys

	Event.observe($('campo_keyword'), 'keydown', function(event){ if(event.keyCode==13){ addKeyword(); } });
	Event.observe($('btn_keyword'), 'click', function(event){ addKeyword(); });
	// Tabela: Keys
	showTable($('table_keywords'));

	//Add Affiliations
	Event.observe($('campo_aff_name'), 'keydown', function(event){ if(event.keyCode==13){ addAffiliation(); } });
	Event.observe($('btn_aff'), 'click', function(event){ addAffiliation(); });
	// Tabela: Affiliation
	showTable($('table_aff'));

	//Add Author
	Event.observe($('campo_author_name'), 'keydown', function(event){ if(event.keyCode==13){ addAuthor(); } });
	Event.observe($('btn_author'), 'click', function(event){ addAuthor(); });
	
	
	// Tabela: authors
	showTable($('table_authors'));

	// Editor Latex
	if(absOnlyLatex==1){
		editorLatex();
	}else{
		if($('campo_latex')){
			$('campo_latex').observe('click', function(event){ editorLatex(); });
		}
	}
	if($('link_help_latex')){
		$('link_help_latex').observe('click', function(){ $('latexHelp').toggle(); });
	}
	
	


	// Submit: parte 1
	Event.observe($('botao_save'), 'click', function(event){ hideUploadMsg(); hideStatus(); readySubmit(); });


	// show abstract PDF options
	Event.observe($('PDF_link'), 'click', function(event){ $$('.pdfOption').invoke('show'); });
	Event.observe($('btnFinish'), 'click', function(event){ finish(); });
	Event.observe($('btnEdit'), 'click', function(event){ edit(); });
	Event.observe($('lnkCancelAndEdit'), 'click', function(event){ edit(1); });


	// Files: relatório
	if($('abs_fileSentReport')){
		$('fileSentRepor_link').observe('click',function(){ $$('#fileReport, .fileSentReportToggle').invoke('toggle'); })
	}
	
	// TabIndex
	autoTab();
	
	// autoTextareaHeight
	$$('.autoTextareaHeight').each(function(campo){
	    campo.observe('click', function(){ autoTextareaHeight(campo); });
	    campo.observe('keyup', function(){ autoTextareaHeight(campo); });
	});	
	
	

	//alert('/Função: inicial');

}//inicial

	function stripValue(value){
		return value.stripScripts().stripTags().strip();
		
	}

	function autoTab(){
		// Auto-tab:
		var indice  = autoTabindex($('form_pr'));
		indice = autoTabindex($('form_pass'), indice);
		indice = autoTabindex($('form_forgot'), indice);
		indice = autoTabindex($('form_abstract'), indice);
		if($('form_img')){
			indice = autoTabindex($('form_img'), indice);
		}
		if($('form_files')){
			indice = autoTabindex($('form_files'), indice);
		}		
		indice = autoTabindex('#botao_save', indice);
	}

	function editorLatex(){
	    if($('campo_latex').checked==true || absOnlyLatex==1){
	        $$('.editorLatex, #view_help_latex').invoke('show');
	    }else{
	        $$('.editorLatex, #view_help_latex, #latexHelp').invoke('hide');
	    };	
	}
	
    function keepAlive(){
       //alert('keepAlive =D');
       var myAjax =  new Ajax.PeriodicalUpdater('keepAlive',  conUrl+'rpc/abstracts_keepAlive.php', {
            method: 'post', frequency: 30, decay: 2
        });

    }


		function edit(aborted){
			// exibe form c/ msg
			showEtapa(2,1);
			$('abs_form').show();
			if(aborted) {
				pdfGenerationAborted = true;
			}else{
			    $('abs_form').scrollTo();
			}
		}

		function finish(){

			//AJAX
			var url = conUrl+'rpc/abstracts_finish.php';
			var pars = '?hash='+$('campo_hash').value;
			var myAjax = new Ajax.Request( url, {
				method: 'post',
				parameters: pars,
				onLoading: function() {

					// load
					$('abs_PDFsendl').show();

				},//onLoading
				onComplete: function(originalRequest) {

					// Msgs
					$('abs_PDFsendl').hide();
					$('abs_PDFsend').show();

					//Resposta da requisicao
					var resp = originalRequest.responseText;

					// Auth?
    				if(isAuth(resp)==false){
    				    return false;
    				}

					//alert(resp);
					//alert(typeof(resp));

					switch(resp){
						// OK
						case '1':
							//alert('SUCESSO.');
							showEtapa(4);
						break;
						//ERROS
						default:
							alert(strError['finish'][resp]);
						break;
					}

				},//onComplete
				onFailure: function() {
				    alertstrError(strError['function']['finish']);
				}//onFailure
			});

		}// finish()

	function checkAutAffs(obs){
		var aaErro = false;
		$$('#tbody_authors input.AutAff').each(function(campo){
			if(campo.value.length==0){
				aaErro = true;
			}
		});
		// toogle msg
		if(aaErro==true){
			showMsg($('campo_a_ERRO'));
			if(obs==1){
				$$('#tbody_authors input.AutAff').each(function(campo){
					Event.observe(campo, 'keyup', function(event){ checkAutAffs(); } );
				});
			}
			retorna = false;
		}else{
			hideMsg($('campo_a_ERRO'));
			retorna = true;
		}

		// retorna
		return retorna;
	}

	// Salva os dados do form e envia a IMG
	function readySubmit(noSubmit){

		// Trava botao
		$('botao_save').disable = true;

		var erro = false;

		// Valida: Evento
		if($('campo_evento_1')){
			if($('campo_evento_1').checked==false && $('campo_evento_2').checked==false){
				showMsg($('campo_evento_ERRO'));
				erro = true;
				Event.observe($('campo_evento_1'), 'click', function(event){ hideMsg($('campo_evento_ERRO')); } );
				Event.observe($('campo_evento_2'), 'click', function(event){ hideMsg($('campo_evento_ERRO')); } );
			}else{
				hideMsg($('campo_evento_ERRO'));
			}
		}


		// Valida: title
		if($('campo_title').hasClassName(campoClassNameOk)==false){
			//show erro
			$('campo_title').addClassName(campoClassNameErro);
			showMsg($('campo_title_ERRO'));
			//erro
			erro = true;
		}


		// Valida: abstract
		if($('campo_abstract').hasClassName(campoClassNameOk)==false){
			//show erro
			$('campo_abstract').addClassName(campoClassNameErro);
			showMsg($('campo_abstract_ERRO'));
			//erro
			erro = true;
		}

		// Valida: Keywords
		if($$('#tbody_keywords tr').length==0){
			showMsg($('campo_keyword_ERRO'));
			erro = true;
		}else{
			hideMsg($('campo_keyword_ERRO'));
		}

		// Valida: affiliation
		if($$('#tbody_aff tr').length==0){
			showMsg($('campo_aff_name_ERRO'));
			erro = true;
		}else{
			hideMsg($('campo_aff_name_ERRO'));
		}


		// Valida: author
		if($$('#tbody_authors tr').length==0){
			showMsg($('campo_author_name_ERRO'));
			erro = true;
		}else{
			hideMsg($('campo_author_name_ERRO'));

			//affs
			if(checkAutAffs(1)==false){
				erro = true;
			};

			//apresentador
			var apErro = true;
			$$('#tbody_authors input.AutAp').each(function(campo){
				if(campo.checked==true){
					apErro = false;
				}
			});
			// toogle msg
			if(apErro==true){
				showMsg($('campo_p_ERRO'));
				erro = true;
				$$('#tbody_authors input.AutAp').each(function(campo){
					Event.observe(campo, 'click', function(event){ hideMsg($('campo_p_ERRO')); } );
				});
			}else{
				hideMsg($('campo_p_ERRO'));
			}

			//Correspondente
			var cErro = true;
			$$('#tbody_authors input.AutC').each(function(campo){
				if(campo.checked==true){
					cErro = false;
				}
			});
			// toogle msg
			if(cErro==true){
				showMsg($('campo_c_ERRO'));
				erro = true;
				$$('#tbody_authors input.AutC').each(function(campo){
					Event.observe(campo, 'click', function(event){ hideMsg($('campo_c_ERRO')); } );
				});
			}else{
				hideMsg($('campo_c_ERRO'));
			}

		}


		// Valida: oral ou poster
		if($('campo_tipo_oral').checked==false && $('campo_tipo_poster').checked==false /*&& $('campo_tipo_invited').checked==false*/){
			showMsg($('campo_tipo_ERRO'));
			erro = true;
			Event.observe($('campo_tipo_oral_label'), 'click', function(event){ hideMsg($('campo_tipo_ERRO')); } );
			Event.observe($('campo_tipo_poster_label'), 'click', function(event){ hideMsg($('campo_tipo_ERRO')); } );
			//Event.observe($('campo_tipo_invited_label'), 'click', function(event){ hideMsg($('campo_tipo_ERRO')); } );
		}else{
			hideMsg($('campo_tipo_ERRO'));
		}
		
		// Valida: area
		if($('campo_area')){
			if(!$F('campo_area')){
				showMsg($('campo_area_ERRO'));
				erro = true;
				$('campo_area').observe('change', function(event){ 
					if($F('campo_area')){ 
						hideMsg($('campo_area_ERRO')); 
					}else{ 
						showMsg($('campo_area_ERRO')); 
					} 
				});
			}else{
				hideMsg($('campo_area_ERRO'));
			}	
		}
		
		// Valida: concurso
		if($('campo_concurso')){
			if(!$F('campo_concurso')){
				showMsg($('campo_concurso_ERRO'));
				erro = true;
				$('campo_concurso').observe('change', function(event){ 
					if($F('campo_concurso')){ 
						hideMsg($('campo_concurso_ERRO')); 
					}else{ 
						showMsg($('campo_concurso_ERRO')); 
					} 
				});
			}else{
				hideMsg($('campo_concurso_ERRO'));
			}	
		}


		// Valida: figure (opcional)
		if($('campo_imgCaption')){
			// caption
			if($('campo_imgCaption').hasClassName(campoClassNameErro)==true){
				//show erro
				$('campo_imgCaption').addClassName(campoClassNameErro);
				showMsg($('campo_imgCaption_ERRO'));
				//erro
				erro = true;
			}
		}
		
		
		// Valida: Files
		if($('form_files')){
			var validFile = 1;
			$$('input.files').each(function(campo){
				//alert('campo.id: '+campo.id+'\n' + 'campo.value: '+campo.value+'\n' + 'fileSentName'+ campo.id.replace(/campo_file/,'')+': '+$('fileSentName'+ campo.id.replace(/campo_file/,'')));
				if(campo.value=='' && !$('fileSentName'+ campo.id.replace(/campo_file/,''))){
					validFile = 0;
					
					campo.observe('change', function(event){
						var validFile = 1;
						$$('input.files').each(function(campo){
							if(campo.value==''){
								validFile = 0;
							}
						});
						if(validFile==1){
							hideMsg($('campo_files_ERRO'));
						}
					});//obs

				}// if
				
			});// each
			
			if(validFile==0){
				//show erro
				showMsg($('campo_files_ERRO'));
				//erro
				erro = true;
			}
			
		}// valida FIles



		if(erro==false && noSubmit!=1){
			//envia dados
			//alert("OK");
			submitAbs();
		}else{

			// novo array
			var erros = new Array();

			// seleciona campos com erro AND caixas de erro visiveis
			var seletor = $$(".msgErro, textarea."+campoClassNameErro+"");
			seletor.each(function(erro){
				if(erro.visible()==true){
					// add no inicio
					erros.unshift(erro);
				}
			});

			// inverte
			erros.reverse();

			// Scroll
			$(erros[0]).scrollTo();

			// focus
			if($(erros[0]).nodeName=="TEXTAREA"){
				$(erros[0]).focus();
				window.setTimeout(function(){ $($(erros[0]).id+'_INFO', $(erros[0]).id+'_ERRO').invoke('toggle'); }, 500);
				
			}
		}

		// Destrava botao
		$('botao_save').disable = false;

	}


	function submitStatus(cod){

		//debug("status: "+cod);

		if(cod.length==1){
			//esconde load
			($('abs_result'+cod+'l')) ? $('abs_result'+cod+'l').hide() : alert("Status '"+cod+"l' inexistente");
		}

		// show msg
		if($('abs_result'+cod)){
			$('abs_result'+cod).show();
			// scroll
			$('abs_result'+cod).scrollTo();
		}else{
			alert("Status '"+cod+"' inexistente")
		}

	}

	function hideStatus(etapa){
		if(etapa){
			$('abs_result'+etapa).hide();
		}else{
			$$('.submitStatus').invoke('hide');
		}

	}





	function forgotPass(){

	/* ENVIA DADOS */
		//AJAX
		var url = conUrl+'rpc/abstracts_forgotPass.php';
		var pars = 'forgot_email='+$F('pr_mail');
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

			    // Esconde todas
			    $$('.forgot_frmMsg').invoke('hide');
			    // Loader
			    $('forgot_load').show();

			},//onLoading
			onComplete: function(originalRequest) {

				//Resposta da requisicao
				var resp = originalRequest.responseText;
				//alert(resp+" -" + typeof(resp));

				// Exibe msg de resposta
				$('forgot_load','forgot_'+resp).invoke('toggle');

			},//onComplete
			onFailure: function() {
			    alertstrError(strError['function']['forgotPass']);
			}//onFailure
		});

	}// forgotPass()


	function submitAbs(){

	/* ENVIA DADOS */

		//Dados
		var form	= $('form_abstract');

		//AJAX
		var url = conUrl+'rpc/abstracts.php';
		var pars = form.serialize()+(($('campo_imgCaption'))?"&form[imgCaption]="+$F('campo_imgCaption'):'');
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

				// Status
				submitStatus("1l");

			},//onLoading
			onComplete: function(originalRequest) {

				//Resposta da requisicao
				var resp = originalRequest.responseText;

				//alert(resp+" -" + typeof(resp));

				// Auth?
				if(isAuth(resp)==false){
				    return false;
				}

				// ERROS
				if(resp.length<32){
				    //alert('ERRO');

					hideStatus("1l");
					
					alert(strError['submit'][resp]);

				}
				// OK
				else if(resp.length==32){

					// Hash
					$('campo_hash').value = resp;
					($('campo_hash_img'))? $('campo_hash_img').value = resp : null;
					($('campo_hash_files'))? $('campo_hash_files').value = resp : null;

					// oculta msg das etapas anteriores =D
					$$('.pr_frmMsg, .pass_frmMsg').invoke('hide');

					// Status
					submitStatus("1");

					// Img
					if($('campo_imgFile')){
						if($('campo_imgFile').value.length>0){
						// upload img
						figureUpload();
						}
					}
					else if(filesToUpload()){
						// upload
						filesUpload();
					}else{
						// TEX e PDF
						geraPDF(resp);
					}

				}
				else{
					hideStatus("1l");
					alert("BUG\nresp: "+resp);
				}

			},//onComplete
			onFailure: function() {
			    alertstrError(strError['function']['submitAbs']);
			}//onFailure
		});


	}// submitAbs()




	function showEtapa(etapa, msgs){

		// Esconde tudo
		$$('.etapa, .pr_frmMsg, .msgErro, .submitStatus, .pdfOption').invoke('hide');

		switch(etapa){
			// pre
			case 1:
				$('preRegister_text').show();
				//if(msgs==1){}
			break;

			// form
			case 2:
				//$('abs_form').show();
				(newSubmitDisabled==0)? $('abs_options').show() : $('abs_submitDisable').show();
				if(msgs==1){
					($$('div#abs_old_links div').length>0)? $('abs_old').show() : null;
					$('pr_ok').show();
				}
			break;

			// PDF ok
			case 3:
				$('abs_old').hide();
				$('abs_PDFok').show();
				//if(msgs==1){}
			break;

			// Submit ok
			case 4:
				$('abs_finished').show();
				
				// MC
				if($('mc_link') && $F('pr_mail')){
					$('mc_link').writeAttribute('href', $('mc_link').readAttribute('href')+'?email='+$F('pr_mail'));
				}
				
				//if(msgs==1){}
			break;
		}

	}



	function limitaCampo(campo, limite, classRetorna, byStr){

		//alert(limite);
		
		if(byStr){
			var resto = limite - $F(campo).split(/[ \n]/).length;
		}else{
			var resto = limite - $F(campo).length;
		}
		
		var retornaBool = true;

		// limita
		if(resto<1){
			if(resto == 0){
				// retorna
				resto = ', <span class="campoClassNameErro"><strong>'+Math.abs(resto)+'</strong> '+ ((byStr)? strInfo['stringLeft'] : strInfo['characterLeft']) +'.</span>';
				// retornaBool
				retornaBool = true;
			}else{
				// retorna
				resto = ', <strong class="campoClassNameErro">'+Math.abs(resto)+'</strong> '+ ((byStr)? strInfo['stringExceeded'] : strInfo['characterExceeded']) +'!</strong>';
				// class
				campo.removeClassName(campoClassNameOk);
				campo.addClassName(campoClassNameErro);
				// retornaBool
				retornaBool = false;
			}

		}else{
			/*
			// class
			if(campo.hasClassname(campoClassNameErro)==true){
				campo.removeClassName(campoClassNameOk);
				campo.addClassName(campoClassNameErro);
			}
			*/
			// retorna
			resto = ', <strong class="campoClassNameOk">'+Math.abs(resto)+'</strong> '+ ((byStr)? strInfo['stringLeft'] : strInfo['characterLeft']) +'!</strong>';
			// retornaBool
			retornaBool = true;
		}

		// retorna atualizando strings
		$$("span."+classRetorna).each(function(span){
			setInnerHTML(span, resto);
		});

		// retorna
		return retornaBool;
	}


	function moveUp(i){

		var atual = i;
		var acima = Number(atual) - 1;

		// pega inputs linha atual
		var linhaAtual 			= $(document.getElementsByName('form[author][name]['+atual+']')[0]).up(1);
		var linhaAtualInputs 	= linhaAtual.select('input');
		var linhaAtualAutor 	= linhaAtual.select('.authorName');

		// pega linha de baixo
		var linhaAcima = document.getElementsByName('form[author][name]['+acima+']');
		// pega inputs da linha de acima se existir
		if(linhaAcima.length>0){
			linhaAcima 				= $(linhaAcima[0]).up(1);
			var linhaAcimaInputs 	= linhaAcima.select('input');
			var linhaAcimaAutor 	= linhaAcima.select('.authorName');
		}else{
			linhaAcima = false;
		}

		// so faz a troca, caso exista a linha de baixo
		if(linhaAcima != false){

			// Campos da linha ATUAL
			nomeAtual	= $(linhaAtualInputs[0]).value;
			nomeAtualStr= $(linhaAtualAutor[0]).innerHTML;
			aAtual		= $(linhaAtualInputs[1]).value;
			pAtualCheck	= $(linhaAtualInputs[2]).checked;
			cAtualCheck	= $(linhaAtualInputs[3]).checked;

			// Campos da linha acima
			nomeAcima	= $(linhaAcimaInputs[0]).value;
			nomeAcimaStr= $(linhaAcimaAutor[0]).innerHTML;
			aAcima		= $(linhaAcimaInputs[1]).value;
			pAcimaCheck = $(linhaAcimaInputs[2]).checked;
			cAcimaCheck = $(linhaAcimaInputs[3]).checked;

			// Troca Dados
			setInnerHTML($(linhaAtualAutor[0]), nomeAcimaStr);
			$(linhaAtualInputs[0]).value	 	= nomeAcima;
			$(linhaAtualInputs[1]).value  		= aAcima;
			$(linhaAtualInputs[2]).checked  	= pAcimaCheck;
			$(linhaAtualInputs[3]).checked  	= cAcimaCheck;

			setInnerHTML($(linhaAcimaAutor[0]), nomeAtualStr);
			$(linhaAcimaInputs[0]).value 		= nomeAtual;
			$(linhaAcimaInputs[1]).value 		= aAtual;
			$(linhaAcimaInputs[2]).checked 	    = pAtualCheck;
			$(linhaAcimaInputs[3]).checked 	    = cAtualCheck;

			// debug
			//alert("nomeAtual: "+nomeAtual+"\n"+"aAtual: "+aAtual+"\n"+"pAtual: "+pAtual+" ("+pAtualCheck+")");
			//alert("nomeAcima: "+nomeAcima+"\n"+"aAcima: "+aAcima+"\n"+"pAcima: "+pAcima+" ("+pAcimaCheck+")");

		}

	}

	function moveDown(i){

		var atual = i;
		var abaixo = Number(atual) + 1;

		// pega inputs linha atual
		var linhaAtual 			= $(document.getElementsByName('form[author][name]['+atual+']')[0]).up(1);
		var linhaAtualInputs 	= linhaAtual.select('input');
		var linhaAtualAutor 	= linhaAtual.select('.authorName');

		// pega linha de baixo
		var linhaAbaixo = document.getElementsByName('form[author][name]['+abaixo+']');

		// pega inputs da linha de abaixo se existir
		if(typeof(linhaAbaixo)=='object'){
			linhaAbaixo = $(linhaAbaixo[0]).up(1);
			var linhaAbaixoInputs 	= linhaAbaixo.select('input');
			var linhaAbaixoAutor 	= linhaAbaixo.select('.authorName');
		}else{
			linhaAbaixo = false;
		}

		// so faz a troca, caso exista a linha de baixo
		if(linhaAbaixo != false){

			// Campos da linha ATUAL
			nomeAtual	= $(linhaAtualInputs[0]).value;
			nomeAtualStr= $(linhaAtualAutor[0]).innerHTML;
			aAtual		= $(linhaAtualInputs[1]).value;
			pAtualCheck	= $(linhaAtualInputs[2]).checked;
			cAtualCheck	= $(linhaAtualInputs[3]).checked;

			// Campos da linha ABAIXO
			nomeAbaixo	= $(linhaAbaixoInputs[0]).value;
			nomeAbaixoStr= $(linhaAbaixoAutor[0]).innerHTML;
			aAbaixo		= $(linhaAbaixoInputs[1]).value;
			pAbaixoCheck= $(linhaAbaixoInputs[2]).checked;
			cAbaixoCheck= $(linhaAbaixoInputs[3]).checked;

			// Troca Dados
			setInnerHTML($(linhaAtualAutor[0]), nomeAbaixoStr);
			$(linhaAtualInputs[0]).value	 	= nomeAbaixo;
			$(linhaAtualInputs[1]).value  		= aAbaixo;
			$(linhaAtualInputs[2]).checked  	= pAbaixoCheck;
			$(linhaAtualInputs[3]).checked  	= cAbaixoCheck;

			setInnerHTML($(linhaAbaixoAutor[0]), nomeAtualStr);
			$(linhaAbaixoInputs[0]).value 		= nomeAtual;
			$(linhaAbaixoInputs[1]).value 		= aAtual;
			$(linhaAbaixoInputs[2]).checked 	= pAtualCheck;
			$(linhaAbaixoInputs[3]).checked 	= cAtualCheck;

			// debug
			//alert("nomeAtual: "+nomeAtual+"\n"+"aAtual: "+aAtual+"\n"+"pAtual: "+pAtual+" ("+pAtualCheck+")");
			//alert("nomeAbaixo: "+nomeAbaixo+"\n"+"aAbaixo: "+aAbaixo+"\n"+"pAbaixo: "+pAbaixo+" ("+pAbaixoCheck+")");

		}

	}


	function updateSetas(){

		/**
		UP
		**/
		// indice
		var c = 0;
		var setasDown	= $$('#tbody_authors tr a.moveUp');

		$$('#tbody_authors tr a.moveUp').each(function(seta){
			//count
			++c;

			var onClick = seta.readAttribute('onClick');
			var disable = seta.hasClassName('disable');

			//debug
			//debug("["+c+"]\nonClick: "+onClick+"\nDisable: "+disable);

			if(c==1){
				// remove onClick
				(onClick!=null) ? seta.writeAttribute("onClick", null) :null;
				// desabilita
				(disable==false) ? seta.addClassName('disable') : null;
			}else{
				// add onClick
				(onClick==null) ? seta.writeAttribute("onClick", "moveUp('"+c+"');") :null;
				// habilita
				(disable==true) ? seta.removeClassName('disable') : null;
			}
		});



		/**
		DOWN
		**/
		// indice
		var d = 0;
		var setasDown	= $$('#tbody_authors tr a.moveDown');

		$$('#tbody_authors tr a.moveDown').each(function(seta){
			//count
			++d;

			var onClick = seta.readAttribute('onClick');
			var disable = seta.hasClassName('disable');

			//debug
			//debug("["+c+"]\nonClick: "+onClick+"\nDisable: "+disable);

			if(setasDown.length==d){
				// remove onClick
				(onClick!=null) ? seta.writeAttribute("onClick", null) :null;
				// desabilita
				(disable==false) ? seta.addClassName('disable') : null;
			}else{
				// add onClick
				(onClick==null) ? seta.writeAttribute("onClick", "moveDown('"+d+"');") :null;
				// habilita
				(disable==true) ? seta.removeClassName('disable') : null;
			}
		});

	}



	function checkAffs(campo){

		var retorna ='';

		campo.value.split(",").each(function(n){

			var ok;

			// filtra valor
			n = stripValue(n);

			// numero?
			if(isFinite(n) && n.length>0){
			    // nao ZERO
			    n = n.replace('0','');

			    // nao pode ser maior que o numero de AFFs
			    if($$('#table_aff #tbody_aff tr').length>=n){
			        // concatena com virgula
			        retorna += ((retorna.length>0)?",":"") + n;
			    }
			}
		});

		// atualiza valor no campo
		campo.value = retorna.replace(/,,/g,',');
	}

	function addAuthor(popula){

		// Valor do campo
		var newAuthor = (popula!=undefined)? popula : $F('campo_author_name');
		
		// filtra valor
		newAuthor = stripValue(newAuthor);

		// Inputs hiddem
		var dup = false
		$$('#tbody_authors tr input').each(function(campo){
			if(campo.value == newAuthor){
				dup = true;
			}
		});

		//verifica se tem valor
		if(newAuthor.length<=0){
			// Erro
			alert(strInfo['fieldMandatory']);
		}
		//Verifica Duplicidade
		else if(dup == true){
			// Erro
			alert(strError['author']['already']);
		}else{
			
			var newId = $$('#tbody_authors tr').length + 1;
			var i = 10;

			var aff = ($$('#table_aff tbody tr').length<=1)? "1" : "";

			// HTML
            var html = '<tr>';
            html += '<td width="60">';
            html += '<a class="moveUp" href="#up" onClick="moveUp(\''+newId+'\');"><span>up</span></a>';
            html += '<a class="moveDown" href="#down" onClick="moveDown(\''+newId+'\');"><span>down</span></a>';
            html += '</td>';
            html += '<td class="authorI" width="10">'+newId+'.</td><td width="270">';
            html += '<input type="hidden" name="form[author][name]['+newId+']" value="'+escape(newAuthor)+'" /><span class="authorName">'+newAuthor+'</span>';
            html += '</td><td width="65" style="text-align:center;" class="aff_indice">';
            html += '<input type="text" name="form[author][a]['+newId+']" value="'+aff+'" class="AutAff" tabindex="'+(++i)+'" onblur="checkAffs(Event.element(event));" />';
            html += '</td><td width="30" style="text-align:center;">';
            html += '<input type="radio" id="autorP'+newId+'" name="form[author][p]" value="'+newId+'" tabindex="'+(++i)+'" class="AutAp" onclick="setPresentingEmail(Event.element(event), \''+escape(newAuthor)+'\');" />';
            html += '</td><td width="30" style="text-align:center;">';
            html += '<input type="radio" id="autorC'+newId+'" name="form[author][c]" value="'+newId+'" tabindex="'+(++i)+'" class="AutC" onclick="setCorrespondingEmail(Event.element(event), \''+escape(newAuthor)+'\');" />';
            html += '</td><td>';
            html += '<a class="x" href="#del" onClick="removeAuthor(Event.element(event));"><span>del</span></a>';
            html += '</td>';
            html += "</tr>\n";

			// Insere
			$('tbody_authors').insert(html); //Bottom

			//zebra
			zebraTable('table_authors');

			// atualiza setas
			updateSetas()

			// limpa campo
			$('campo_author_name').value = '';

			// exibe/esconde tabela
			showTable($('table_authors'));
			
			// TabIndex
			autoTab();

		}

		// focus no campos
		if(popula==undefined){
		  $('campo_author_name').activate();
		}


		// msgErro
		if($$('#tbody_authors tr').length>0){
			hideMsg($('campo_author_name_ERRO'));
		}

	}


	function removeAuthor(trObj){

		// remove
		$(trObj.up(1)).remove();

		// Atualiza
		updateAuthors();

		// exibe/esconde tabela
		showTable($('table_authors'));
		
		// TabIndex
		autoTab();	

	}

	function updateAuthors(){

		// vars
		var i, newId  = 0;

		// recalcula Ids
		$$('#tbody_authors tr').each(function(linha){

			// seleciona inputs
			var inputs = linha.select('input');

			// Gera o novo ID
			++newId;

			// atualiza setas
			$(linha.select('.moveUp')[0]).writeAttribute('onClick', 'moveUp(\''+newId+'\');');
			$(linha.select('.moveDown')[0]).writeAttribute('onClick', 'moveDown(\''+newId+'\');');

			// atualiza indice
			setInnerHTML(linha.select('.authorI')[0], newId+'.');

			// atualiza name
			$(inputs[0]).writeAttribute('name', 'form[author][name]['+newId+']');
			// atualiza A
			$(inputs[1]).writeAttribute('name', 'form[author][a]['+newId+']');
			// atualiza P
			$(inputs[2]).value = newId;


			// Remove Zebra anterior
			linha.removeClassName('zebra_0');
			linha.removeClassName('zebra_1');

		});//each

		// atualiza Zebra
		zebraTable('table_authors');

		// atualiza setas
		updateSetas();
		
		// TabIndex
		autoTab();

	}

	/*function setPresentingEmail(campo, nome, email){
		// Eventos
	    //iBox.addEvent(iBox, 'show', function(formulario){ });		
	    //iBox.addEvent(iBox, 'hide', function(){alert('iBox was hidden');});
		
		// Exibe Form
		iBox.show(formHTML, '','');
		
	}
	*/
	function setPresentingEmail(campo, nome, email){

		//alert('campo:'+campo.id+'\nnome: '+nome+'\nemail: '+email);

	    if(nome==null){
    	    var nome = '';
	    }

	    if(email==undefined){
    	    // variaveis
    	    var email = '';

    	    // loop
    	    while(validaEmail(email)==false && email!=null){
    	       email = prompt(strInfo['enterValidEmail']+" \""+unescape(nome)+"\":", email);
    	    }
	    }

		// remove HTML do email
		$$('#table_authors small.p').invoke('remove');

		// se cancelar
	    if(email==null){
			// limpa campo
			$('campo_emailP').value = '';
			// nao checa
			campo.checked = false;
	    }
	    // se estiver valido
	    else{
	        // preenche campo
	        $('campo_emailP').value = email;
			// Insere HTML
			$($(campo.id).up(1).select('span.authorName')[0]).insert("<small class='p'><br />P: "+email+"</small>");
	        // checa
	        campo.checked = true;
	    }
	}

	function setCorrespondingEmail(campo, nome, email){

	   if(email==undefined){
            // variaveis
            var email = '';

            // loop
            while(validaEmail(email)==false && email!=null){
            email = prompt(strInfo['enterValidEmail']+" \""+unescape(nome)+"\":", email);
            }
	   }

		// remove HTML do email
		$$('#table_authors small.c').invoke('remove');

	    // se cancelar
	    if(email==null){
			// limpa campo
			$('campo_emailC').value = '';
			// nao checa
			campo.checked = false;
	    }
	    // se estiver valido
	    else{
	        // preenche campo
	        $('campo_emailC').value = email;
			// Insere HTML
			$($(campo.id).up(1).select('span.authorName')[0]).insert("<small class='c'><br />C: "+email+"</small>");
	        // checa
	        campo.checked = true;
	    }

	}

    /* Valida endereco de Email */
    function validaEmail(valor){
    	if(valor==null || valor.length==0){
    		return false;
    	}else{
    		var re = /^[\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}\])$/;
    		return re.test(valor);
    	}
    }



	function showTable(tableObj){

		var id = tableObj.id;
		var linhas = $$('#'+id+' tbody tr').length;

		//alert("showTable: "+linhas);

		// toggle tabela
		(linhas>0)? tableObj.show() : tableObj.hide();

		// Afiliacoes - indices
		//($$('#table_aff tbody tr').length>1)? $$('.aff_indice').invoke('show') : $$('.aff_indice').invoke('hide') ;

	}


	function addKeyword(popula){

		// Valor do campo
		var newKey = (popula!=undefined)? popula : $F('campo_keyword');

		//verifica se tem valor
		if(newKey.length>0){
			
			var words = $A(newKey.split(","));

			if(($$('#tbody_keywords tr').length + words.length) > keywordsLimite){
		        alert(strError['keyWord']['limit']);
		        return false;
		    }
			
			words.each(function(word){
				
				// filtra valor
				word = stripValue(word);
				
				if(word.length>0){

				    if($$('#tbody_keywords tr').length >= keywordsLimite){
				        alert(strError['keyWord']['limit']);
				        return false;
				    }
		
					var newId = $$('#tbody_keywords tr').length + 1;
		
					// HTML
					var html = '<tr><td width="6%" class="key_indice">'+newId+'.</td><td width="88%"><input type="hidden" name="form[keywords]['+newId+']" value="'+escape(word)+'" />'+word+'</td><td width="50"><a class="x" href="#del" onClick="removeKeyword(Event.element(event));"><span>del</span></a></td></tr>'+"\n";
		
					// Insere
					$('tbody_keywords').insert(html); //Bottom
					
				}
			
			});

			//zebra
			zebraTable('tbody_keywords');

			// limpa campo
			$('campo_keyword').value = '';
		}else{
			// Erro
			alert(strInfo['fieldMandatory']);
		}

		// exibe/esconde tabela
		showTable($('table_keywords'));

		// focus no campos
		if(popula==undefined){
		  $('campo_keyword').activate();
		}

		// msgErro
		if($$('#tbody_keywords tr').length>0){
			hideMsg($('campo_keyword_ERRO'));
		}

	}


	function removeKeyword(trObj){

	    // remove
		$(trObj.up(1)).remove();

		// count
		var i, newId  = 0;

		// recalcula Ids
		var seletor = $$('#tbody_keywords tr');
		seletor.each(function(linha){
				// Atualiza ID
				++newId;
				//linha.firstDescendant().innerHTML = newId;
				setInnerHTML(linha.firstDescendant(), newId+'.');
				$(linha.select('input')[0]).writeAttribute('name', 'form[keywords]['+newId+']')
				// Remove Zebra anterior
				linha.removeClassName('zebra_0');
				linha.removeClassName('zebra_1');
			}//function
		)//each

		/*// preenche os aff (vazio) dos autores
		if(seletor.length==1){
			$$('#tbody_keywords tr input.AutAff').each(function(campo){
				campo.value = (campo.value.length==0)? 1 : campo.value;
			});
			checkAutAffs(1);
		}*/

		// atualiza Zebra
		zebraTable('table_keywords');

		// exibe/esconde tabela
		showTable($('table_keywords'));
	}



	function addAffiliation(popula){

		// Valor do campo
		var newAff = (popula!=undefined)? popula : $F('campo_aff_name');
		
		// limpa valor
		newAff = stripValue(newAff);

		//verifica se tem valor
		if(newAff.length>0){

			var newId = $$('#tbody_aff tr').length + 1;

			// HTML
			var html = '<tr><td width="6%" class="aff_indice">'+newId+'.</td><td width="88%"><input type="hidden" name="form[aff]['+newId+']" value="'+escape(newAff)+'" />'+newAff+'</td><td width="50"><a class="x" href="#del" onClick="removeAffiliation(Event.element(event));"><span>del</span></a></td></tr>'+"\n";

			// Insere
			$('tbody_aff').insert(html); //Bottom

			//zebra
			zebraTable('table_aff');

			// limpa campo
			$('campo_aff_name').value = '';
		}else{
			// Erro
			alert(strInfo['fieldMandatory']);
		}

		// exibe/esconde tabela
		showTable($('table_aff'));

		// focus no campos
		if(popula==undefined){
		  $('campo_aff_name').activate();
		}

		// msgErro
		if($$('#tbody_aff tr').length>0){
			hideMsg($('campo_aff_name_ERRO'));
		}

	}

	function removeAffiliation(trObj){

		// remove
		$(trObj.up(1)).remove();

		// count
		var i, newId  = 0;

		// recalcula Ids
		var seletor = $$('#tbody_aff tr');
		seletor.each(function(linha){
				// Atualiza ID
				++newId;
				setInnerHTML(linha.firstDescendant(), newId+'.');
				$(linha.select('input')[0]).writeAttribute('name', 'form[aff]['+newId+']')
				// Remove Zebra anterior
				linha.removeClassName('zebra_0');
				linha.removeClassName('zebra_1');
			}//function
		)//each

		// preenche os aff (vazio) dos autores
		var seletorInputAffs = $$('#tbody_authors tr input.AutAff');
		if(seletor.length==1){
			seletorInputAffs.each(function(campo){
				campo.value = (campo.value.length==0)? '1' : campo.value;
			});
			checkAutAffs(1);
		}
		
		// checa Affs
		seletorInputAffs.each(function(campo){
			checkAffs(campo);
		});
		
		
		

		// atualiza Zebra
		zebraTable('table_aff');

		// exibe/esconde tabela
		showTable($('table_aff'));
	}




	/* Busca pelo email do preRegister */
	function findPreRegister(){

		//Dados
		var form = $('form_pr');

		//AJAX
		var url = conUrl+'rpc/abstracts_auth.php';
		var pars = form.serialize()+'&action=pr';
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

			    //Esconde TODAS msgs
				$$('.pr_frmMsg, #boxDeslogado').invoke('hide');

				//Load - exibe
				$('pr_load').show();

			},//onLoading
			onComplete: function(originalRequest) {

				//Resposta da requisicao
				var resp = originalRequest.responseText;
				// transforma JSON em Objeto
				resp = resp.evalJSON(true);

				//Load - esconde
				$$('.loader, #pr_load').invoke('hide');

				// distrubui valores
				var prOK    = resp.pr[0];
				prName      = resp.pr[1];
				
			    var pass = (resp.pass)? resp.pass[0] : null;
				//alert('prOK: '+prOK+' ('+typeof(prOK)+')');
				//alert('prName: '+prName+' ('+typeof(prName)+')');

				// Acoes
				switch(prOK){
					// email em branco
					case -1:
						//Exibe Msg
						$('pr_erro_mailEmpty').show();
						// focus no campos
						$('pr_mail').activate();
					break

					// email nao encontrado
					case 0:
						//Exibe Msg
						$('pr_erro').show();
						// focus no campos
						$('pr_mail').activate();
					break

					// email encontrado
					case 1:
			           // cola nome
			           setInnerHTML($('pr_name'), prName);

                       // Confirmação de senha
                       if(pass==0){
                            $('link_forgotPass').hide();
                            $('boxPassC').show();
                       }

			           // alterna forms
                       $('form_pr','form_pass','pass_'+pass).invoke('toggle');

					   // focus no campos
					   $('campo_pass').activate();
					break
				}
				
			},//onComplete
			onFailure: function() {
			    alertstrError(strError['function']['findPreRegister']);
			}//onFailure
		});
		
	}// function


	/* Autentica/Cadastra Senha obtem abstracts anteriores */
	var absQde;
	function auth(){

		//Dados
		var form = $('form_pass');

		// Verifica senhas
		if($F('campo_pass')!=$F('campo_passC') && $('boxPassC').visible()==true){
		    alert(strInfo['PasswordsNoMatch']);
		    $('campo_pass').activate();
		    return false;
		}

		//AJAX
		var url = conUrl+'rpc/abstracts_auth.php';
		var pars = form.serialize()+"&action=pass";
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

				//Esconde TODAS msgs
				$$('.pass_frmMsg').invoke('hide');

				//Load - exibe
				$('pass_load').show();

			},//onLoading
			onComplete: function(originalRequest) {
				
				var showInfoMsg = 0;

				//Resposta da requisicao
				var resp = originalRequest.responseText;
				//alert(resp);
				
				// transforma JSON em Objeto
				resp = resp.evalJSON(true);
				
				
				//Load - esconde
				$$('.loader, #pass_load').invoke('hide');

				// distrubui valores
				var pass    = resp.pass[0];
				var auth    = resp.pass[1];
				//alert("pass: "+pass+" ("+typeof(pass)+")");
				//alert("auth: "+auth+" ("+typeof(auth)+")");
				

				// Acoes: senha
				switch(pass){
					// ERROR: tamanho invalido
					case -2:
						//Exibe Msg
						$('pass_erro_size').show();
						// focus no campos
						$('campo_pass').activate();
					break

					// ERROR: senha em branco
					case -1:
						//Exibe Msg
						$('pass_erro_empty').show();
						// focus no campos
						$('campo_pass').activate();
					break

					// Erro inesperado: não salvou
					case 0:
						//Exibe Msg
						$('pass_erro').show();
						// focus no campos
						$('campo_pass').activate();
					break

					// OK: salvou
					case 1:
					   // Exibe msg
					   $('form_pass','pass_ok').invoke('toggle');
					   // lista ABs
					   var ok = 1;
					break

					// NADA
					case 'null':
					break
				}

    			// Acoes: auth
    			$('form_forgot').hide();
				if(auth==1){
				    //alert('autenticado');
				    $('form_pass').hide();
				    $('auth_ok').show();

// o show() abaixo foi comentado pois
// vai exigir mais horas para ficar bom
//
//				    $('auth_okWelcome').show();

				    // lista ABs
				    var ok = 1;
				}else if(auth==0){
				    //alert('nao auteh');
				    $('auth_erro').show();
					// focus no campos
					$('campo_pass').activate();
				}



				// Abstracts Anteriores
    		     if(ok==1){
    				// exibe ABS anteriores
    				if(resp.abs.length>0){
    				    var totalSubmittedAbstracts = "";
    					var html="";
    					var i=0;

    				    totalSubmittedAbstracts += resp.abs.length;

    					//loop
    					resp.abs.each(function(abs){
    					    i++;
    						html += "<div style='width: 618px; margin-bottom: 25px; padding:5px;  background-color:#FFFFFF; color: #000000;'> ";
    						//html += "<h4 style='padding:0;margin:0 0 10px 0;'>"+ abs.title +" ("+strInfo['submittedFor']+" "+abs.event+")</h4>";
    						html += "<h4 style='padding:0;margin:0 0 10px 0;'>"+ abs.title +"</h4>";

    						// Revisions
    						if(abs.olds){
        						if(abs.olds.length>0){
        						    abs.olds.each(function(absOld){
            						    html += "<div style='padding-bottom: 5px;'>";
            						    if(absOld.url.length>0){
                						  html += "<a href='"+absOld.url+"' target='_blank'><img src='"+imgUrl+"filetype_small_pdf.gif' alt='"+strInfo['PDFFile']+"' align='left' /> </a>";
            						    }else{
            						      html += "<img src='"+imgUrl+"filetype_small_pdf.gif' alt='"+strInfo['PDFFileRemoved']+"' title='"+strInfo['PDFFileRemoved']+"' align='left' />";
            						    }
                						html += "&nbsp;<strong>"+absOld.revision+"</strong> - "+absOld.date;
            						    html += "</div>";
        						    });
        						}
    						}

    						html += "<a href='"+abs.url+"' target='_blank'><img src='"+imgUrl+"filetype_small_pdf.gif' alt='"+strInfo['PDFFile']+"' align='left' /></a> ";
        					html += /*strInfo['ThisIsYour']+*/" <strong> &nbsp;"+ ((abs.revision>0)?strInfo['abstractRevision']+abs.revision:strInfo['abstractOriginal']) +"</strong> "+strInfo['sent']+" "+abs.date+"<br />";
    						html += strInfo['abstractStatus']+": <strong>"+abs.status+"</strong>";
    						html += ((abs.status=='Accepted')?' '+strInfo['for']+' <strong>'+abs.typeFinal+'</strong> '+strInfo['presentation']:"");
    						if(abs.parecer.length>0){
        						html += "<div><strong><a href='#toggleEvaluation' onClick=\"$('abs_parecer"+i+"','strParecer"+i+"v','strParecer"+i+"o').invoke('toggle');\" style='margin-rigth:5px; color: black'><img src='"+imgUrl+"zoom.png' alt='zoom icon' title='"+strInfo['toggleEvaluation']+"' align='left' /> <span id='strParecer"+i+"v'>"+strInfo['view']+"</span><span id='strParecer"+i+"o' style='display:none;'>"+strInfo['hide']+"</span> "+strInfo['statusAndEvaluations']+"</strong></a></div><br />";
        						html += "<em id='abs_parecer"+i+"' style='display:none;'><br />"+unescape(abs.parecer)+"</em>";
    						}
    						if(abs.corrigir==1){
    							showInfoMsg = 1;
    							html += '<div><a href="#sendRevisedVersion" onclick="populaAbsForm(\''+abs.hash+'\')"  style="color: black"><img src="'+imgUrl+'ico_editar.gif" alt="edit icon" title="'+strInfo['sendRevisedClick']+'" align="left" /> <strong>'+strInfo['sendRevised']+'</strong></a></div>';
    						}
    						html += "</div>";
    					});

    					// Exibe
    					//$('abs_old_links').innerHTML = html;
    					setInnerHTML($('abs_old_links'), html);
    					$('abs_old').show();
// lpanebr Sat Aug 30 04:22:06 BRT 2008 04:22:06
//
// os dois setInnerHTML abaixo tbm foram comentados
// por exigir mais tempo para ficar redondo
//
//    					setInnerHTML($('totalSubmittedAbstracts'), totalSubmittedAbstracts);
//    					setInnerHTML($('pr_nameLogged'), prName);

    				}else if($('abs_newAbs')){
    					$('abs_newAbs').activate();
    				}
    				
    				// Exibe msg de info
    				if(showInfoMsg==1){
    					$('abs_info').show();
    				}

       				// limite de abs
       				absQde = resp.abs.length;
    				if(absQde>=absLimitePR && absLimitePR>0){
    					$('preRegister_text').hide();
    					$('abs_old_stop').show();
    					return;
    				}else{
    					//String do Email
    					setInnerHTML($('pr_mail_str'), "<u>" + $F('pr_mail') + "</u>");
    					//Copia Email
    					$('campo_email').value = $F('pr_mail');
    					// Exibe msg Ok e form
    					showEtapa(2,1);
    					// focus no form
    					//$('form_abstract').focusFirstElement();
    				}

    				// limpa o form
    				newAbs();

    				// mantem logado
    				keepAlive();
    				
                    if(ok==1 && resp.abs.length>0){
                        //scrool
                        $('cabecalho').scrollTo();
                    }

    	        }// abs

			},//onComplete
			onFailure: function() {
			    alertstrError(strError['function']['auth']);
			}//onFailure
		});

	}// function

	function populaAbsForm(hash){
	    // debug
	    //alert("HASH: "+hash);

	    //  verifica
	    if(hash.length!=32){
	        alert(strError['popula']['hash'])
	        return false;
	    }else{
	    	
	    	// Reset form
	    	newAbs();

    		//AJAX
    		var url = conUrl+'rpc/abstracts_popula.php';
    		var pars = "hash="+hash;
    		var myAjax = new Ajax.Request( url, {
    			method: 'post',
    			parameters: pars,
    			onLoading: function() {

    				//Esconde TODAS msgs e o form
    				$$('.abs_msg, #abs_form').invoke('hide');

    				//Load - exibe
    				$('abs_old_load').show();

    			},//onLoading
    			onComplete: function(originalRequest) {

    			    //Resposta da requisicao
    				var resp = originalRequest.responseText;
    				// transforma JSON em Objeto
    				resp = resp.evalJSON(true);

    				//Load - esconde
    				$$('.loader, #abs_old_load').invoke('hide');

					// Auth?
    				if(isAuth(resp)==false){
    				    return false;
    				}
    				
    				// Popula form
					$('campo_hash').value = resp.abs.hash;
					($('campo_hash_img'))? $('campo_hash_img').value = resp.abs.hash : null;
					($('campo_hash_files'))? $('campo_hash_files').value = resp.abs.hash : null;

                    if($('campo_evento_'+resp.abs.event)){
                        $('campo_evento_'+resp.abs.event).checked = true;
                    }
    				
    				if($('campo_latex')){
	    				if(resp.abs.latex==1){
	    				    $('campo_latex').checked = true;
	    				    $$('.editorLatex').invoke('show');
	    				    $('view_help_latex').show();
	    				}
    				}
    				
    				$('campo_title').value = unescape(resp.abs.title);

    				$('campo_abstract').value = unescape(resp.abs.abstract);

    				
    				// Caso for oral e estiver oculto, exibe
    				/*if(resp.abs.type=="O" && $('tipo_oral').visible()==false){
    					$$('.oral').invoke('show');
    				}*/
    				if(resp.abs.type=="O"){
    					oralDisabled = 0;
    					typeDisable();
    				}
    				// Caso for poster e estiver oculto, exibe
    				/*if(resp.abs.type=="P" && $('tipo_poster').visible()==false){
    					$$('.poster').invoke('show');
    				}*/
    				if(resp.abs.type=="P"){
    					posterDisabled = 0;
    					typeDisable();
    				}
    				
    				$('campo_tipo_'+((resp.abs.type=="O")?'oral':((resp.abs.type=="P")?'poster':'invited'))).checked = true;

                    if($('campo_imgCaption')){
                        $('campo_imgCaption').value = unescape(resp.abs.caption);
                    }

    				// remove Keywords
    				$$('#tbody_keywords a.x').each(function(objKw){
    				    removeKeyword(objKw);
    				});
    				
    				// add Keywords
    				resp.keywords.each(function(kw){
    				    addKeyword(unescape(kw));
    				});
    				
    				// remove Aff
    				$$('#tbody_aff a.x').each(function(objAff){
    				    removeAffiliation(objAff);
    				});
    				
    				// add Aff
    				resp.affs.each(function(aff){
                        addAffiliation(unescape(aff));
    				});
    				
    				// remove Authors
    				$$('#tbody_authors a.x').each(function(objAut){
    				    removeAuthor(objAut);
    				});
    				
    				// add Authors
    				var i=0;
    				resp.authors.each(function(aut){
    				    // vars
    				    i++;
    				    var campo_a = campo_p = campos_p = false;

                        // Add autor
                        addAuthor(unescape(aut.name));

                        // Affiliations
                        campo_a = $(document.getElementsByName('form[author][a]['+i+']'))[0];
                        if(campo_a){
                            campo_a.value = aut.a;
                        }


                        // Apresentador
                        if(aut.p){
	                        if(aut.p==1){
	                            var campos_p = $A(document.getElementsByName('form[author][p]'));
	                            if(campos_p.length>0){
	                                campos_p.each(function(campo_p){
	                                    if(campo_p.value==i){
	                                        campo_p.checked = true;
	                                        // Email do Apresentador
	                                        if(resp.abs.emailP){
	                                            setPresentingEmail(campo_p, null, resp.abs.emailP);
	                                        }
	                                    }
	                                });
	                            }
	                        }
                        }

                        // Correspondente
                        if(aut.c){
	                        if(aut.c==1){
	                            var campos_c = $A(document.getElementsByName('form[author][c]'));
	                            if(campos_c.length>0){
	                                campos_c.each(function(campo_c){
	                                    if(campo_c.value==i){
	                                        campo_c.checked = true;
	                                        // Email do Correspondente
	                                        if(resp.abs.emailC){
	                                            setCorrespondingEmail(campo_c, null, resp.abs.emailC);
	                                        }
	                                    }
	                                });
	                            }
	                        }
                        }

    				});
    				
    				// insere campos revision
    				if(!$('campo_revision')){
    				    $('form_abstract').insert({top:'<input type="hidden" id="campo_revision" name="form[revision]" value="'+(resp.abs.revision+1) +'" />'});
    				}
    				
    				// atualiza sub titulo
    				setInnerHTML($('abs_subTitle'), strInfo['resubmitAbstract']+resp.abs.id);
    				
    				// insere botao NOVO
    				if(!$('boxNewAbs') && (absQde<absLimitePR || absLimitePR==0)){
    				    $('form_abstract').insert({top:'<div id="boxNewAbs" class="btn"><input type="button" value="'+strInfo['cancelRevision']+'" onclick="newAbs(); $(\'abs_form\').hide(); $(\'abs_newAbs\').show();" /></div>'});
    				}
    				
    				// Reativa campos
                    if ($('campo_imgCaption')){
                        window.setTimeout(function(){ $('campo_imgCaption').activate(); }, 500);
                    }
                    window.setTimeout(function(){ $('campo_abstract').activate(); }, 550);
                    window.setTimeout(function(){ $('campo_title').activate(); }, 600);
                    window.setTimeout(function(){ $((($('boxNewAbs'))?'boxNewAbs':'abs_subTitle')).scrollTo(); }, 650);
                    window.setTimeout(function(){ $('campo_title').blur(); }, 700);
                    
                    // escone as msg de erro
                    $$('.msgErro').invoke('hide');

    				// Exibe form
    				$('abs_form').show();
    				
    			},//onComplete
    			onFailure: function() {
    			    alertstrError(strError['function']['populaAbsForm']);
    			}//onFailure
    		});
	    }// else valida

	}// populaAbsForm

	function newAbs(){

	    // Remove Elementos
	    if($('boxNewAbs')){
	       $('boxNewAbs').remove();
	    }

	    if($('campo_revision')){
	       $('campo_revision').remove();
	    }


		// atualiza sub titulo
		setInnerHTML($('abs_subTitle'), strInfo['subTitle']);

		// remove Keywords
		$$('#tbody_keywords a.x').each(function(objKw){
		    removeKeyword(objKw);
		});

		// remove Aff
		$$('#tbody_aff a.x').each(function(objAff){
		    removeAffiliation(objAff);
		});

		// remove Authors
		$$('#tbody_authors a.x').each(function(objAut){
		    removeAuthor(objAut);
		});


	    // limpa campos do form e remove as classes
	    var campos =  $$('#form_abstract input[type=hidden], #form_abstract input[type=text], #form_abstract textarea');
	    ($('campo_hash_img'))? campos.push($('campo_hash_img')) : null;
	    ($('campo_hash_files'))? campos.push($('campo_hash_files')) : null;
	    ($('campo_imgCaption'))? campos.push($('campo_imgCaption')) : null;
	    campos.invoke('clear').invoke('removeClassName', campoClassNameOk).invoke('removeClassName', campoClassNameErro);
        //Copia Email
        $('campo_email').value = $F('pr_mail');


	    // esconde as msgs dos campos e msg de erro
	    $$('.msgField, .msgErro').invoke('hide');

	    // deseleciona os radios
	    $('form_abstract').getInputs('radio').each(function(campo){ campo.checked=false; });
	    // deseleciona os checkbox
	    $('form_abstract').getInputs('checkbox').each(function(campo){ campo.checked=false; });
	    
	    // Oculta editor Latex
	    if($('campo_latex')){
	    	editorLatex();
	    }
	    
	    // Tipos
	    typeDisable();
	    
	    // Oral Disable
	    if(oralDisabled==1){
	    	//$$('.oral').invoke('hide');
	    }
	    // Poster Disable
	    if(posterDisabled==1){
	    	//$$('.poster').invoke('hide');
	    }

	}
	
	
	function typeDisable(){
		// Oral
		if(oralDisabled==1){
			// desabilita input
			$('campo_tipo_oral').checked = false;
			$('campo_tipo_oral').disabled = true;
			// add classe disabled
			$('campo_tipo_oral_label').addClassName('disabled');
		}else{
			// habilita input
			$('campo_tipo_oral').disabled = false;
			
			// remove classe disabled
			$('campo_tipo_oral_label').removeClassName('disabled');
		}
		
		// Poster
		if(posterDisabled==1){
			// desabilita input
			$('campo_tipo_poster').checked = false;
			$('campo_tipo_poster').disabled = true;
			// add classe disabled
			$('campo_tipo_poster_label').addClassName('disabled');
		}else{
			// habilita input
			$('campo_tipo_poster').disabled = false;
			
			// remove classe disabled
			$('campo_tipo_poster_label').removeClassName('disabled');
		}

		// invited
		if(oralDisabled==1 &&posterDisabled==1){
			$('campo_tipo_invited').checked = true;
		}
		
		
	}






	/* Exibe o objeto que contem as instrucoes para preencher o campo */
	function showInstrucoes(){

		//Esconde Todas
		$$('.msgField').invoke('hide');

		// Campo: title
		valida('campo_title', limiteTitulo, 'title_left');

		// Campo: abstract
		valida('campo_abstract', limiteAbstract, 'abstract_left');

		// Campo: abstract
		if($('campo_imgFile')){
			Event.observe($('campo_imgFile'), 'click', function(){ showMsg($('campo_imgFile_INFO')); });
			Event.observe($('campo_imgFile'), 'focus', function(){ showMsg($('campo_imgFile_INFO')); });
			Event.observe($('campo_imgFile'), 'blur', function(){ hideMsg($('campo_imgFile_INFO')); });
		}

		// Campo: caption
		if($('campo_imgCaption')){
			validaCaption(limiteCaption, 'imgCaption_left');
		}

	}//function



	function valida(idCampo, limite, classRetorna){
		// Campo: abstract
		var campo	 	= $(idCampo);
		var msgInfo 	= $(idCampo+'_INFO');
		var msgOk 		= $(idCampo+'_OK');
		var msgErro 	= $(idCampo+'_ERRO');

			//Exibe msg Info
			Event.observe(campo, 'click', function(){ [msgOk, msgErro].each(hideMsg); showMsg(msgInfo); });
			Event.observe(campo, 'focus', function(){ [msgOk, msgErro].each(hideMsg); showMsg(msgInfo); });

			if(limite && classRetorna){

				//Esconder msg Info e valida
				Event.observe(campo, 'blur', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(validaCampo(campo)==true && limitaCampo(campo, limite, classRetorna)==true){
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}else{
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}
				});
				Event.observe(campo, 'keyup', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(validaCampo(campo)==true && limitaCampo(campo, limite, classRetorna)==true){
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}else{
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}
				});

			}// if
			else{

				//Esconder msg Info e valida
				Event.observe(campo, 'blur', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(validaCampo(campo)==true){
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}else{
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}
				});
				Event.observe(campo, 'keyup', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(validaCampo(campo)==true){
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}else{
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}
				});

			}// else

	}// function
	
	
	function validaAbsEn(idCampo, limite, classRetorna){
		// Campo: abstract
		var campo	 	= $(idCampo);
		var msgInfo 	= $(idCampo+'_INFO');
		var msgOk 		= $(idCampo+'_OK');
		var msgErro 	= $(idCampo+'_ERRO');
		
		//Exibe msg Info
		Event.observe(campo, 'click', function(){ [msgOk, msgErro].each(hideMsg); showMsg(msgInfo); });
		Event.observe(campo, 'focus', function(){ [msgOk, msgErro].each(hideMsg); showMsg(msgInfo); });
		
		
		//Esconder msg Info e valida
		Event.observe(campo, 'blur', function(){
			[msgInfo, msgOk, msgErro].each(hideMsg);
			if(limitaCampo(campo, limite, classRetorna, 1)==true){
				campo.removeClassName(campoClassNameErro);
				campo.addClassName(campoClassNameOk);
				showMsg(msgOk);
			}else{
				campo.removeClassName(campoClassNameOk);
				campo.addClassName(campoClassNameErro);
				showMsg(msgErro);
			}
		});
		Event.observe(campo, 'keyup', function(){
			[msgInfo, msgOk, msgErro].each(hideMsg);
			if(limitaCampo(campo, limite, classRetorna, 1)==true){
				campo.removeClassName(campoClassNameErro);
				campo.addClassName(campoClassNameOk);
				showMsg(msgOk);
			}else{
				campo.removeClassName(campoClassNameOk);
				campo.addClassName(campoClassNameErro);
				showMsg(msgErro);
			}
		});
			
		
	}// function



	function validaCaption(limite, classRetorna){
		// Campo: abstract
		var campo	 	= $('campo_imgCaption');
		var msgInfo 	= $('campo_imgCaption_INFO');
		var msgOk 		= $('campo_imgCaption_OK');
		var msgErro 	= $('campo_imgCaption_ERRO');
		// by lpanebr:
		var campoFigura = $('campo_figura');

			//Exibe msg Info
			Event.observe(campo, 'click', function(){ [msgOk, msgErro].each(hideMsg); showMsg(msgInfo); });
			Event.observe(campo, 'focus', function(){ [msgOk, msgErro].each(hideMsg); showMsg(msgInfo); });


			if(limite){

				//Esconder msg Info e valida
				Event.observe(campo, 'blur', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(($('campo_imgFile').value.length>0 && $('campo_imgCaption').value.length==0) || ($('campo_imgFile').value.length==0 && $('campo_imgCaption').value.length>0) || (limitaCampo(campo, limite, classRetorna)==false)){
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}else{
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}
				});
				Event.observe(campo, 'keyup', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(($('campo_imgFile').value.length>0 && $('campo_imgCaption').value.length==0) || ($('campo_imgFile').value.length==0 && $('campo_imgCaption').value.length>0) || (limitaCampo(campo, limite, classRetorna)==false)){
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}else{
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}
				});
				//
				// lpanebr:
				// adicionado para dar erro tbm se apagar o conteudo campo_imgFile
				// e para setar o hidden campo_figura como '' ou 1 se tem ou nao fig
				//
				Event.observe($('campo_imgFile'), 'change', function(){
				    campoFigura.value = ($('campo_imgFile').value.length==0)?'':'1';
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(($('campo_imgFile').value.length>0 && $('campo_imgCaption').value.length==0) || ($('campo_imgFile').value.length==0 && $('campo_imgCaption').value.length>0) || (limitaCampo(campo, limite, classRetorna)==false)){
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}else{
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}
				});

			}// if
			else{

				//Esconder msg Info e valida
				Event.observe(campo, 'blur', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(($('campo_imgFile').value.length>0 && $('campo_imgCaption').value.length==0) || $('campo_imgFile').value.length==0 && $('campo_imgCaption').value.length>0){
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}else{
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}
				});
				Event.observe(campo, 'keyup', function(){
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(($('campo_imgFile').value.length>0 && $('campo_imgCaption').value.length==0) || $('campo_imgFile').value.length==0 && $('campo_imgCaption').value.length>0){
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}else{
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}
				});
				//
				// lpanebr:
				// adicionado para dar erro tbm se apagar o conteudo campo_imgFile
				// e para setar o hidden campo_figura como '' ou 1 se tem ou nao fig
				//
				Event.observe($('campo_imgFile'), 'change', function(){
				    campoFigura.value = ($('campo_imgFile').value.length==0)?'':'1';
					[msgInfo, msgOk, msgErro].each(hideMsg);
					if(($('campo_imgFile').value.length>0 && $('campo_imgCaption').value.length==0) || $('campo_imgFile').value.length==0 && $('campo_imgCaption').value.length>0){
						campo.removeClassName(campoClassNameOk);
						campo.addClassName(campoClassNameErro);
						showMsg(msgErro);
					}else{
						campo.removeClassName(campoClassNameErro);
						campo.addClassName(campoClassNameOk);
						showMsg(msgOk);
					}
				});

			}
	}




	/* Exibe msg de info/ok/erro do campo */
	function showMsg(msg){
		//new Effect.Opacity(msg, {duration:1, from:0.0, to:1.0});
		msg.show();
	}

	/* Exibe msg de info/ok/erro do campo */
	function hideMsg(msg){
		//new Effect.Opacity(msg, {duration:1, from:1.0, to:0.0});
		msg.hide();
	}


	/* Se conter a classe de campo OK remove-a e adiciona a classe de campo ERRO, se ja nao conter*/
	function erroClass(campo){
		//remove classe OK
		campo.removeClassName(campoClassNameOk);

		//add classe Erro, se ja nao tiver
		var add = true;
		campo.classNames().each(function(classe){
			if(classe==campoClassNameErro){
				add = false;
			}
		});
		if(add==true){
			campo.addClassName(campoClassNameErro);
		}

	}

	/* Se conter a classe de campo ERRO remove-a e adiciona a classe de campo OK, se ja nao conter*/
	function okClass(campo){
		//remove classe Erro
		campo.removeClassName(campoClassNameErro);

		//add classe Erro, se ja nao tiver
		var add = true;
		campo.classNames().each(function(classe){
			if(classe==campoClassNameOk){
				add = false;
			}
		});
		if(add==true){
			campo.addClassName(campoClassNameOk);
		}

	}



	/* Remove os espacos em branco para realizar algumas validacoes */
	function removeEspaco(str){
		var retorna = str;
		var re = /\s/g;
		if(str.search(re) != -1){
			retorna = str.replace(re, '');
		}
		return retorna;
	}


	/* Valida Campo se esta preenchido */
	function validaCampo(campo){
		var value = removeEspaco(campo.value);
		//if (value==null || value=="" || value.length==0){
//		alert(campo.limit);
		if (value.length==0){
			return false;
		}else{
			return true;
		}
	}


	function isAuth(resp){
        if(resp.auth!=undefined){
            alert('Checa Auth: '+resp.auth);
            if(resp.auth==0){
                // redireciona
                window.location.href = "abstracts.php?deslogado=1";
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }
	}// isAuth()




	function geraPDF(hash){

		//AJAX
		var url = conUrl+'rpc/abstracts_pdf.php';
		var pars = '?hash='+hash;
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

				// Status
				submitStatus("4l");

			},//onLoading
			onComplete: function(originalRequest) {

				//Resposta da requisicao
				var resp = originalRequest.responseText;

				//alert(resp+"\n"+typeof(resp));

				// transforma JSON em Objeto
				resp = resp.evalJSON(true);

				// Auth?
				if(isAuth(resp)==false){
				    return false;
				}

				//alert(resp.erro+"\n"+typeof(resp.erro));

				// ERROS
				switch(resp.erro){
					// ERROS
					case 'S1':
					case 'S2':
					case "-1":
					case "-2":
					case "-3":
					case "-4":
					case "-5":
					case "-6":
						alert(strError['geraPDF'][resp.erro]);
					break;

					// OK
					default:
						//
						// by lpanebr
						// para não mostrar a etapa3 se o cara abortou na geracao do pdf...
						// util pra quando trava nesse ponto
						//
						if(!pdfGenerationAborted) {
							// Status
							submitStatus("4");

							// Link do PDF
							$('PDF_link').writeAttribute('href', resp.pdf);
							// Link do LOG
							if($('campo_latex')){
								if($('campo_latex').checked==true){
								    $('PDF_linkLog').writeAttribute('href', resp.log);
	        						// by lpanebr
	        						// esconde o loglink sempre
	        						// para não confundir os usuários leigos...
								    $('PDF_linkLog').hide();
								}else{
								    $('PDF_linkLog').writeAttribute('href', '');
								    $('PDF_linkLog').hide();
								}
							}else{
							    $('PDF_linkLog').writeAttribute('href', '');
							    $('PDF_linkLog').hide();
							}

							// Arquivo PDF
							//$('PDF_arquivo').innerHTML = resp.pdfName;
							setInnerHTML($('PDF_arquivo'), resp.pdfName);
							
							if(filesSentResult){
								// Gera lista dos arquivos Enviados
								var filesList = filesSentList(filesSentResult, filesSentModel);
								
		        				// exibe na pagina
		                        setInnerHTML($('abs_filesSent_list'), filesList);
		                        
		                        // exibe divs
		                        $('abs_filesSent','abs_fileSentReport').invoke('show');

							}else{
								// oculta divs
								$('abs_filesSent','abs_fileSentReport').invoke('hide');
							}
	                        // oculta relatório
	                        $('fileReport','fileReportHide').invoke('hide');
	                        $('fileReportShow').show();


							// OK, exibe proximo passo!!
							showEtapa(3);
						}
						// resetar a variavel pdfGenerationAborted
						else {
							pdfGenerationAborted = false;
						}
					break;
				}


			},//onComplete
			onFailure: function() {
			    alertstrError(strError['function']['geraPDF']);
			}//onFailure
		});

	}// geraPDF()
	
	function filesSentList(objJSON, template){
		// Gera lista dos arquivos Enviados utilizando os Templates do prototype
		var tpl = new Template(template);
		
		var i = 0;
		var max = objJSON.length;
		var htmlFiles = '';
		
		// loop
		for(i=0;i<max;i++){
        	htmlFiles = tpl.evaluate(objJSON[i]);
		}// for

		// retorna
		return htmlFiles;
	}


	function figureUpdate(imgFile, hash){

		//alert('figureUpdate('+imgFile+', '+hash+')');

		//AJAX
		var url = conUrl+'rpc/abstracts_img.php';
		var pars = '?imgFile='+imgFile+'&hashImg='+hash;
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

			},//onLoading
			onComplete: function(originalRequest) {

				//Resposta da requisicao
				var resp = originalRequest.responseText;

				//alert(resp);
				//alert(typeof(resp));

                // Auth?
				if(isAuth(resp)==false){
				    return false;
				}

				switch(resp){
					case '1':
						// status
						submitStatus("2");
						if(filesToUpload()){
							// envia arquivos
							filesUpload();
						}else{
							// TEX e PDF
							geraPDF(hash);
						}
					break;

					case '0':
					case '-1':
					case 'S1':
					case 'S2':
						alert(strError['figureUpdate'][resp]);
					break;

				}

			},//onComplete
			onFailure: function() {
			    alertstrError(strError['function']['figureUpdate']);
			}//onFailure
		});

	}// figureUpdate()

	
	function removeFile(sid){
		
		//alert('removeFile('+sid+')');
		
		var loadId = 'removeFileLoad'+Math.round((Math.random() * 10000));
		
		//AJAX
		var url = conUrl+'rpc/abstracts_files.php';
		var pars = '?sid='+sid+'&hash='+$F('campo_hash');
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
		onLoading: function() {
			$('file'+sid).insert({bottom:'<span id="'+loadId+'"><img src="../imgsSys/ajax_load.gif" /> '+strInfo['removeFileLoad']+'...</span>'});
		},//onLoading
		onComplete: function(originalRequest) {
			
			//Resposta da requisicao
			var resp = originalRequest.responseText;
			
			//alert(resp);
			//alert(typeof(resp));
			
			// Auth?
			if(isAuth(resp)==false){
				return false;
			}
			
			// remove load
			//$(loadId).remove();
			
			// ok
			if(resp=='1'){
				$('file'+sid).remove();
				//$('form_files').reset();
				$('form_files','abs_fileRemoved').invoke('show');
			}
			// erros
			else{
				alert(strError['fileRemoveError'][resp]);
			}
			
			
		},//onComplete
		onFailure: function() {
			alertstrError(strError['function']['removeFile']);
		}//onFailure
		});
		
	}// removeFile()
	

/* UPLOAD IMG*/

	function figureUpload(){
		// Status do Botao
		submitStatus("2l");
		//upload
		uploadFile($('form_img'), $('imgLoad'));
		// Status do Botao
		//submitStatus("2");
	}
	
	function filesUpload(){
		// Status do Botao
		submitStatus("3l");
		//upload
		uploadFile($('form_files'), $('filesLoad'));
		// Status do Botao
		//submitStatus("2");
	}
	
	function finishUploadFiles(resp,hash) {
		//alert('finishUploadFiles('+resp+');');

		// oculta load
		$('abs_result3l').hide();
		
		//alert('typeof(resp): '+typeof(resp));
		
		switch(typeof(resp)){
			
			// ERRO
			case 'string':
				alert(strInfo['filesUpdate'][resp]);
				return false;
			break;
			
			// OBJ JSON **OK**
			case 'object':
				// inicia vars
				var relatorio = '';
				var comErro = i = 0;
				var max = resp.files.length;
				//alert('resp.files.length: '+max);
				
				
				// loop
				for(i=0;i<max;i++){
					var file = resp.files[i];
					
					// Relatorio
					relatorio += (relatorio.length>0)?'<br />':'';
					relatorio += strInfo['filesUpdate']['id'];
					relatorio += (max>1)?' Nº'+file.id+' "':' ';
					relatorio += '"'+file.name+'" - ';
					
					// sucesso
					if(file.erro==0){
						// limpa campo
						//$('campo_file'+file.id).value = '';
						//$('campo_file'+file.id).clear();
						// armazena
						var labelHtml = $('labelFile'+file.id).innerHTML;
						// limpa
						setInnerHTML($('labelFile'+file.id), '');
						// insere
						$('labelFile'+file.id).insert(labelHtml);
						
						
						// Relatorio
						relatorio += strInfo['filesUpdate']['ok'];
					}
					// erro
					else{
						// seta erro
						comErro = 1;
						
						// Relatorio
						relatorio += strInfo['filesUpdate']['error']+': '+strInfo['filesUpdate'][file.erro]+'';
					}
					
				}// for
				
				// ocula msg de removido
				$('abs_fileRemoved').hide();
				
				// Atualiza e exibe relatorio dos arquivos
				setInnerHTML($('abs_result3'), relatorio);
				setInnerHTML($('fileReport'), relatorio);
				$('abs_result3').className = 'submitStatus';
				$('abs_result3').addClassName(((comErro==0)?'msgOk':'msgErro'));
				submitStatus('3');

				// Armazena o Objeto da Resposta
				filesSentResult = resp.files;
				
				/*
				// Armazena HTML modelo dos arquivos enviados
				filesSentModel = (filesSentModel!='')? filesSentModel : $('abs_filesSent').innerHTML;
				// limpa modelo da página
				setInnerHTML($('abs_filesSent'), '');
				*/
				
				if(comErro==0){
					// oculta form
					$('form_files').hide();
					
					var filesSent = filesSentList(resp.files, filesSentRemoveModel);
					setInnerHTML($('filesSent'), filesSent);
					
					// TEX e PDF
					geraPDF(hash);			
				}else{
				}
				
			break;
			
			// Outra Resposta **ERRO** 
			default:
				alert(strInfo['filesUpdate']['unknown']+' '+typeof(resp));
			break;
		
		}// switch(typeof(resp))

	}// finishUploadFiles()

	function uploadFile(formId, loadId) {

		// oculta erros
		$('imgErro1', 'imgErro2', 'imgErro3', 'imgErro4').invoke('hide');

		// show Load
		//(loadId.visible()==false) ? loadId.show() : null;

		// Submit Form
		$(formId).submit();

	}

	function hideUploadMsg(msgId){
		if(msgId){
			$('imgErro'+msgId).hide();
		}else{
			$$('.msgFigureErro').invoke('hide');
		}
	}

	function finishUpload(imgFile,loadId) {
		//alert('finishUpload('+imgFile+', '+loadId+');');

		// oculta load
		$(loadId).hide();

		// atualiza registro
		figureUpdate(imgFile, $('campo_hash').value);
	}

	function uploadError(idErro, loadId) {

		//alert('uploadError('+idErro+', '+loadId+')');

		// oculta load
		hideStatus("2l")

		// show erro
		$('imgErro'+idErro).show();

		// scroll
		$('imgErro'+idErro).scrollTo();

	}

	function hideUpload(originalRequest) {
		var res = originalRequest.responseText;

		aux 	= res.split(":");
		id		= aux[0];
		oldId	= aux[1];
		html	= aux[2];

		idForm = 'fileForm_'+oldId;
		idFile = 'File_'+oldId;
		$(idForm).remove();
		//$(idFile).innerHTML = html;
		setInnerHTML($(idFile), html);
	}

    function alertstrError(erro){
        alert(strError['function']['header']+erro);
    }
    
    function filesToUpload(){
    	var retorna = false;
    	var i;
    	
    	for(i=0;i<=filesLimite;i++){
    		if($('campo_file'+i)){
	    		if($F('campo_file'+i)){
	    			retorna = true;
	    			break;
	    		}
    		}
    	}
    	
    	return retorna;
    }

//alert('Fim do Arquivo: abstracts.js');
