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

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

function inicial(){

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

	//Areas de Interesse
	if($('areas_interesse')){
		//alert('areas_interesse');
		var area_box = document.getElementsByClassName('ai_box');
		if(area_box.length>0){
			for(i=1; i<=area_box.length; i++){
				//alert($('area'+i).id);
				Event.observe($('area'+i), 'click', function(){AreaInteresse(this,area_box.length)}, false);
			}//for
		}//if
	}



    /**
     *
     * Encontre um Anatomista
     *
    **/
    if ($('formBuscaAnatomista')){
        
        Event.observe($('linkBuscaAnatomista'), 'click', function (){ $('linkBuscaAnatomista').hide(); $('formBuscaAnatomista').show(); });
//        Event.observe($('buttonBuscaAnatomista'), 'click', function (){ $('formBuscaAnatomista').hide(); $('linkBuscaAnatomista').show(); });

    }


    //Form para inscrição da newsletter - Home
    if ($('news_nome')){

        //entra na funcao - quando carregar a página
        retiraValor($('news_nome'), 'nome');
        retiraValor($('news_email'), 'email');

        //Quando o campo recebe o focus, retira o value inicial do campo automaticamente
        Event.observe($('news_nome'), 'click', function(){ retiraValor($('news_nome'), 'nome'); } );
        Event.observe($('news_email'), 'click', function(){ retiraValor($('news_email'), 'email'); } );

        //entra na funcao - quando carregar a página
        repoemValor($('news_nome'), 'nome');
        repoemValor($('news_email'), 'email');

        //Quando o campo sai do focus, volta com o value inicial (caso o campo está vazio)
        Event.observe($('news_nome'), 'blur', function(){ repoemValor($('news_nome'), 'nome'); } );
        Event.observe($('news_email'), 'blur', function(){ repoemValor($('news_email'), 'email'); } );

    }//fim if


    //Form para se logar no sistema - Home
    if ( $('user_login') ){

        //entra na funcao - quando carregar a página
        retiraValor($('user_login'), 'login ou email');

        //Quando o campo recebe o focus, retira o value inicial do campo e muda o type do input
        Event.observe($('user_login'), 'focus', function(){ retiraValor($('user_login'), 'login ou email'); } );
        Event.observe($('user_senha'), 'focus', function(){ 
                                                            retiraValor($('user_senha'), 'senha');
                                                        });
        //entra na funcao - quando carregar a página
        repoemValor($('user_login'), 'login ou email');

        //Quando o campo sai do focus, volta com o value inicial (caso o campo está vazio) e muda o type do input
        Event.observe($('user_login'), 'blur', function(){ repoemValor($('user_login'), 'login ou email'); } );
        Event.observe($('user_senha'), 'blur', function(){
                                                            repoemValor($('user_senha'), 'senha');
                                                        });
    }//fim if


    //Form de aprovação do sócio - admin
    if ( $('camposDataAprov') ){

        Event.observe($('idAprovar'), 'focus', function(){ $('camposDataAprov').show(); } );
        Event.observe($('idIgnorar'), 'focus', function(){ $('camposDataAprov').hide(); } );

    }


    //Endereço alternativo de correspondencia
    if ( $('field_corresp_endereco') ){

        //obtém os elementos de forma de um array pelo name
        ends = $A( document.getElementsByName('form[socio_correspondencia]') );
        
        //loop
        ends.each(function(campo){
            
            checaEnderecoAlternativo(campo);

            Event.observe(campo.id, 'click', function() { checaEnderecoAlternativo(campo); });
            
        });

    }


    //Titulação / Formação Acadêmica
    if ( $('pro_titulacao') ){
        titulacao(false);
        Event.observe($('pro_titulacao'), 'change', function(){ titulacao(true); });
    }

    //Justificativa da situação
    if ( $('just_sit')){
        Event.observe($('just_sit'), 'change', function(){ justSit(); });
    }

	//Add Cobrança
	if($('label_para')){

		//alert('Entrou no Esquema');

		addCobranca();

		var cob_para = document.getElementsByClassName('cob_para');
		if(cob_para.length>0){
			for(i=0; i<=(cob_para.length-1); i++){
				//alert(cob_para[i].id);
				ObsCobranca(cob_para[i]);
			}//for
		}//if

	}

	if($('cob_tipo_anuidade')){

		Event.observe(
			$('cob_tipo_anuidade'),
			'click',
			function(){
				cobName_anuidade();
			},
			false
		);

		Event.observe(
			$('cob_ano'),
			'change',
			function(){
				cobName_anuidade();
			},
			false
		);
		
	}


	if($('form_cob_add')){

 		//Radio Anuidade
 		checkAnuidade();
 		Event.observe (
			$('cob_tipo_anuidade'),
			'click',
			function () {
				checkAnuidade();
			},
			false
		);

		//RADIO Outros
		Event.observe (
			$('cob_tipo_outros'),
			'click',
			function () {
				checkOutros();
			},
			false
		);

		//RADIO OUTROS
		Event.observe (
			$('nome'),
			'change',
			function () {
 				if($('cob_tipo_outros').checked==true){
 					VerificaNomeCob();
 				}

			},
			false
		);

	}


	//Captcha
	if($('captcha')){
		novo_captcha();
		Event.observe($('troca_img'), 'click', function(){novo_captcha()}, false);

	}

	//Observa Campo URL
 	if($('url')){
		Event.observe($('url'),
		'change',
		function(){
			ExibiLink('url')
		},
		false
	);}


        //Observa Campo Link Curriculo - Form de inscrição
 	if($('socio_curriculo')){
            //console.log('qqq');
            Event.observe($('socio_curriculo'), 'change', function(){ ExibiLink('socio_curriculo') });
	}


	//Relatorios - Sócios
	if($('form_relatorios')){
		DesabilitaCampos('rela_tipo');
		Event.observe($('form_relatorios'), 'click', function(){DesabilitaCampos('rela_tipo')}, false);
	}


	//Boletim
	if($('form_boletim')){
		DesabilitaCampos('dest');
		Event.observe($('form_boletim'), 'click', function(){DesabilitaCampos('dest')}, false);
		
		//Dest: Eleitores
		destEleitores();
        
        if ($('field_dest')){
            Event.observe($('field_dest'), 'click', function(){destEleitores()}, false);
        }

		
	}

    //Selecionar categorias - Formulário de cat. de documentos
    if ($('cat_all')){
        select_all_label('cat_all', 'perm_cat');
    }



	if($('label_select_all')){

		var objLabel 	= "label_select_all";
		var classe 		= "check_perm";


		select_all_label(objLabel, classe);

		Event.observe($(objLabel),
		'click',
		function(){
			select_all_checkbox(objLabel, classe);
			select_all_label(objLabel, classe)
		},
		false
		);


	}


	//Busca Sócio p/ inserir dados
	if($('ajax_busca_socio') || $('ajax_busca_eleitor')){

		//Esconde "Lista de Resultados"
		if($('resultado_lista')){
			Element.hide($('resultado_lista'));
			Element.hide($('resultado_lista_loading'));
		}
		if($('resultado_lista_elei')){
			Element.hide($('resultado_lista_elei'));
			Element.hide($('resultado_lista_loading_elei'));			
		}

		//Esconde "CARREGANDO"
		//var spans = document.getElementsByClassName('resul_carregando');
		var spans = $$('.resul_carregando','.label_curriculo','.txt_curriculo');
	    var spansArray = $A(spans);
		    spansArray.each(function(span){
		    	Element.hide($(span));
		    });

		//Oberserva botoes de busca de socio
		var botoes = document.getElementsByClassName('btn_busca_socio');
	    var botoesArray = $A(botoes);
		    botoesArray.each(function(botao){
		        Event.observe(botao, 'click', function(event){ buscaSocio(Event.element(event)); hideCurriculos(); });
		    });
		    
		    
		//observa os campos de busca, p/ qdo focar(focus) esconder os curriculos
		var buscas = document.getElementsByClassName('campo_busca');
	    var buscasArray = $A(buscas);
		    buscasArray.each(function(busca){
		        Event.observe(busca, 'focus', function(event){ hideCurriculos(); });
		        Event.observe(busca, 'change', function(event){ 
		        												var cargo = Event.element(event).id.replace(/str_/g,"");
		        												//se tiver, zera valores
		        												if($(cargo)){
			        												if($(cargo).value){
			        													$(cargo).value = '';
			        													//$('str_'+cargo).value = '';
			        												}
		        												}
		        												//se tiver, some
		        												if($('curriculo_label_'+cargo)){
		        													$('curriculo_label_'+cargo).update("");
		        												}		        												
		        												//se tiver, some
		        												if($('noCurriculo'+cargo)){
		        													$('noCurriculo'+cargo).update("");
		        												}
		        												//se tiver, some
		        												if($('curriculo_txt_'+cargo)){
		        													$('curriculo_txt_'+cargo).update("");
		        												}
		        											});
		    });
		    
		    
		//Mini-Curriculos
	    $A($$('.campo_id')).each(function(cargo){
	    	if(cargo.value){
	    		var n = cargo.id.replace(/cargo_/g,"");
	    		addChapa($('par_id'+n).value, cargo.id, cargo.value,1);
	    	}
		    });
		
		    


	}// if $('resultado_busca_socio')
	

	
	
	//VALIDA CEDULA DE PAPEL
	if($('valida_cedula_papel')){
		//esconde
		Element.hide($('valida_cedula_papel'));
		$('resp_valida').innerHTML = '';
		
		//observer campo: codigo
		Event.observe($('vc_codigo'), 'keyup', function(event){ 
																$('vc_codigo').value = $F('vc_codigo').toUpperCase();
																if($F('vc_codigo').length==6){
																	$('vc_confirma').focus();
																}
															  });
		Event.observe($('vc_codigo'), 'keypress', function(event){ $('resp_valida').innerHTML = ''; });
		
		
		//observer campo: confirma
		Event.observe($('vc_confirma'), 'keyup', function(event){ 
																$('vc_confirma').value = $F('vc_confirma').toUpperCase();
																if($F('vc_confirma').length==6){
																	$('vc_submit').focus();
																}
															  });

		//observer botar: Validar
		Event.observe($('vc_submit'), 'click', function(event){ 
																if($F('vc_codigo')=="" || $F('vc_codigo')==null){
																	alert('Campo "Código da Cédula" em Branco!');
																	$('vc_codigo').focus();
																}else if($F('vc_codigo').length!=6){
																	alert('O campo "Código da Cédula" deve possuir 6 caracteres!');
																	$('vc_codigo').focus();
																}else if($F('vc_codigo')!=$F('vc_confirma')){
																	alert('Campos "Código da Cédula" e "Confirmação" não são iguais!');
																}else{
																	validaCedulaPalpel();
																}
															  });
	}//valida






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

}//inicial


    //retira o valor inicial do campo se for igual a 'name'
    function retiraValor(obj, name){

        if (obj.value == name){
            obj.value = '';
        }

        obj.style.color = "black";
		
    }//fim function


    

    //volta o valor inical do campo se o valor for vazio ''
    function repoemValor(obj, name){
        
		if (obj.value == ''){
            obj.value = name;

                obj.style.color = "#808080";
        }//fim if
		
    }//fim function



    //Exibe ou Inibe o campo para incluir Outras Titulações
    function titulacao(load){

        //obtém o último option
        var lastIndex = $('pro_titulacao').options.length-1;

        //se foi escolhido o ultimo option (Outras titulações)
        if ( $('pro_titulacao').selectedIndex == lastIndex){
            (load==true)?$('inputTitAlt').clear():null;
            $('tit_alt').show();
        }else{
            $('tit_alt').hide();
        }

    }//fim function


    //Exibe ou Inibe o campo para incluir Outras Justificativas de situação
    function justSit(){

        //obtém o último option
        var lastIndex = $('just_sit').options.length-1;

        //se foi escolhido o ultimo option (Outras titulações)
        if ( $('just_sit').selectedIndex == lastIndex){
            //(load==true)?$('inputTitAlt').clear():null;
            $('just_sit_alt').show();
        }else{
            $('just_sit_alt').hide();
        }

    }//fim function


	function mc(socio_id, tipo){
		
		//TIPO = 1(CHAPA) | 2 (CONSELHEIRO)
		var tipo = (tipo==1)? 'Chapa' : ((tipo==2)?'Cons':'BUG') ;
		
		//Esconde
		if($('showMcChapa')){
			if($('showMcChapa').visible()){
				Element.hide($('showMcChapa'));
			}
		}
		if($('showMcCons')){
			if($('showMcCons').visible()){
				Element.hide($('showMcCons'));
			}
		}
		
		//AJAX
		var url = '../inc/ajax.php';
		var pars = 'op=socio_mc&socio_id='+socio_id;
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {
				$('showMc'+tipo).innerHTML = '<img src="../img/wait_small.gif" border="0" /> Carregando...';
				Element.show($('showMc'+tipo));
			},
			onComplete: function(originalRequest) {
				//alert("RESP: ["+originalRequest.responseText+"]");
				$('showMc'+tipo).innerHTML = originalRequest.responseText;
				Event.observe($('result_close'), 'click', function(event){ 
																			Element.hide($('showMc'+tipo));
																			$('showMc'+tipo).innerHTML = '';
				});
				Element.show($('showMc'+tipo));
			}//oncomplete
		});

	}//mc
	
	
	

	function cobName_anuidade(){
		$('nome').value = $('cob_anuidade').value+' '+$('cob_ano').value;
		$('nome').readOnly = true;
	}


	function validaCedulaPalpel(){
		
		var url = '../inc/ajax.php';
		var pars = 'op=valida_cedula&ele_id='+$F('ele_id')+'&codigo='+$F('vc_codigo');
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {
				Element.hide($('form_valida'));
				$('resp_valida').innerHTML = '<div id="msg_valida" class="alerta"><img src="../img/wait_small.gif" border="0" /> Aguarde...</div>';
				Element.show($('resp_valida'));
			},
			onComplete: function(originalRequest) {

				//alert("RESP: ["+originalRequest.responseText+"]");
				
				Element.show($('form_valida'));
				
				switch (originalRequest.responseText) {
					//Erro: Hash inexistente
					case "-1":
						$('resp_valida').innerHTML = "<div id='msg_valida' class='erro'>Código da Cédula Não Encontrado!<br />Código: "+$F('vc_codigo')+"</div><br />";
					break
					//Erro: Já Validada
					case "0":
						$('resp_valida').innerHTML = "<div id='msg_valida' class='erro'>Cédula Já Validada!<br />Código: "+$F('vc_codigo')+"</div><br />";
					break
					//Sucesso: Validada
					case "1":
						$('resp_valida').innerHTML = "<div id='msg_valida' class='sucesso'>Cédula Validada com Sucesso!<br />Código: "+$F('vc_codigo')+"</div><br />";
					break
				}				
				
				$('vc_codigo').value = '';
				$('vc_confirma').value = '';;
				$('vc_codigo').focus();
				
				

			}//oncomplete
		});

	}// validaCedulaPalpel
	

	function formValidaCedulaPalpel(close){
		if(close){
			Element.hide($('valida_cedula_papel'));
		}else{
			$('resp_valida').innerHTML = '';
			Element.toggle($('valida_cedula_papel'));
			$('vc_codigo').focus();
		}
	}

	function destEleitores(){

       if($('dest_eleitores').checked || $('dest_socio').checked || $('dest_todosNL').checked ){

                //input ativo
                $('dest_ativos').disabled = true;
                $('dest_ativos').checked = false;
                $('li_dest_ativos').hide();

                //input inativo
                $('dest_inativos').disabled = true;
                $('dest_inativos').checked = false;
                $('li_dest_inativos').hide();

            }else if(   $('dest_categoria').checked ||
                        $('dest_regional').checked  ||
                        $('dest_todos').checked  ||
                        $('dest_todosSN').checked  ){

                //input ativo
                $('dest_ativos').disabled = false;
                $('li_dest_ativos').show();

                //input inativo
                $('dest_inativos').disabled = false;
                $('li_dest_inativos').show();

                if ( $('edit_boletim').value != ''){
                    $('dest_ativos').checked = true;
                    $('dest_inativos').checked = true;
                }
            }
        
	}

	function hideCurriculos(){
		
		//pega todos elementos com a classe
		var curriculosArray = $A($$('.txt_curriculo'));
			//loop
			curriculosArray.each(function(curriculo){
				//esconde
				Element.hide($(curriculo));
			}//function
			)//each
			;
	}//function


	function verificaChapa(socio_id){


		var erro = 0;
		var campos = document.getElementsByClassName('campo_id');
	    var camposArray = $A(campos);
		    camposArray.each(function(campo){
		    	//alert('socio_id: '+socio_id+'\ncampo: '+$(campo).id+'\nvalor: '+$(campo).value);
		    	if($(campo).value == socio_id){
		    		erro = 1;
		    	}//if
		    });

		    if(erro==1){
		    	return true;
		    }else{
		    	return false;
		    }

	}//function




	function addChapa(ele_id, cargo_id, socio_id, autoAdd){
		
		//alert("addChapa()\nele_id: "+ele_id+"\ncargo_id: "+cargo_id+"\nsocio_id: "+socio_id+"\nautoAdd:"+autoAdd);
		


		//AJAX add no BD
		var url = '../inc/ajax.php';
		var pars = 'op=add_ele&tipo=chapa&ele_id='+ele_id+'&socio_id='+socio_id+'&autoAdd='+autoAdd;
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {
				Element.hide($('resultado_lista'));
				Element.show($('resultado_lista_loading'));
			},
			onComplete: function(originalRequest) {
				Element.hide($('resultado_lista_loading'));
				Element.show($('resultado_lista'));
				//alert("RESP: ["+originalRequest.responseText+"]");
				//alert("VERIFICACAO: ["+verificaChapa(socio_id)+"]");
				//Caso retorne false, exibe erro, caso contrario atualiza lista de candidatos
				if(originalRequest.responseText=="0" && !autoAdd){
					alert('Este sócio já esta participando desta eleição!');
					var erro = 1;
				}
				else{
					if(verificaChapa(socio_id) && !autoAdd){
						alert('Este sócio já esta participando desta chapa!');
						var erro = 1;
					}else{
						if(!autoAdd){
							$(cargo_id).value = $('chapa_id_'+socio_id).value;
							$('str_'+cargo_id).value  = $('chapa_nome_'+socio_id).value;
							
						}
						if($('resultado_lista').visible()){
							Element.hide($('resultado_lista'));
						}
						if($('resultado_lista_loading').visible()){
							Element.hide($('resultado_lista_loading'));
						}
						
						
						if(originalRequest.responseText==1){
							//alert('sem curr');
							//sem curiculo
							$('noCurriculo'+cargo_id).update("<img src='../img/nao.gif' border='0' /> Sem Mini-Currículo");
							//exibe noCurriculo
							Element.show($('noCurriculo'+cargo_id));	
						}else{
							//alert('com curr');
							//com curriculo
							$('curriculo_label_'+cargo_id).update("<img src='../img/sim.gif' border='0' /> Exibir/Ocultar Mini-Currículo");
							//joga curriculo na div
							$('curriculo_txt_'+cargo_id).update(originalRequest.responseText);
							//exibe link p/ curriculo
							Element.show($('curriculo_label_'+cargo_id));	
						}
						
											
					}
				}

				//zera valores e focus no campo
				if(erro){
					$(cargo_id).value = '';
					$('str_'+cargo_id).value  = '';
					$('str_'+cargo_id).focus();
				}

			}//oncomplete
		});

	}// addNaChapa


	function addConselheiro(ele_id, cargo_str, socio_id, tipo){
		
		var tipo = tipo;
		if(!tipo){
			tipo = 'cons';
		}else{
			tipo = 'cand';
		}
		

		//AJAX add no BD
		var url = '../inc/ajax.php';
		var pars = 'op=add_ele&tipo='+tipo+'&ele_id='+ele_id+'&socio_id='+socio_id;
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {
				Element.hide($('resultado_lista'));
				Element.show($('resultado_lista_loading'));
			},
			onComplete: function(originalRequest) {
				Element.hide($('resultado_lista_loading'));
				Element.show($('resultado_lista'));
				
				//alert("RESP: ["+originalRequest.responseText+"]");
				
				//Caso retorne false, exibe erro, caso contrario atualiza lista de candidatos
				if(!originalRequest.responseText){
					alert('Este sócio já é um candidato nesta eleição!');
				}else{
					updateConselheiros(originalRequest.responseText);
					Element.hide($('resultado_lista'));
					$(cargo_str).value = '';
					$(cargo_str).focus();
				}

			},//oncomplete
			onFailure: function() {
				Element.hide($('resultado_lista_loading'));
				Element.hide($('resultado_lista'));
				alert('ajax error');
			}			
		});

	}// addConselheiro
	

	function updateConselheiros(cons_id, ele_id){
		
		if(!ele_id){
			var ele_id = 0;
		}
		

		//Pega o nome da classe da ultima linha da tabela de candidatos a conselheiro
		var linhas = document.getElementById("tab_cons").getElementsByTagName("tr");
		var nLinhas = linhas.length;
		var ultimaLinha = linhas[(nLinhas-1)]
		if(ultimaLinha.className=="rowcolor_0"){
			var nextStyle = "1";
		}else{
			var nextStyle = "0";
		}

		//Remove linha "sem registro"
		if($('cons_sem_reg')){
			Element.remove($('cons_sem_reg'));
		}



		//AJAX updater LISTA
		var url = '../inc/ajax.php';
		var pars = 'op=lista_cons&ele_id='+ele_id+'&cons_id='+cons_id+'&style='+nextStyle;
		var myAjax = new Ajax.Updater('tab_cons', url, {
		  	parameters: pars,
			insertion: Insertion.Bottom
		});

	}//function

	

	
	function addEleitor(ele_id, cargo_str, socio_id){

		//AJAX add no BD
		var url = '../inc/ajax.php';
		var pars = 'op=add_eleitor&ele_id='+ele_id+'&socio_id='+socio_id;
		var myAjax = new Ajax.Request( url, {
			method: 'post',
			parameters: pars,
			onLoading: function() {
				Element.hide($('resultado_lista_elei'));
				Element.show($('resultado_lista_loading_elei'));
			},
			onComplete: function(originalRequest) {
				Element.hide($('resultado_lista_loading_elei'));
				Element.show($('resultado_lista_elei'));
				
				//alert("RESP: ["+originalRequest.responseText+"]");
				
				//Caso retorne false, exibe erro, caso contrario atualiza lista de candidatos
				if(originalRequest.responseText<0){
					alert('Este sócio já é um eleitor nesta eleição!');
				}else{
					updateEleitores(socio_id, ele_id);
					Element.hide($('resultado_lista_elei'));
					$(cargo_str).value = '';
					$(cargo_str).focus();
				}

			},//oncomplete
			onFailure: function() {
				Element.hide($('resultado_lista_loading_elei'));
				Element.hide($('resultado_lista_elei'));
				alert('ajax error');
			}			
		});

	}// addConselheiro
	

	function updateEleitores(socio_id, ele_id){
		
		if(!ele_id){
			var ele_id = 0;
		}
		
		//Pega o nome da classe da ultima linha da tabela de candidatos a conselheiro
		var linhas = document.getElementById("tab_elei").getElementsByTagName("tr");
		var nLinhas = linhas.length;
		var ultimaLinha = linhas[(nLinhas-1)]
		if(ultimaLinha.className=="rowcolor_0"){
			var nextStyle = "1";
		}else{
			var nextStyle = "0";
		}

		//Remove linha "sem registro"
		if($('cons_sem_reg')){
			Element.remove($('cons_sem_reg'));
		}
		
		//alert("socio_id: "+socio_id+"\n"+"ELE_ID: "+ele_id);

		//AJAX updater LISTA
		var url = '../inc/ajax.php';
		var pars = 'op=lista_elei&ele_id='+ele_id+'&socio_id='+socio_id+'&style='+nextStyle;
		var myAjax = new Ajax.Updater('tab_elei', url, {
		  	parameters: pars,
			insertion: Insertion.Bottom
		});

	}//function
	


	

	

	function removeCandidato(cons_id, nome){
		
	
		if (confirm('Você realmente deseja apagar esse Candidato?\n\nCanditado: '+ nome)){

			//AJAX add no BD
			var url = '../inc/ajax.php';
			var pars = 'op=del_candidato&cons_id='+cons_id;
			var myAjax = new Ajax.Request( url, {
				method: 'post',
				parameters: pars,
				onLoading: function() {
					/*
					Element.hide($('resultado_lista'));
					Element.show($('resultado_lista_loading'));
					*/
				},
				onComplete: function(originalRequest) {
					/*
					Element.hide($('resultado_lista_loading'));
					Element.show($('resultado_lista'));
					*/
					
					//alert("RESP: ["+originalRequest.responseText+"]");
					
					//Caso retorne false, exibe erro, caso contrario atualiza lista de candidatos
					if(originalRequest.responseText==1){
						//alert('Cnadidato removido com sucesso!');
						Element.remove($('linha_candidato_'+cons_id));
					}else{
						alert('Não foi possível remover esse Candidato.\n\nPor favor, tente novamente. Caso o erro persistir, entre em contato com o desenvolvedor do sistema.');
					}
					
				},//oncomplete
				onFailure: function() {
					/*
					Element.hide($('resultado_lista_loading'));
					Element.hide($('resultado_lista'));
					*/
					alert('ajax error');
				}			
			});
		
		}

	}// addConselheiro	
	
	function removeEleitor(ele_id, socio_id, nome){
		
	
		if (confirm('Você realmente deseja remover esse Eleitor?\n\nEleitor: '+ nome)){

			//AJAX add no BD
			var url = '../inc/ajax.php';
			var pars = 'op=del_eleitor&ele_id='+ele_id+'&socio_id='+socio_id;
			var myAjax = new Ajax.Request( url, {
				method: 'post',
				parameters: pars,
				onLoading: function() {
					/*
					Element.hide($('resultado_lista'));
					Element.show($('resultado_lista_loading'));
					*/
				},
				onComplete: function(originalRequest) {
					/*
					Element.hide($('resultado_lista_loading'));
					Element.show($('resultado_lista'));
					*/
					
					//alert("RESP: ["+originalRequest.responseText+"]");
					
					//Caso retorne false, exibe erro, caso contrario atualiza lista de candidatos
					if(originalRequest.responseText==1){
						//alert('Cnadidato removido com sucesso!');
						Element.remove($('linha_eleitor_'+socio_id));
					}else if(originalRequest.responseText<0){
						alert('Não foi possível remover esse Eleitor, pois ele já votou!');
					}else{
						alert('Não foi possível remover esse Eleitor.\n\nPor favor, tente novamente. Caso o erro persistir, entre em contato com o desenvolvedor do sistema.');
					}
					
				},//oncomplete
				onFailure: function() {
					/*
					Element.hide($('resultado_lista_loading'));
					Element.hide($('resultado_lista'));
					*/
					alert('ajax error');
				}			
			});
		
		}

	}// addConselheiro
	
	function addAll(ele_id){
		window.open('bot/eleicoes_cedulas.php?acao=addAll&ele_id='+ele_id, '_self');
	}
	function removeAll(ele_id){
		window.open('bot/eleicoes_cedulas.php?acao=removeAll&ele_id='+ele_id, '_self');
	}
	function notificar(ele_id){
		window.open('bot/eleicoes_cedulas.php?acao=notificar&ele_id='+ele_id, '_self');
	}

	

	function buscaSocio(obj_btn){


			//Procura o LABEL
			var botao = $(obj_btn);
			while (botao.nodeName!="LABEL"){
				//console.log(botao.nodeName);
				botao = botao.previousSibling;
			}

			//LABEL
			//alert("LABEL ID: " + botao.id);


			//Entra no Label
			var aux = botao.firstChild;
			//alert("AKI: " + aux);


			//setar campos a serem "buscados" pelo while como falsos
			var campo_busca = false;
			var campo_id = false;
			var par_id = false;
			var carregando = false;

			//loop
			while (!campo_busca || !campo_id || !par_id || !carregando){

				if(aux.nodeName=="INPUT"){
					if(Element.hasClassName(aux, 'campo_busca')){
						var campo_busca = aux;
						//alert('Campo Busca: '+aux);
					}
					if(Element.hasClassName(aux, 'campo_id')){
						var campo_id = aux;
						//alert('campo_id: '+aux);
					}
					if(Element.hasClassName(aux, 'par_id')){
						var par_id = aux;
						//alert('par_id: '+aux);
					}
				}

				if(aux.nodeName=="SPAN"){
					if(Element.hasClassName(aux, 'resul_carregando')){
						var carregando = aux;
						//alert('carregando: '+aux);
					}
				}

				//Se alguma das variaveis for falso, vai pro proximo
				if(!campo_busca || !campo_id || !par_id || !carregando){
					aux = aux.nextSibling;
				}

			}//while
			
			
			//Define campo de resultado
			if(carregando.id=="resultado_carregando_elei"){
				var resultado = "resultado_lista_elei";
			}else{
				var resultado = "resultado_lista";
			}


			//DEBUG
			//alert('OK!\n\nCampo Busca: '+campo_busca.id+' ('+ campo_busca.value +')\nCampo ID: '+campo_id.id+' ('+ campo_id.value +')\nPar ID: '+par_id.id+' ('+ par_id.value +')\nCarregando: '+ carregando.id + '\nResultado: '+ resultado);


			//Remove o valor do campo ID, caso o campo já tenho um valor anterior
			if(campo_id.value){
				$(campo_id).value = '';
			}


			//Verificação de campo em branco
			if(!campo_busca.value){
				alert('Ops..\n\nO campo está em branco!');
				$(campo_busca.id).focus();
				return false;
			}




			//Pego o Cargo que será utilizado na resposta da busca e tambem para gerar o HTML
			var cargo = campo_busca.title;
			//alert(cargo);
			
			
			
				var url = '../inc/ajax.php';
				var pars = 'op=busca_socio&buscar='+campo_busca.value+'&id_busca='+campo_busca.id+'&id_cargo='+campo_id.id+'&par='+par_id.value;
				var myAjax = new Ajax.Updater(
				resultado,
				url,
				{
				method: 'post',
				parameters: pars,
				onLoading: function() {
					Element.hide($(campo_busca));
					Element.show($(carregando));
				},
				onComplete: function(originalRequest) {
					Element.hide($(carregando));
					Element.show($(campo_busca));
					Element.show($(resultado));
					//observer do fechar
					if($('result_close')){
						Event.observe($('result_close'), 'click', function(event){ Element.hide($(resultado));});
					}

				},
				onFailure: function() {
					Element.hide($(carregando));
					Element.hide($(resultado));
					Element.show($(campo_busca));
					alert('ajax error');
			}
			});






	}//function buscaSocio



	function checkAnuidade(){
		if($('cob_tipo_anuidade').checked==true){
			Element.hide('label_valor');
			$('submit').disabled = false;
			$('nome').readOnly = true;
			$('cob_ano').disabled = false;
		}else{
			$('cob_ano').disabled = true;
		}
	}

	function checkOutros(){
		VerificaNomeCob();
		$('nome').readOnly = false;
		Element.show('label_valor');
	}



	function select_all_checkbox(objLabel, classe){


		var campos = document.getElementsByClassName(classe);
		if(campos.length>0){
			for(i=0; i<=(campos.length-1); i++){

				//alert(campos[i].value);
				//alert($(objLabel).innerHTML);

				if($(objLabel).innerHTML=="Selecionar Todos"){
					campos[i].checked = true;
				}else{
					campos[i].checked = false;
				}

			}//for
		}//if

	}


	function select_all_label(objLabel, classe){

		var selecionado = 0;
		var deselecionado = 0;


		var campos = document.getElementsByClassName(classe);
		if(campos.length>0){
			for(i=0; i<=(campos.length-1); i++){

				if(campos[i].checked == true){
					selecionado = selecionado+1;
				}else{
					deselecionado = deselecionado+1;
				}

			}//for
		}//if

		if(selecionado==0){
			//alert("Selecionar Todos");
			$(objLabel).innerHTML = "Selecionar Todos";
		}else{
			//alert("Deselecionar Todos");
			$(objLabel).innerHTML = "Deselecionar Todos";
		}

		//alert($(objLabel).innerHTML);

	}




