//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
	}

	//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
		);

                //Radio - Semestres
                Event.observe( $('Semestre1'), 'click', function(){cobName_anuidade();});
                Event.observe( $('Semestre2'), 'click', function(){cobName_anuidade();});

	}


	//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
	);



	}

	//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();
		Event.observe($('field_dest'), 'click', function(){destEleitores()}, false);
		
	}





	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')){

		//Esconde "Lista de Resultados"
		Element.hide($('resultado_lista'));
		Element.hide($('resultado_lista_loading'));

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

		//Oberserva botoes de busca de socio
		//var botoes = document.getElementsByClassName('btn_busca_socio');
	    //var botoesArray = $A(botoes);
	    $$('.btn_busca_socio').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);
		    $$('.campo_busca').each(function(busca){
		    	
		    	busca.observe('keypress',function(event){
		    		if(event.keyCode=='13'){
		    			
		    			buscaSocio(Event.element(event).up().next());hideCurriculos();
		    		}
		    		
		    	});
		    	
		        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)){
		        													$(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
	    $$('.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



	//Exibe as Categorias dos Conselheiros
	SetCategoriaStart();
	
	
	
	
	//Confirma Votos de Papel
	if($('form_votos_papel')){
		
	}


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

}//inicial

	function confirmVotosPapel(){

		if(confirm('=====================\nEsta operação é irreversível!\n=====================\n\nCertifique-se que os totais lançandos estejam corretos antes de clicar OK.\n\nApós clicar em OK somente será possível abrir a urna!')){
			return true;
		}else{
			return false;
		}
		
	}//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').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(){

            var semestre;

            if( $('Semestre1').checked == true ){
                semestre = ' (1º Semestre)';
            }else if( $('Semestre2').checked == true ){
                semestre = ' (2º Semestre)';
            }else{
                semestre = '';
            }

            $('nome').value = $('cob_anuidade').value+' '+$('cob_ano').value + semestre;
            $('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 confirmaPubResult(eleId){
		if(confirm('Você tem certeza que deseja publicar o resultado desta eleição?\n\nAção inrreverssível!')){
			window.location = '../eleicoes/bot/apuracao.php?publicar='+eleId;
		}		
	}
	
	function formValidaCedulaPapel(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){
		
		//AJAX add no BD
		var url = '../inc/ajax.php';
		var pars = 'op=add_ele&tipo=cons&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 a conselheiro 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){

		//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&cons_id='+cons_id+'&style='+nextStyle;
		var myAjax = new Ajax.Updater('tab_cons', url, {
		  	parameters: pars,
			insertion: Insertion.Bottom,
			onComplete: function() {
				SetCategoriaStart();
			},
			onFailure: function() {
				SetCategoriaStart();
			}			
		});
		



	}//function
	
	
	
	function SetCategoriaStart(){
		
		//Esconde TUDO
		$A($$('.consCatLoad','.consCatStar')).each(function(obj){
			Element.hide($(obj));
			}//function
		)//each
		;//fim
		
		htmlCategoria();
	}	

	
	function htmlCategoria(){
		
		//pega todos elementos com a classe e faz um loop
		$A($$('.consCat')).each(function(cons){
				
				//Seta CAT 1
				if($(cons).value==1){
					//[CAT1] Esconde estrela "apagada" e Exibe estrela "acesa"
					Element.hide($($(cons).id+'1_0'));
					Element.show($($(cons).id+'1_1'));
					
					//[CAT2] Exibe estrela "apagada" e Esconde estrela "acesa"
					Element.show($($(cons).id+'2_0'));
					Element.hide($($(cons).id+'2_1'));						
				}

				//Seta CAT 2
				if($(cons).value==2){
					//[CAT1] Exibe estrela "apagada" e Esconde estrela "acesa"
					Element.show($($(cons).id+'1_0'));
					Element.hide($($(cons).id+'1_1'));
					
					//[CAT2] Esconde estrela "apagada" e Exibe estrela "acesa"
					Element.hide($($(cons).id+'2_0'));
					Element.show($($(cons).id+'2_1'));
				}
				
			}//function
		)//each
		;//fim
		
	}


	function setCategoria(cons_id, cat_id){
		
		//alert('CONS ID: '+cons_id+'\nCAT ID'+cat_id);
		
		//ATUALIZA via AJAX

			//AJAX add no BD
			var url = '../inc/ajax.php';
			var pars = 'op=setCategoria&cons_id='+cons_id+'&cat_id='+cat_id;
			var myAjax = new Ajax.Request( url, {
				method: 'post',
				parameters: pars,
				onLoading: function() {
					//Esconde Estrelas
					$A($$('.consCatStar'+cons_id)).each(function(obj){Element.hide($(obj));});
					//Exibe Loading
					$A($$('.consCatLoad'+cons_id)).each(function(obj){Element.show($(obj));});
				},
				onComplete: function(originalRequest) {
					//DEBUG
					//alert("RESP: ["+originalRequest.responseText+"]");
					
					//Joga novo valor da Categoria p/ campo hidden
					if(originalRequest.responseText){
						$('cons'+cons_id+'_Cat').value = cat_id;
					}
					
					//Esconde Loading
					$A($$('.consCatLoad'+cons_id)).each(function(obj){Element.hide($(obj));});
					
					//Esconde TODOS Loading, caso alguns não tenha sido escondido
					$A($$('.consCatLoad')).each(function(obj){Element.hide($(obj));});
					
					
					//Gera HTML
					htmlCategoria();
					
				},
				onFailure: function() {
					alert('Ocorreu um erro na atualização da categoria!\n\nPor favor recarregue esta página e tente novamente,\ncaso o erro persistir notifique o desenvolvedor do sistema.');
				}			
			});
			
	}// setCategoria
	
	
	
	

	
	



	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


			//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);


			//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_lista',
				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_lista'));
					//observer do fechar
					if($('result_close')){
						Event.observe($('result_close'), 'click', function(event){Element.hide($('resultado_lista'));});
					}

				},
				onFailure: function() {
					Element.hide($(carregando));
					Element.hide($('resultado_lista'));
					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;
			$('Semestre1').disabled = false;
			$('Semestre2').disabled = false;
		}else{
			$('cob_ano').disabled = true;
                        $('Semestre1').disabled = true;
			$('Semestre2').disabled = true;

                        $('Semestre1').checked = false;
			$('Semestre2').checked = false;
		}
	}//fim function

	function checkOutros(){

            //Semestres
            $('Semestre1').checked = false;
            $('Semestre2').checked = false;
            $('Semestre1').disabled = true;
            $('Semestre2').disabled = true;

            $('cob_ano').disabled = true;

            VerificaNomeCob();
            $('nome').readOnly = false;
            Element.show('label_valor');

	}//fim function


	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 = document.getElementsByClassName(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).</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;
                
//                Event.observe($('categoria_id'), 'change', function(){console.log(  ); });
                Event.observe($('categoria_id'), 'change', function(){ setInstrucao2(); });

	}else{
		$('categoria_id').disabled = true;
	}

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

	//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;
}

function setInstrucao2(){

    var index = $('categoria_id').selectedIndex;
    var textSelect = $('categoria_id').options[index].text;

    var data = new Date();

    if( textSelect.indexOf('Sócio') != -1 ){

        var textSelectFormat = textSelect.replace('Sócio ', '');
        $('instrucao1').value = $('altInstrucao1').value + ' ' + textSelectFormat.toUpperCase() + ' ' + data.getFullYear();
    }
}