/* Scripts espeficicos para o form de Abstracts */

//alert('Inicio do Arquivo: abstracts.js');



//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;

// LIMITES de preenchimento para campos
var limiteTitulo 	= 100;
var limiteAbstract 	= 1500;
var limiteCaption 	= 200;

// 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;




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(); });
	
	//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
	Event.observe($('campo_latex'), 'click', function(event){ editorLatex(); });
	
	$('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); });





	//alert('/Função: inicial');

}//inicial

	function editorLatex(){
	    if($('campo_latex').checked==true){
	        $$('.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
						case '0':
							alert('Error updating the status.');
						break;
						case '-1':
							alert('Error: image hash not found.');
						break;
						case '-2':
							alert('Error: delivery abstract attachments failed.');
						break;
						case '-3':
							alert('Error compressing (ZIP) abstracts files.');
						break;
						
                        case '-5':
                            alert("Error: could not save the Authors data in the database.\n\nPlease try again and if the error persists notify the webmaster!");
                        break;
                        case '-6':
                            alert("Error: could not save the affiliations data in the database.\n\nPlease try again and if the error persists notify the webmaster!");
                        break;
                        case '-7':
                            alert("Error: could not save the keywords data in database.\n\nPlease try again and if the error persists notify the webmaster!");
                        break; 						
						

    					case 'S1':
    						alert('Error: incorrect hashes.');
    					break;

    					case 'S2':
    						alert('Error: object from absctract not found.');
    					break;

					}

				},//onComplete
				onFailure: function() {
				    alertMsgError('Error: function finish() resquest failed.');
				}//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').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: figure (opcional)
			// caption
			if($('campo_imgCaption').hasClassName(campoClassNameErro)==true){
				//show erro
				$('campo_imgCaption').addClassName(campoClassNameErro);
				showMsg($('campo_imgCaption_ERRO'));
				//erro
				erro = true;
			}



		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() {
			    alertMsgError('Error: function forgotPass() resquest failed!');
			}//onFailure
		});

	}// forgotPass()


	function submitAbs(){

	/* ENVIA DADOS */

		//Dados
		var form	= $('form_abstract');

		//AJAX
		var url = conUrl+'rpc/abstracts.php';
		var pars = form.serialize()+"&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");

					switch(resp){
						case '-1':
							alert("Error: empty field(s)!");
						break;
						case '-2':
							alert("Error: e-mail not found on pre-register!");
						break;
						case '-3':
							alert("Error: maximum limit of "+absLimitePresenting+" Abstracts per presenting Author reached.");
						break;
                        case '-4':
                            alert("Error: could not save the Abstract data in the database.\n\nPlease try again and if the error persists notify the webmaster!");
                        break;
                        case '-5':
                            alert("Error: could not save the Authors data in the database.\n\nPlease try again and if the error persists notify the webmaster!");
                        break;
                        case '-6':
                            alert("Error: could not save the affiliations data in the database.\n\nPlease try again and if the error persists notify the webmaster!");
                        break;
                        case '-7':
                            alert("Error: could not save the keywords data in database.\n\nPlease try again and if the error persists notify the webmaster!");
                        break; 						
					}
				}
				// OK
				else if(resp.length==32){

					// Hash
					$('campo_hash').value 		= resp;
					$('campo_hash_img').value 	= resp;

					// oculta msg das etapas anteriores =D
					$$('.pr_frmMsg, .pass_frmMsg').invoke('hide');

					// Status
					submitStatus("1");

					// Img
					if($('campo_imgFile').value.length>0){
						// upload
						figureUpload();
					}else{
						// TEX e PDF
						geraPDF(resp);
					}

				}
				else{
					hideStatus("1l");
					alert("BUG\nresp: "+resp);
				}

			},//onComplete
			onFailure: function() {
			    alertMsgError('Error: function submitAbs() resquest failed!');
			}//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() : null;
				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();
				//if(msgs==1){}
			break;
		}

	}



	function limitaCampo(campo, limite, classRetorna){

		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> character left.</span>';
				// retornaBool
				retornaBool = true;
			}else{
				// retorna
				resto = ', <strong class="campoClassNameErro">'+Math.abs(resto)+'</strong> character(s) exceeded!</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> character(s) left!</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;

			// remove espaços
			n = n.strip();

			// 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');

		// 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("This field is mandatory.");
		}
		//Verifica Duplicidade
		else if(dup == true){
			// Erro
			alert("This author name is already registered.");
		}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="50">';
            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'));

		}

		// 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'));

	}

	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], html);

			// 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()

	}

	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("Please enter a valid e-mail address for \""+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("Please enter a valid e-mail address for \""+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('You may only add up to '+keywordsLimite+' keywords');
		        return false;
		    }
			
			words.each(function(word){
				
				// remove espaços em branco
				word = word.strip();
				
				if(word.length>0){

				    if($$('#tbody_keywords tr').length >= keywordsLimite){
				        alert('You may only add up to '+keywordsLimite+' keywords');
				        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("This field is mandatory");
		}

		// 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');

		//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("This field is mandatory");
		}

		// 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){
                            $('boxPassC').show();
                       }

			           // alterna forms
                       $('form_pr','form_pass','pass_'+pass).invoke('toggle');

					   // focus no campos
					   $('campo_pass').activate();
					break
				}

			},//onComplete
			onFailure: function() {
			    alertMsgError('Error: function findPreRegister() resquest failed!');
			}//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('Passwords do not match. Please try again.');
		    $('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: 546px; margin-bottom: 25px; padding:5px; background-color:#f9f9f9;'>";
    						html += "<h4 style='padding:0;margin:0 0 10px 0;'>"+ abs.title +" (submitted for "+abs.event+")</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='PDF File' align='left' /></a>";
            						    }else{
            						      html += "<img src='"+imgUrl+"filetype_small_pdf.gif' alt='PDF File Removed' title='PDF File Removed' align='left' />";
            						    }
                						html += "&nbsp;<strong>"+absOld.revision+"</strong> - "+absOld.date;
            						    html += "</div>";
        						    });
        						}
    						}

    						html += "<a href='"+abs.url+"' target='_blank'><img src='"+imgUrl+"filetype_big_pdf.gif' alt='PDF File' align='left' /></a>";
        					html += "This is your <strong>"+ ((abs.revision>0)?"abstract revision #"+abs.revision:"originally submitted abstract") +"</strong> sent "+abs.date+"<br />";
    						html += "Abstract status: <strong>"+abs.status+"</strong>";
    						html += ((abs.status=='Accepted')?' for <strong>'+abs.typeFinal+'</strong> presentation':"");
    						if(abs.parecer.length>0){
        						html += "<div style='float:right'  ><strong><a href='#toggleEvaluation' onClick=\"$('abs_parecer"+i+"','strParecer"+i+"v','strParecer"+i+"o').invoke('toggle');\" style='margin-rigth:5px;'><img src='"+imgUrl+"zoom.png' alt='zoom icon' title='click to toggle evaluation' align='left' /><span id='strParecer"+i+"v'>View</span><span id='strParecer"+i+"o' style='display:none;'>Hide</span> status and evaluations history</strong></a></div><br /><div>&nbsp;</div>";
        						html += "<em id='abs_parecer"+i+"' style='display:none;'><br />"+unescape(abs.parecer)+"</em>";
    						}
    						if(abs.corrigir==1){
    							showInfoMsg = 1;
    							html += '<div style="float:right"  ><a href="#sendRevisedVersion" onclick="populaAbsForm(\''+abs.hash+'\')"><img src="'+imgUrl+'ico_editar.gif" alt="edit icon" title="click to send revised version" align="left" /><strong>send revised version</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);

    				}
    				
    				// 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() {
			    alertMsgError('Error: function auth() resquest failed!');
			}//onFailure
		});

	}// function

	function populaAbsForm(hash){
	    // debug
	    //alert("HASH: "+hash);

	    //  verifica
	    if(hash.length!=32){
	        alert('Error: Invalid 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 = $('campo_hash_img').value = resp.abs.hash;
    				$('campo_evento_'+resp.abs.event).checked = true;
    				
    				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;

    				$('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'), 'Resubmit Abstract #'+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="Cancel revision" onclick="newAbs(); $(\'abs_form\').hide(); $(\'abs_newAbs\').show();" /></div>'});
    				}
    				
    				// Reativa campos
                    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() {
    			    alertMsgError('Error: function populaAbsForm() resquest failed!');
    			}//onFailure
    		});
	    }// else valida

	}// populaAbsForm

	function newAbs(){

	    // Remove Elementos
	    if($('boxNewAbs')){
	       $('boxNewAbs').remove();
	    }

	    if($('campo_revision')){
	       $('campo_revision').remove();
	    }


		// atualiza sub titulo
		setInnerHTML($('abs_subTitle'), 'Abstract Submission');

		// 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');
	    campos.push($('campo_hash_img'));
	    campos.push($('campo_imgCaption'));
	    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
	    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
		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
		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 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 = uploadUrl+'rpc_abstracts_pdf.php';
		var pars = '?hash='+hash;
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

				// Status
				submitStatus("3l");

			},//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':
						alert('Error: incorrect hashes.');
					break;

					case 'S2':
						alert('Error: object from absctract not found.');
					break;

					case "-1":
						alert('Error: hash not found.');
					break;
					case "-2":
						alert('Error creating TEX file.');
					break;
					case "-3":
						alert('Error writing to TEX file.');
					break;
					case "-4":
						alert('Error closing TEX file.');
					break;
					case "-5":
						alert('Error generating PDF file.');
					break;
					case "-6":
						alert('Error generating LOG file.');
					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("3");

							// Link do PDF
							$('PDF_link').writeAttribute('href', resp.pdf);
							// Link do LOG
							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();
							}

							// Arquivo PDF
							//$('PDF_arquivo').innerHTML = resp.pdfName;
							setInnerHTML($('PDF_arquivo'), resp.pdfName);

							// OK, exibe proximo passo!!
							showEtapa(3);
						}
						// resetar a variavel pdfGenerationAborted
						else {
							pdfGenerationAborted = false;
						}
					break;
				}


			},//onComplete
			onFailure: function() {
			    alertMsgError('Error: function geraPDF() resquest failed!');
			}//onFailure
		});

	}// geraPDF()


	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");
						// TEX e PDF
						geraPDF(hash);
					break;
					case '0':
						alert('Error while updating file name on register.');
					break;
					case '-1':
						alert('Error: image hash not found.');
					break;

					case 'S1':
						alert('Error: incorrect hashes.');
					break;

					case 'S2':
						alert('Error: object from absctract not found.');
					break;

				}

			},//onComplete
			onFailure: function() {
			    alertMsgError('Error: function figureUpdate() resquest failed!');
			}//onFailure
		});

	}// figureUpdate()

/* UPLOAD IMG*/

	function figureUpload(){
		// Status do Botao
		submitStatus("2l");
		//upload
		uploadFile($('form_img'), $('imgLoad'));
		// Status do Botao
		//submitStatus("2");
	}

	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 alertMsgError(erro){
        alert('Error\n\nReload this page and try again, if the error persists inform the error message to the system developer:\n\n'+erro);
    }

//alert('Fim do Arquivo: abstracts.js');