function DesabilitaCampos(classe){

		var elementos = $$('.'+classe);
		if(elementos.length>0){
			for(i=0; i<=(elementos.length-1); i++){

				//Se existir o select
				if($(elementos[i].value+'_id')){

					if($(elementos[i].id).checked==true){
						$(elementos[i].value+'_id').disabled = false;
					}else{
						$(elementos[i].value+'_id').disabled = true;
					}

				}//if - select

			}//for
		}//if

}



	function ExibiLink(campo) {
		if($(campo).value==""){
			$('linkPreview').innerHTML='';
		}else{

			var PegaURL = $(campo).value.substring(0,7).toLowerCase();
			if(PegaURL!="http://"){
				$(campo).value = 'http://'+$(campo).value;
			}
				$('linkPreview').innerHTML='<a href="'+$(campo).value+'" target="_blank">Click aqui para testar o link (abre nova janela).<br /><br /></a>';
		}
	}




function VerificaNomeCob(){

	//limpa campo, caso seja igaul ao hidden
	if($('nome').value==$('cob_anuidade').value){
		$('nome').value = '';
	}

	var str = $('nome').value.toUpperCase();

	if(str.split("ANUIDADE").length > 1){
		alert('ATENÇÃO\n\nPara adicionar um cobrança relacionada a "ANUIDADE", selecione a opção "Anuidade" acima.');
		$('submit').disabled = true;
	}else{
		$('submit').disabled = false;
	}

}




 function novo_captcha(){
    var myAjax = new Ajax.Updater('captcha', 'inc/captcha/captcha.php');
  }

