/* Pre Register */

//alert('Inicio do Arquivo: preRegister.js');

Event.observe(window, 'load', inicial);

function inicial(){

    //alert('Função: inicial');
    //
    
    if($('preRegister')){
        if(1 == $('openPreReg').value){
            openPreRegister();
        }else{
            // Expande Form no Click
            Event.observe($('openForm'), 'click', function(event){
                openPreRegister();
            });

            // Expande Form via parametro GET
            if(String(window.location).match('preRegister=1')!=null){
                openPreRegister();
            }
        }
    }
		
		
		
    // Title
    Event.observe($('title'), 'change', function(event){
        showOther();
    });

    // UF - Pais
    //Event.observe($('country'), 'change', function(){ showOtherUf(); });

    //Submete Form
    Event.observe($('btn_prereg'), 'click', function(event){
        submitPreRegister();
    });

    /**
		* efeitos...
		*/

       

    if($('glow')){
        new Effect.Highlight($('glow'), {
            startcolor:'#f5f5f5',
            endcolor:'#FFFF99',
            duration: 1.0
        });
        new PeriodicalExecuter(function(pe) {
            new Effect.Highlight($('glow'), {
                startcolor:'#f5f5f5',
                endcolor:'#FFFF99',
                duration: 1.0
            });
        }, 2);
    }

//alert('/Função: inicial');

    

}//inicial


function openPreRegister(){
    //Esconde TODAS msgs
    $$('.frmMsg').invoke('hide');

    //Abre
    new Effect.toggle($('preRegister'),'blind',{
        afterFinish:function(){
            if(!$('sisDbDown')){// Se não estiver down
                $('name').activate();
            }
        }
    });
}// openPreRegister()

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
            $$('.frmMsg').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.');
            }
            // Ok
            else{

                //facilita
                var valido 	= resp.valido;
                var erros 	= resp.erros;
                var mail 	= resp.mail;
                var bd 		= resp.bd;
    
                debug(originalRequest.responseText);
    				
                //alert("valido: "+valido+"\n" + "erros: "+erros+"\n" + "mail: "+mail+"\n" + "bd: "+bd);
    
                //Verifica se esta valido
                if(valido==1){
    
                    //Erro BD
                    if(bd==0){
                        //msg de erro no persist
                        $('erroBD').show();
                    }
                    // Duplicado
                    else if(bd==-1){
                        //msg de Email DUPLICADO
                        $('erroMail').show();
                    }
                    //EMAIL enviado
                    else if(mail==1){
    
                        //frufu
                        new Effect.toggle($('preRegister'),'blind');
    						
                        // Copia nome para a msg de sucesso
                        $('pr_nameStr').innerHTML = $F('name');
    						
                        // Integração para Submissão
                        if($('pr_absLink')){
                            // exibe msg
                            $('pr_absLink').show();
    						
                            //  melhora Link
                            $('pr_submitLink').writeAttribute('href', $('pr_submitLink').readAttribute('href')+'?email='+$F('email'));
                        }
    						
                        //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{
    
                    var showBoxErro = false;
    
                    //LOOP nos inputs do FORM
                    dados.getElements().each(function(v, k){
    
                        var vId = v.id;
                        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').value == 'other'){
        $('otherLabel').show();
        $('other').activate();
    }else{
        $('otherLabel').hide();
    }
}


function showOtherUf() {
    if ($('country').value != 'BR'){
        $('otherUfLabel').show();
        $('stateSelect').hide();
    }else{
        $('stateSelect').show();
        $('otherUfLabel').hide();
    }
}

//alert('Fim do Arquivo: preRegister.js');