var txtOLD = "";
var txtNEW = "";
var data   = "";
var poup   = null;

var CaArray = Array();
var LoArray = Array();
var cargo   = Array("Analista de Mercado", "Inspetor", "Agente Executivo","Auxiliar de Serviços Gerais");
var lotacao = Array("Rio de Janeiro","São Paulo","Brasília");

$(document).ready(function(){
		//[LOAD]
			$("[class=aba_cargo]").hide();
			$("[id=aba_cargo]").css({color:"#aa8"});
		//[FIM]
		
		//[VALIDA LOGIN]
			$("[id=logar]").bind('click',logar);
		//[FIM]
		
		//[VALIDAR FORMS]
			  $("[id=form_]").bind('click',acForm);	
		//[FIM]
		
		//[VALIDAR SINDICALIZADO]
			//$("[id=buscar_sind]").bind('keypress',validar);
			/*$("[id=txtBuscar]").keydown(function(event){
				if(event.keyCode == 13){
					validar();					
				}
			});*/
			
			$('form#buscador').submit(function(event){
				if(event.keyCode == 13){
					validar();
					return false;
				}								   
			});
			
			//$("form#buscador").submit(function(){return false; });
		//[FIM]
		
		//[VALIDA BUSCA NOTICIA]
			$("[id=busca_noticia]").click(function(){
				var busca = $("[id=titulo_busca]").val();
				
				if(busca.length > 0){
					window.location = "buscaNoticia.php?filter="+busca;
				}else{
					alert("Campo pesquisa em branco!");
					$('[id=titulo_busca]').focus();
				}
			});
		//[FIM]
		
		//[LOGOUT USUARIO]
			$("[class=logout]").click(function(){
				c = confirm("Confirma operação?");
				if(c){
					$url = "./action/logout_usuario.php?redir="+this.id;
					isClose();
					window.location = $url;
				}
			});
		//[FIM]
		
		//[EDITAR AVISO]
			$("[class=editar_aviso]").toggle(
			function(){
				txtOLD = $("#textarea").text().replace(/^\s+|\s+$/g,'');
				$("#textarea div").remove();
	
				$("#textarea").html("<textarea id=\"txtNEW\" style=\"width:520px; height:50px\">"+txtOLD+"</textarea>");

			},function(){
				var id = this.id;
				txtNEW = $("[id=txtNEW]").val().replace(/^\s+|\s+$/g,'');
				$("#textarea textarea").remove();
				
				$("#textarea").html("<div>"+txtNEW+"</div>");
				
				
				if(txtNEW != txtOLD){
					$.post("./action/editar_aviso.php",{id:id, txt:txtNEW},function(){
						
					});
				}
			}
			);
		//[FIM]
		
		//[EDITAR PERFIL]
			$("[class=editar_perfil]").click(function(){
				var tipo   = splits(this.id,"_",0);
				var acForm = splits(this.id,"_",1);
				var show   = this.name;
				
				if(tipo == 1){
					url = "form_usuario.php?acForm="+acForm+"&show="+show;
				}else if(tipo == 0){
					url = "filiar.php?show="+show;
				}
				
				window.location = url;
			});
		//[FIM]
		
		//[DELETAR]
			$("[class=del]").click(function(){
				var id    = this.id;
				var table = this.name;
				
				if(confirm("Confirma a solicitação!")){
					$("[id="+id+"]").remove();
					
					$.post("./action/deletar_texto.php",{table:table, id:id},function(result){
						if(result){
							
						}
					});
				}
				
			});
		//[FIM]
		
		//[DIRECIONAR FORM]
			$("[class^=form]").click(function(pos){
				var id     = this.id;
				var acForm = splits(id, "_", 1);
				var pag    = splits(id, "_", 0);
				
				if(acForm == 'inserir'){
					$url = "./form_"+pag+".php?acForm="+acForm;
				}else{
					var show = splits(id, "_", 2);
					$url = "./form_"+pag+".php?acForm="+acForm+"&show="+show;
				}
				
				window.location = $url;			
			});
		//[FIM]
		
		//[POPUP]
			$("[class=popup]").click(function(){
				var aux = this.id;
				var tokenCvm  = splits(aux,"_",1);
				var page  = splits(aux,"_",0);
				
				var url   = page+".php?tokenCvm="+tokenCvm;
				
				isPop(url, page, "fullscreen=yes, menubar=0,resizable=1, scrollbars=1");
			});
		//[FIM]
		
		//[CHECK EMAIL]
			$(":checkbox").click(function(e){
				var value = $(this).val();
				var id    = this.id;
				var from  = splits(id,"_",1);
				
				if($("#"+id).is(":checked")){
					$("input:hidden").val(value);
					
					
					if(from !=0){
						$(":checkbox").removeAttr("checked");
						$(this).attr({"checked":"checked"});
						$("[id=from]").html(value);
					}else{
						$(":checkbox").attr({"checked":"checked"});
						
						html = "<a href=\"javascript:;\" onclick=\"filterEmail(event)\">"+value+"</a>";
						$("[id=from]").html(html);
					}
				}else{
					$("input:hidden").val("");
					$("[id=from]").html("&nbsp;");
					
					$(":checkbox").removeAttr("checked");
					
				}
			});
		//[FIM]
		//[MENU TAB PESPUQUITIVA]
			$("[class=tab_menu]").click(function(){
				var id = this.id;
				
				$("[class^=aba_]").hide();
				$("a").css({color:"#aa8"});
				$(this).css({color:"#000"});
				$("."+id).show();
			});
		//[FIM]
		
		//[MUDAR STATUS]
			$("[class=status]").toggle(
					function(e){
					  var id     = this.id;
					  var status = $(this).text();
					  var arrayStatus = Array("NOVO","APROVADO","DELETAR");
					  
					  
					  selec = "<select id="+id+" onChange=\"change(this)\">";
					  
						  for(i=0; i < arrayStatus.length; i++){
							st = arrayStatus[i]
							$select = st == status ? "selected=\"selected\"" : "";
							selec += "<option value="+st+" "+$select+">"+st+"</option>";
						  }
					
					  selec += "</select>";
					  
					  
					  $("[id=pop]").remove();
					  
					  $("body").append("<div id=\"pop\">"+selec+"</div>");
					  
					  if($.browser.mozilla){
					  	var left = e.pageX - 80;
						var top  = e.pageY;
					  }else if($.browser.msie){
					  	var left = e.clientX + 250;
						var top  = e.clientY; 	
					  }
					  
					  //alert();
					  $("[id=pop]").css({top  : ""+top+"", left : ""+left+""});
					  				  
					},
					function(){
					  $("div#pop").remove();
					}
			);
		//[FIM]
		
		//[ENVIAR EMAIL AO SINDICALIZADO]
			$("#send").click(function(){
				var titulo = $("#titulo").val();
				var msg    = $("#msg").val();
				var from   = $("#destino").val();
				var cargo  = "";
				var lotacao= "";
				
				$msg  = from.length < 1   ? "Selecione o destinatario!" : "";
				$msg += titulo.length < 1 ? "\nTitulo em branco!"      : "";
				$msg += msg.length < 1    ? "\nMessagem em branco!"  : "";
				
				if($("#email_0").is(":checked")){
					$msg += LoArray.length == 0 ? "\nVocê deve escolher pelo menos uma locação!" : "";
					$msg += CaArray.length == 0 ? "\nVocê deve escolher pelo menos um cargo!" : "";
				}
				
				if(!$msg){
					$("#resp").html("processando<blink>...</blink>");
					
					for(var $j=0; $j<CaArray.length; $j++){
						cargo += CaArray[$j]+"_";	
					}
					
					for(var $k=0; $k<LoArray.length; $k++){
						lotacao +=LoArray[$k]+"_";
					}
					
					$.post("./action/send_msg_sindcalizado.php",{titulo:titulo, from:from, msg:msg, cargo:cargo, lotacao:lotacao},function(result){
						if(result){
							$("#resp").html("Messagem enviada com sucesso!");
						}
					});
				}else{
					alert($msg);
				}
				
			});
		//[FIM]
function validar(){
var validarForm = true;
var msg = "";
  
	  $("[rev=true]").each(function(){
			if($(this).val().length < 1){
				validarForm = false;
				msg += $(this).attr("label")+" e obrigario!\n";
			}
	  });

  
  if(!validarForm){
	  	alert(msg);
		return false;
  }else{
	return true;
  }	
	
}

function logar(){
var validarForm = true;
var msg = "";
  
	  $("[rev=true]").each(function(){
			if($(this).val().length < 1 && $(this).attr('class') == 'szcamp'){
				validarForm = false;
				msg += $(this).attr("label")+" e obrigario!\n";
			}
	  });

  
  if(!validarForm){
	  	alert(msg);
  }else{
		$("form#form-logar").submit();
  }	
	
}

function acForm(){
var validarForm = true;
var msg = "";
  
  $("input[rev=true]").each(function(){
	  var objForm = $(this).get();	
	  
	  for(i in objForm){
		var obj = objForm[i];
		var id  = "#"+obj.id;
		var cl = $(this).attr("class");
		
		
		if(cl !='szcamp'){
			var tipo = splits(obj.id,"_",0);
			
			if(tipo == 'data'){
				//[VERIFICA SE É UMA DATA VALIDA]
								
				if(!obj.value.isDate()){
					msg += $(this).attr('label')+" não esta no formato valido!\n";
				}
			}else if(tipo == 'tel'){
				//[VERIFICA SE É UM TELEFONE VALIDO]
							
				if(!obj.value.isFone()){
					msg += $(this).attr('label')+" não esta no formato valido!\n";
				}
			}else if(tipo == 'email'){
				//[VERIFICA SE É UM EMAIL VALIDO]
				
				if(!obj.value.isEmail()){
					msg += $(this).attr('label')+" não esta no formato valido!\n";
				}
			}else{
				if(obj.value.isEmpty()){
					msg += $(this).attr("label")+" é obrigario!\n";
				}
			}
				
		}
		  
	  }
	  								
  });
  
  if(msg.length){
  	alert(msg);
  }else{
	$("form").submit();
  }
}

change = function(s){
	var id = s.id; 
	var newStatus = s.value;
	var oldStatus = $("#"+id).text();
	
	if((newStatus != oldStatus) && (newStatus != 'DELETAR')){
				
		$("#"+id).text(newStatus);
		$("[id=pop]").remove();
		
		$("[class=adesao_"+id+"]").html("load<blink>..</blink>");
		
		var data = isNowDate(); 
		$.post("./action/update_status_sindicalizado.php",{id:id, status:newStatus, data:data},function(){
			$("[class=adesao_"+id+"]").html(data);
		});
	}else if(newStatus == 'DELETAR'){
		c = confirm("Confirma operação!");
				
		if(c){
			$("[class=griapConteudo_"+id+"]").remove();
			
			$.post("./action/deletar_sindicalizado.php",{id:id},function(result){
				if(result){
					
				}
			});
		}
		
		$("[id=pop]").remove();
	}	
}

});