function ObsCobranca(obj){

	//alert('ObsCobranca ID: '+obj.id);
	//alert('ObsCobranca VALOR: '+obj.value);

	Event.observe($(obj.id), 'click', function(){addCobranca(obj.value)}, false);

	if($('para_'+obj.value).checked==true && $(obj.value+'_id')){
		$(obj.value+'_id').disabled = false;
	}

	//alert('/ObsCobranca: '+obj.value);
}


function addCobranca(campo){

	//alert('addCobranca');

	if(campo=='socio' && $('para_socio').checked==true){
		$('socio_id').disabled = false;
	}else{
		$('socio_id').disabled = true;
	}

	if(campo=='categoria' && $('para_categoria').checked==true){
		$('categoria_id').disabled = false;
	}else{
		$('categoria_id').disabled = true;
	}

        if($('regional_id')){
            if(campo=='regional' && $('para_regional').checked==true){
                    $('regional_id').disabled = false;
            }else{
                    $('regional_id').disabled = true;
            }
        }//fim if

	//alert('/addCobranca');
}


function AreaInteresse(obj, qde){

	//alert(obj.id);
	//alert(obj.value);


	//zera
	var count = 0;

	for(j=1; j<=qde; j++){

		if($('area'+j).checked==true){
			//soma no contador
			count++;
			//alert(count)
			if(count>3){
				$('area'+obj.value).checked = false;
				alert('Você pode selecionar apenas 3 áreas de interesse!');
			}//else
		}//if

	}//for
}//funcao



