/*
 * jQuery Tag Filtering 0.4.0
 * Simon Georget
 * http://www.intermezzo-coop.eu
 * based on 
 * https://github.com/stevenaanen/jquery-tag-filtering
 * Copyright 2013, AppOpHetWeb
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/
(function( $ ) {
	$.fn.tagfiltering = function(options) {
		// Create some defaults, extending them with any options that were provided
		var settings = $.extend({
			items: ".filter-items",
			target_attr: "data-tags", // this parameter handle multi targets such as "data-tags,data-finalities,data-scale"
			active_class: "active",
			separator: ",",	// tags separator
			exclude_parents: false, // false or class value like "ul.filter-menu". Do not exclude_parents if you use multi targets. Useful when using multiple <ul> tags for filter and you want to make theme exclusive
			callback:function() {}
		}, options);

		try {

			// constants & preconditions
			var $items = $(settings.items).children();
			if (!$items.length)				throw "no valid target items to filter";
			var $tags = this.children();
			if (!$tags.length)				throw "called on invalid element (should be non-empty html list of tags)"

			
			handle_multiple_tags();
			
			// bind to click
			$tags.click(function(event) {
				event.preventDefault();
				
				// we get parents
				if(settings.exclude_parents) {
					var currentclass = $(this).parent().attr('class');
					console.log(currentclass);
					$(settings.exclude_parents).each(function() {
						if(!$(this).hasClass(currentclass)) $(this).children().removeClass(settings.active_class);
					});
				}
				
				var target_tag = $(this).attr("data-tag");
				
				if ($(this).hasClass(settings.active_class)) {
					$(this).removeClass(settings.active_class);
				}
				else {
					$(this).addClass(settings.active_class);
				}

				get_all_filtered_items();
				
				// call the callback and apply the scope:
				settings.callback.call(this);
		
			});
			
			// handle multiple tags 
			// if settings.target_attr has multiple values, like "data-tags,data-finalities,data-scale"
			// we create  a new filter tag and merge all values from given tags
			function handle_multiple_tags() {
				if(settings.target_attr.indexOf(',') != -1) {	
					
					// we get all differents attributes
					var targets = settings.target_attr.split(',');
					// console.log(targets);
					
					// we create a new attribute filter based on all values
					// looping on targeted items
					$items.each(function() {
						var values = []
						for (var i = 0; i < targets.length; i++) {
							var tmp = $(this).attr(targets[i]);
							// console.log(tmp);
							if(tmp != '') values.push(tmp);
						}
						$(this).attr('data-filter-zzz', values.join(settings.separator));
					});
					
					// finally, we specify the new target attribute to filter on
					settings.target_attr = "data-filter-zzz";	
					
				}
			}


			// find all items for all currently active tags
			function get_all_filtered_items() {
				
				var filtered_tags = [];
				
				var $active_tags = $tags.filter("." + settings.active_class);
				
				// no tags selected
				if (!$active_tags.length) {
					$items.each(function() {
						$(this).show();
					});
				} else {
					$active_tags.each(function(){
						filtered_tags.push($(this).attr("data-tag"));
						});
					// console.log(filtered_tags);
					// console.log($items);
					$items.each(function(){
						
						// we retrieve tags from data-tags attribute
						var tags = $(this).attr(settings.target_attr).split(new RegExp("[" + settings.separator + "] ?"));
						
						visibleFlag = true;
						// test if all wanted tags are matched. If not return false
						for (var i = 0; i < filtered_tags.length; i++) {
							if (tags.indexOf(filtered_tags[i]) == -1) {
								visibleFlag = false;        
								break;
							}
						}
						
						// display only 'true' flagged item
						if(visibleFlag) $(this).fadeIn();
						else  $(this).hide(); // do not put fadeOut() method because callback won't work fully when checking is(':visible') - @tofix
				});
				}

				// console.log(filtered_tags);

				return filtered_tags;
			}



		}
		catch (err) {
			console.log("jQuery Tag Filtering failed: " + err);
		}

		return this;
	};
})( jQuery );