splits = function(string, sinbol, pos){
	$aux = string.split(sinbol);
	return $aux[pos];
}

String.prototype.isFone = function(){
	var ex = "^(\\d\\d)[-](\\d\\d\\d\\d)[-](\\d\\d\\d\\d)$";
	return this.match(ex) ? true : false;
}

String.prototype.isDate = function(){
	var ex = "^(\\d\\d)[-/](\\d\\d)[-/](\\d\\d\\d\\d)$";
	return this.match(ex) ? true : false;
}

String.prototype.isEmail = function(){
	var ex = /^[a-z0-9._-]+@([a-z0-9]+[a-z0-9_-]*)+(\.[a-z0-9]+)+$/;
	return ex.test(this);
}

String.prototype.isTrim = function(){
	return this.replace(/^\s+|\s+$/g,'');
}

String.prototype.isEmpty = function(){
	return this.split(" ").join("").length == 0;
}

hide = function(box){
	$(box).remove();
}

filterEmail = function(e){
	var func = null;
	
	var html = "";
	
		html =  "<div class=\"box\">";
					html +="<div class=\"close\"><a href=\"javascript:hide('.box')\" title=\"fechar\">[x]</a></div>";
					html += "<div id=\"body\">";
							html += "<div class=\"left\">";
								 html += "<i>Cargo:</i>"
								 html +="<ul>";
								 		for($i=0; $i<cargo.length; $i++){
											//AQUI ENTRA PESQUISA
											var chek  = "";
											
											if(buscaArray(cargo[$i], 1)){
												chek = 	'checked=\"checked\"';
												func = 2;
											}else{
												func = 1;
											}
											
											html += "<li><label>"+cargo[$i]+"</label> <input type=\"checkbox\" name=\"cargo_"+$i+"\" value='"+cargo[$i]+"'  onclick=\"mist('"+cargo[$i]+"', 1,"+func+")\"  "+chek+"/></li>";
										}
								 html +="<ul>";
							html += "</div>";
							html += "<div class=\"rigth\">";
								 html += "<i>Lota&ccedil;&atilde;o:</i>"
								 html +="<ul>";
								 		for($i=0; $i<lotacao.length; $i++){
											//AQUI ENTRA PESQUISA
											var chek  = "";
											
											if(buscaArray(lotacao[$i], 2)){
												chek = 	'checked=\"checked\"';
												func = 2;
											}else{
												func = 1;
											}
											
											html += "<li><label>"+lotacao[$i]+"</label> <input type=\"checkbox\" name=\"lotacao_"+$i+"\" value='"+lotacao[$i]+"'  onclick=\"mist('"+lotacao[$i]+"', 2,"+func+")\" "+chek+"/></li>";
										}
								 html +="<ul>";
							html += "</div>";
					html += "</div>";
		html += "</div>"
	
	$("div.box").remove();	
	$("body").append(html);
	
	if($.browser.mozilla){
		var left = e.pageX;
		var top  = e.pageY;
	}else if($.browser.msie){
		var left = e.clientX;
		var top  = e.clientY; 	
	}
	
	//var left = e.pageX;// - 10;
	//var top  = e.pageY;// - 8;
	
	$("div.box").css({top  : ""+top+"", left : ""+left+"",position:"absolute"});
	
}

function mist(str, cook, func){
	var st = new String();
	st = str;
	
	if(cook == 1){
		if(func == 1){
			CaArray.push(st);
		}else{
			CaArray.pop(st);
		}
	}else{
		if(func == 1){
			LoArray.push(st);
		}else{
			LoArray.pop(st);
		}
	}	
}

function buscaArray(str, cook){
	var r = false;
	var st = new String();
	st = str;
	
	if(cook == 1){
		for(var $j=0; $j < CaArray.length; $j++){
			if(CaArray[$j] == st){
				r = true;
			}
		}
	}else{
		for(var $j=0; $j<LoArray.length; $j++){
			if(LoArray[$j] == str){
				r = true;
			}
		}
	}
	
	return r;
}

isNowDate = function(){
	date = new Date();
	
	ano = date.getYear() < 1000 ? date.getYear()+ 1900 : date.getYear();
	return formatZERO(date.getDate())+"/"+formatZERO(date.getMonth())+"/"+ano;
}

formatZERO = function(n){
	if(n < 10){
		n.toString();
		n = "0"+n;
	}
	
	return n;	
}

isPop = function(url, page, other){
	poup = window.open(url,page,other);
}

isClose = function(){
	if(poup && !poup.closed){
		poup.close();
	}
}