// Função que permite apenas teclas numéricas e
// todos os caracteres que estiverem na lista
// de argumentos.
// Deve ser chamada no evento onKeyPress desta forma
// onKeyPress ="return (soNums(event,'(/){,}.'));"
function soNums(e,args)
{
    var valid_chars    = new Array();
    if (document.all){var evt=event.keyCode;}
    else{var evt = e.charCode;}
    var chr= String.fromCharCode(evt);
    if (evt <20 || (evt >47 && evt<58) || (args.indexOf(chr)>-1 ) ){return true;}
    return false;
}


// url_encode version 1.0
function url_encode(str) {
    var hex_chars = "0123456789ABCDEF";
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var n, strCode, hex1, hex2, strEncode = "";

    for(n = 0; n < str.length; n++) {
        if (noEncode.test(str.charAt(n))) {
            strEncode += str.charAt(n);
        } else {
            strCode = str.charCodeAt(n);
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));
            hex2 = hex_chars.charAt(strCode % 16);
            strEncode += "%" + (hex1 + hex2);
        }
    }
    return strEncode;
}

// url_decode version 1.0
function url_decode(str) {
    var n, strCode, strDecode = "";

    for (n = 0; n < str.length; n++) {
        if (str.charAt(n) == "%") {
            strCode = str.charAt(n + 1) + str.charAt(n + 2);
            strDecode += String.fromCharCode(parseInt(strCode, 16));
            n += 2;
        } else {
            strDecode += str.charAt(n);
        }
    }
    return strDecode;
}


