$(document).ready(function() { 
	
	// alert('loaded');
	
	var a_zonas = new Array( "ccapfed", "cgranba", "cint", "cext" );
	var filtros_on = new Array();
	
	var grupos = new Object();
	
	function ag_filtra () {
		var tipos = new Array();
		
		// $("#wait").show();
		$("#results").hide();
		
		jQuery.each( filtros_on , function() { 
			var t = this.split("_")[1];
			if ( tipos.length == 0 || jQuery.inArray(t,tipos) == -1 ) {
				tipos.push(t);
			}
		});

		var selitems = $(".items > .item");
		var allitems = selitems;
		selitems.addClass("hid"); // Le agrega la clase "hid" a todos los items, para dejarlos en cero.
		selitems.hide(); //.css("border", "");
	
		jQuery.each( tipos , function() { 
			// Por cada tipo de filtro hago un filter (sirve para cuando los filtros son inclusivos)
			var t = this;
			var selclasses = jQuery.grep(filtros_on, function(a){
				return a.indexOf(t) != -1
			});
			var flt = selclasses.join(", ");
			selitems = selitems.filter(flt);
		});

		selitems.removeClass("hid"); // Le saca la clase "hid" que implica que estos son los que no se muestran
		selitems.show();
		
		var seccs = new Array("ccapfed","cgranba","cint","cext");
		// var seccs = new Array("xxx");
		
		jQuery.each(seccs, function() { 
			if ( $("#ag_"+ this).length != 0 ) {
				// var hdnitms = $("#ag_"+ this +" > .items > .item:hidden");
				var	hdnitms = $("#ag_"+ this +" > .items > .hid");
				var allitms = $("#ag_"+ this +" > .items > .item");
				var liherenum =  $("#ag_"+ this +" .ag_filtros_cat li.here").attr("id").split("_")[3]
					// Selecciona el número del label (categoria) actualmente seleccionado.
				if (hdnitms.length == allitms.length && liherenum == 0 ) {
					$("#ag_"+ this).hide("slow");
				} else {
					$("#ag_"+ this).show();
				}
			}
		}); 

		if (selitems.length != allitems.length ) {
			if (selitems.length > 0 ) {
				if (selitems.length == 1) {
					$("#results").text("se ha encontrado 1 ítem");
				} else {
					$("#results").text("se han encontrado " +selitems.length+ " ítems");
				}
			} else {
				$("#results").text("no se han encontrado ítems");
			}
			$("#results").show();
		}

	}

	// Si presiona ctrl-click se pasa a aginclusive
	var aginclusive = false;
	
	$(document)    
		.keydown(function(event){
                if (event.keyCode == 17){
                        aginclusive = true;
                }
        })
        .keyup(function(event){
                if (event.keyCode == 17){
                        aginclusive = false;
                }
        });
		
	var filtrosli = $("#ag_filtros li ~ .labels, .ag_filtros_cat .labels");
		
	$(filtrosli).css("cursor","pointer");
	
	
	$(filtrosli).hover(function () {
      $(this).addClass("over");
    	}, function () {
      $(this).removeClass("over");
    });
	
	
	$(filtrosli).click( 
			
			function(){
				
				var ligroup = $(this).parent().children("li.labels"); // Estos son todos los labels de este grupo
				var lifirst = ligroup.filter(":first"); // Este es el "Todos"
				var thisgroup = $(this).attr("id").split("_")[2];
				var thisnumber = $(this).attr("id").split("_")[3];
				
				// Primero, simplemente le pone "here" al que no lo tiene y viceversa.
				if ($(this).hasClass("here")) {
					$(this).removeClass("here");
				} else {
					if ( ! aginclusive ) // si no presionó ctrl-click
						ligroup.removeClass("here"); // borra todas las demás seleccionadas
					$(this).addClass("here");
				}
				
				if ( ligroup.filter(".here").length == 0) {
					// Si no hay ninguno seleccionado, selecciona el "Todos".
					lifirst.addClass("here");
				} else if ( lifirst.attr("id") == $(this).attr("id") ) {
					// Si el que está seleccionado es el "Todos", tengo que asegurarmne de desactivar los demás.
					ligroup.not(this).removeClass("here");
				} else {
					// Si el que acaba de seleccionar no es el "Todos", tengo que desactivar el "Todos".
					lifirst.removeClass("here");
				}
				
				// Borra todos los registros del presente grupo, para asignarlos de nuevo
				filtros_on = jQuery.grep(filtros_on, function(n, i){
      				return ( n.indexOf("ag_"+thisgroup) == -1 );
    			});
				
				// Si el "Todos" no está seleccionado, agrega al array de filtros el label seleccionado
				if ( ! lifirst.hasClass("here") )
					ligroup.filter(".here").each( function() {
							filtros_on.push( '.'+ this.id.replace(/off_/,'') ) ;
					});
				
				// alert(filtros_on);
				
				aginclusive = false ; // Por las dudas, reseteo la variable.
				ag_filtra();
				
				return;
								
			});

	$("XXX#ag_filtros a, XXX.ag_filtros_cat a").click( 
			function(){
				var parli = $(this).parents("li");
				var thisclass = '.'+ this.id.replace(/off_/,'') ;
				if ( ! parli.hasClass("here") ) {
					parli.addClass("here");
					if ( ! this.id.match(/_0$/)) {
						
						$("#" + this.id.replace(/[0-9]*$/,'0')).parents("li").removeClass("here"); // 
						filtros_on.push(thisclass);
						$(thisclass + " .off_ag_lnk:contains('" +$(this).text()+"')").css("text-decoration", "underline");
						ag_filtra();
					} else {
						$(this).parent("li").nextAll().filter(".here").children('a').trigger("click"); 
					}	
				} else {
				
					if ( ! this.id.match(/_0$/)) {
						parli.removeClass("here");
						if ( parli.parents("ul").children("li.here").length == 0 ) {
							// 
							$("#" + this.id.replace(/[0-9]*$/,'0')).parents("li").addClass("here");									
						}
						filtros_on.splice(jQuery.inArray(thisclass,filtros_on),1);
						$(thisclass + " .off_ag_lnk:contains('" +$(this).text()+"')").css("text-decoration","none");
						ag_filtra();
					} else {
						alert("seleccione algun filtro");								
					}	
				}
			});
	
	$("XXXXXX#ag_filtros > ul > li > a, .XXXXXXXXXag_filtros_cat > ul > li > a").toggle( 
			function(){
				if ( this.id.match(/_0$/)) {
					$(this).parents("li").removeClass("here");
					// alert("todos off");
				} else {
					// 
					$(this).parents("li").parents("ul").children("li").filter(":nth-child(2)").removeClass("here");
					// 
					$(this).parents("li").addClass("here");
					// $("#" + this.id.replace(/[0-9]*$/,'0')).parents("li").removeClass("here"); // 
					var thisclass = '.'+ this.id.replace(/off_/,'') ;
					filtros_on.push(thisclass);
					$(thisclass + " .off_ag_lnk:contains('" +$(this).text()+"')").css("text-decoration", "underline");
					ag_filtra();
				}
			},
			function(){
				if ( this.id.match(/_0$/)) {
					$(this).parents("li").addClass("here");
					$(this).parent("li").nextAll().filter(".here").children('a').trigger("click");
					// alert("todos on");
				} else {
					$(this).parents("li").removeClass("here");
					var thisclass = '.'+ this.id.replace(/off_/,'') ;
					filtros_on.splice(jQuery.inArray(thisclass,filtros_on),1);
					$(thisclass + " .off_ag_lnk:contains('" +$(this).text()+"')").css("text-decoration","none");
					ag_filtra();
				}
			 }
		);

$(".off_ag_lnk").click( 
			function(){
				var thisliid = '#off_'+ this.id.replace(/off[0-9]*_/,'') ;
				$(thisliid).trigger('click');
			});

}); // 
