/* Pre Register */

//alert('Inicio do Arquivo: preRegister.js');


/*
 * JQUery
 * 
*/
var $j = jQuery.noConflict();
$j(document).ready(function(){
	$j("#openForm").click(function () {
		$j("#preRegister").slideToggle("slow");
		// Esconde TODAS msgs
		$j('.pr_formMsg').hide();
	});
});


Event.observe(window, 'load', inicial);

function inicial(){

	//alert('Função: inicial');
	
		//Expande Form
		/*if($('openForm')){
			$('openForm').observe('click', function(event){
				//Abre
				new Effect.toggle($('preRegister'),'blind',{
					afterFinish:function(){
						$('name').activate();
					}
				});
				//Esconde TODAS msgs
				$$('.pr_formMsg').each(Element.hide);
			});
		}
		*/
		
		// Title
		if($('title')){
			$('title').observe('change', function(event){ showOther(); });
		}

		//Submete Form
		if($('btn_prereg')){
			$('btn_prereg').observe('click', function(event){ submitPreRegister(); });
		}

	//alert('/Função: inicial');

}//inicial

	function submitPreRegister(){

		//Dados
		var dados	= $('preRegister');

		//AJAX
		var url = 'congress/rpc/preRegister.php';
		var pars = dados.serialize();
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {

				//Esconde TODAS msgs
				$$('.pr_formMsg').invoke('hide');

				//Load - exibe
				while($('load').visible()==false){
					$('load').show();
				}

			},//onLoading
			onComplete: function(originalRequest) {

				//Load - esconde
				while($('load').visible()==true){
					$('load').hide();
				}

				//Resposta da requisicao
				var resp = originalRequest.responseText;

				//transforma JSON em Objeto
				resp = resp.evalJSON(true);
				
				// Loser
				if(resp.loser){
					// alert
					//alert('Our system thinks that the form was filled by an automatic script.\n\nPlease contact technical support and inform the problem.');
					alert('O nosso sistema acha que o formulário foi preenchido por um script automático.\n\nPor favor, contacte o suporte técnico e informe o problema.');
				}
				// Ok
				else{

    				//facilita
    				var valido 	= resp.valido;
    				var erros 	= resp.erros;
    				var mail 	= resp.mail;
    				var bd 		= resp.bd;
    				var bdPub 	= resp.bdPub;
    
    				debug(originalRequest.responseText);
    				
    				//alert("valido: "+valido+"\n" + "erros: "+erros+"\n" + "mail: "+mail+"\n" + "bd: "+bd+"\n" + "bdPub: "+bdPub);
    
    				//Verifica se esta valido
    				if(valido==1){
    					debug('valido');
    
    					// Duplicado
    					if(bd==-1){
    						debug('duplicado');
    						//msg de Email DUPLICADO
    						$('erroMail').show();
    					}    
    					
    					//Erro BD
    					else if(bd==0  || bdPub==0){
    						debug('erro bd');
    						//msg de erro no persist
    						$('erroBD').show();
    					}

    					//EMAIL enviado
    					else if(mail==1){
    						debug('enviou email');
    
    						//frufu
    						$j("#preRegister").slideToggle("slow");
    						
    						//Copia endereco de email para a msg de sucesso
    						setInnerHTML($('pr_nameStr'), $F('name'));
    						
    						// link para submissão
    						if($('pr_submitLink')){
    							$('pr_submitLink').writeAttribute('href', $('pr_submitLink').readAttribute('href')+'?email='+$F('email'));
    						}
    						
    						// Link para Minicurso
    						if($('pr_minicursoLink')){
    							$('pr_minicursoLink').writeAttribute('href', $('pr_minicursoLink').readAttribute('href')+'?email='+$F('email'));
    						}
    						
    						
    						// Msg Apresentador
    						if(mail==1){
    							$('txtAcesso').show();
    						}
    						
    						//msg de sucessso
    						$('sucesso').show();
    
    						//Limpa os campos
    						dados.reset();
    
    						//Remove as classes de Erro
    						$$('#'+dados.id+' input, #'+dados.id+' p, #'+dados.id+' label').invoke("removeClassName", "campoErro").invoke("removeClassName", "labelErro");
    
    					}
    
    				}else{
    					debug('INVALIDO');
    
    					var showBoxErro = false;
    
    					//LOOP nos inputs do FORM
    					dados.getElements().each(function(v, k){
    
    						var vId = v.id;
    						
    						if(vId){
	    						debug("Validando: "+vId);
	    
	    						//Define qual classe deve ser utilizada
	    						switch(vId){
	    							// Sex
	    							case 'sexM':
	    							case 'sexF':
	    								vId = "sex";
	    								classAdd = "labelErro";
	    							break;
	    							
	    							// Student
	    							case 'stud0':
	    							case 'stud1':
	    								vId = "student";
	    								classAdd = "labelErro";
	    							break;
	    
	    							// Congress
	    							case 'cong0':
	    							case 'cong1':
	    							case 'cong2':
	    								vId = "congress";
	    								classAdd = "labelErro";
	    							break;
	    							
	    							// Apresentador
	    							case 'apre0':
	    							case 'apre1':
	    								vId = "apresentador";
	    								classAdd = "labelErro";
	    							break;
	    							
	    							// Title
	    							case 'title':
	    								vId = "titleLabel";
	    								var vIdRpc = "title";
	    								classAdd = "labelErro";
	    							break;
	    							
	    							default:
	    								classAdd = "campoErro";
	    							break;
	    						}
	    
	    						var campoErro = eval('erros.'+((vIdRpc)?vIdRpc:vId));
	    						
	    						debug("campoErro: "+campoErro);
	    
	    						// COM ERRO
	    						if(campoErro==1){
	    							if($(vId).hasClassName(classAdd)==false){
	    								$(vId).addClassName(classAdd);
	    								debug("ERRO: "+vId+" [ADD CLASS: "+classAdd+"]");
	    								
	    								// add class no LABEL tb
	    								if($(vId).up().nodeName=="LABEL"){
	    									$(vId).up().addClassName("labelErro");
	    									debug("ERRO: LABEL do "+vId+" [ADD CLASS: labelErro]");
	    								}
	    								
	    							}else{
	    								debug("ERRO: "+vId+" [NO ADD CLASS]");
	    							}
	    
	    							//define que deve ser exibido o box de erro
	    							showBoxErro = true;
	    
	    						}
	    						// SEM ERRO
	    						else if(campoErro==0){
	    							if($(vId).hasClassName(classAdd)==true){
	    								$(vId).removeClassName(classAdd);
	    								debug("Removeu class de erro: "+vId);
	    							}
	    							// remove class no LABEL tb
	    							if($(vId).up().nodeName=="LABEL"){
	    								if($(vId).up().hasClassName("labelErro")==true){
	    									$(vId).up().removeClassName("labelErro");
	    									debug("Removeu class de erro do LABEL do: "+vId);
	    								}								
	    							}
	    							debug("OK: "+vId);
	    						}
	    
	    						debug("- - - - - - - - - - - - - - - - - ");
	    						
    						}
    
    					});// fim do LOOP
    
    
    				}// Else VALIDO
    
    
    				//Exibe/Esconde box de erro
    				if(showBoxErro==true){
    					$('erro').show();
    				}else if($('erro').visible()==true){
    					$('erro').hide();
    				}

				}

			},//onComplete
			onFailure: function() {

			}//onFailure
		});

	}// submitPreRegister()
	
	
	function showOther() {
		if ($('title').selectedIndex == 6){
			$('otherLabel').show();
			$('other').activate();
		}else{
			$('otherLabel').hide();
		}
	}	

//alert('Fim do Arquivo: preRegister.js');