//Desabilita o ENTER, usar: onkeypress="return noenter();"
function noenter() {
	return !(window.event && (window.event.keyCode == 13));
}

function rejeitaTecla(oEvent){    

	//var cod_tecla=116; //tecla que quer bloquear. 116 é o código da tecla F5
    var cod_tecla=13; //tecla que quer bloquear. 13 é o código da tecla ENTER

    //filtrando o evento
    var oEvent = oEvent ? oEvent : window.event;
    var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which;
    
    if(oEvent.type=="keydown" && navigator.appName.indexOf('Internet Explorer')<0 ){
        //se for keydown e não for o IE, vazarei pois o keypress já foi executado
        return false;
    }
    
    if (typeof(oEvent.keyCode)=='number' && oEvent.keyCode == cod_tecla){
        if (typeof(oEvent.preventDefault)=='function'){
            oEvent.preventDefault();
        } else {
            oEvent.returnValue = false;
            oEvent.keyCode = 0;
        }
    }
    return false;
}

//Se o usuário escolheu um Endereço alternativo para correspondencia, exibe o formulário
function checaEnderecoAlternativo(campo){

    if (campo.checked == true && campo.value == '3'){
        $('field_corresp_endereco').show();
    }else{
        $('field_corresp_endereco').hide();
    }//fim else

}//fim function checaEnderecoAlternativo



