
	/* ------------	::::: FILTERING OF TAGS ::::::----------------------------------------------
	*	
	*	Whenever the user types in the search-field the following function is executed
	*	It creates a regexp object and calls the test-method on the content of 
	*	each of the text-nodes to see if it mathces. If so it is added to the _doesContain
	*	array, if not it's added to the _notContains array. When it's done it hides all of 
	*	the elements in the _notContains and shows alle the elements of the _doesContain array.
	*
	*	@parem - input_field : 
	*	This is the input field from which to take the search string (jQuery object)
	*	@parem - list_to_filter
	*	This is the list (ul/ol) that the filtering function will search through and match
	*	(jquery object)
	*	@parem - properties_dictionary : 
	*	This is a javascript object which gives the user the ability to enable special features
	*	
	*
	------------------------------------------------------------------------------------------*/
	function add_filtering_to_field(input_field, list_to_filter, properties_dictionary) {
		

		var _searchString = "";
		var _doesContain = [];
		var _notContains = [];
		var _regxp;
		var _that;
		
		/** --------------------------------------------------------------- 
		*	This is where the actual filtering is going on
		--------------------------------------------------------------- **/
		
		function filter_list(){
			
			if (input_field.val().length >= _properties_dictionary.min_chars)
			{
				_searchString = input_field.val();
				_regxp = new RegExp('\\b'+ _searchString, "i"); // new _searchString 
				_notContains = []; // empty the array
				_doesContain = []; // empty the array
			         
				// -----------------------------------------------------
	            // Loop through each item and see if it matches

				list_to_filter.find('li').each(function(){ 
					_that = $(this);
				
					var string = _that.text().toLowerCase();
					if (_regxp.test(string)) 
					{
						_doesContain.push(_that);
					} 
					else 
					{
						var was_in_ignore_array = false;
						$.each(_properties_dictionary.ignore, function(i,n) {
							if (_properties_dictionary.ignore[i] == _that.attr('class')) {
								_doesContain.push(_that); 
								was_in_ignore_array = true;
							}
						});
						if (!was_in_ignore_array) {
							_notContains.push(_that);	
						} 
					}
					if (input_field.val().length > 0) { show_list(); } 
				});
			
				// -----------------------------------------------------
				// hide the ones that doesn't match
			
				$.each(_notContains, function(i,n){ 
					_notContains[i].hide();
				});
			
				// -----------------------------------------------------
				// show the ones that do match in case they were hidden
			
				$.each(_doesContain, function(i,n){ 
					if (_doesContain.length > 0) {
					    _doesContain[i].show();
					}
				});
			
				// -----------------------------------------------------
				// If the client has added any 'dividers' lets add the
				// text If divider is turned on, check if all entities in 
				// any group is hidden
			
				$('.nomatches').remove();
				$.each(_properties_dictionary.ignore, function(i,n){
				    $('.' + _properties_dictionary.ignore[i]).each(function(){
				        var all_are_hidden = true; 
	    			    var current_item = $(this).next();
	    			    while(!(current_item.is('.divider')) && all_are_hidden === true && current_item.height() !== null)
	    			    {
	    			        if(current_item.is(':visible')) { all_are_hidden = false;}    
	    			        current_item = current_item.next();
	    			    }
	    			    if (all_are_hidden) { $(this).append('<p class="nomatches">Der er desværre ingen ' + $(this).text() + ' der matcher'); }

	    			});
				});
				
				// -----------------------------------------------------
				// Finaly, if the list is hidden and a search query 
				// has been typed, show the list
				show_list();
			} else 
			{	
				hide_list();
			}
		}
		
		/** --------------------------------------------------------------- 
		This simply resets the value of the input field, and then invokes
		filter_list to reset it.
		--------------------------------------------------------------- **/
		function reset_search(){
			input_field.val('');
			filter_list();
		}
		
		/** --------------------------------------------------------------- 
		Hides the list, however only if the control_visibility ivar of the 
		properties_dictionary is set to true
		--------------------------------------------------------------- **/
		function hide_list(){
			if (_properties_dictionary.control_visibility) { list_to_filter.fadeOut(300); }
			if (_properties_dictionary.clear_on_blur) { reset_search(); }
			if (_properties_dictionary.navigation) { list_to_filter.find('.selected').removeClass('selected'); }
		}
		
		/** --------------------------------------------------------------- 
		Shows the list, however only if the control_visibility ivar of the 
		properties_dictionary is set to true
		--------------------------------------------------------------- **/
		function show_list() {
			if (_properties_dictionary.control_visibility) { list_to_filter.fadeIn(300); }
		}
		
		/** --------------------------------------------------------------- 
		Navigates the list according to the string that is passed. It also
		updates the text-field according to the value of the selectd element
		@parem  direction   If 'down' it will select the next visible element
		                    else the previous
		--------------------------------------------------------------- **/
		function navigate_list(direction) 
		{
		    function find_next_visible()
		    {
		        var tagishidden = false;
		        var is_a_link = false;
        		var start_tag = list_to_filter.find('a.selected').parent();
        		        		
        		while(tagishidden || !is_a_link) 
        		{
        			if (start_tag.size() === 0) 
        			{
        			    return list_to_filter.find('li:visible').eq(1).find('a');
        			}
        			start_tag = (direction == 'down') ? start_tag.next() : start_tag.prev() ;
        			tagishidden = (start_tag.is(':hidden')) ? true : false; 
        			is_a_link = (start_tag.find('a').size() > 0) ? true : false;
        		}
        		return start_tag.find('a');
		    }
		    
		    if (_properties_dictionary.navigation) 
		    {
		        var next_tag = ( list_to_filter.find('.selected').size() > 0 ) ? find_next_visible() : list_to_filter.find('li:visible a').eq(0);
		        list_to_filter.find('a.selected').removeClass('selected');
		        next_tag.addClass('selected');
		        
		        var value = next_tag.text();
		        var regexp_category = new RegExp(/(.*)\(.*\)/);
		        var regexp_person = new RegExp(/(.*) [0-9]* følgere/);
		        console.log(value);
            	var result_array = (regexp_category.test(value)) ? value.match(regexp_category,"i") : value.match(regexp_person, "i") ;
				input_field.val(result_array[1]);
		    }
		}
		
		/** --------------------------------------------------------------- 
		This initializes the properties_dictionary. It creates the default
		values when the user neclected to do so
		--------------------------------------------------------------- **/
		function initialize_properties_dictionary(){
			var obj = (properties_dictionary === undefined) ? {} : properties_dictionary;
			obj.control_visibility = (obj.control_visibility === undefined) ? false : properties_dictionary.control_visibility;
			obj.ignore = (obj.ignore === undefined) ? '' : properties_dictionary.ignore;
			obj.navigation = (obj.navigation === undefined) ? false : properties_dictionary.navigation;
			obj.clear_on_blur = (obj.clear_on_blur === undefined) ? true : properties_dictionary.clear_on_blur;
			obj.min_chars = (obj.min_chars === undefined) ? 0 : properties_dictionary.min_chars;
			return obj;
		}
			
/** ------------------------------------------------------------------------
	Now, lets wire the whole ting together to satisfy the properties object
	handed to us in the initial function call
 	--------------------------------------------------------------------- **/
		
		// Initialize the whole thing.
		var _properties_dictionary = initialize_properties_dictionary();
		
		// --------------------------------------------------------------- 
		//	The following block is invoked whenever The user types something 
		//	into the input_field 
		
		input_field.bind('keyup',function(event){
			
			switch(event.keyCode) {
			    case 27 :
			        hide_list(); //escape was pressed	
					input_field.val('');
			        break;
			    case 38 :
			        navigate_list('up');
			        break;
			    case 40 : 
			        navigate_list('down');
			        break;
			    case 13 : // enter
			        if ( !$('.nomatches').is(':visible') ){
						if (!list_to_filter.find('.selected').size() > 0)
						{
							list_to_filter.find('.category:visible a').eq(0).addClass('selected');
						}
						window.location = list_to_filter.find('.selected').attr('href');
					}
			        break;
			    default :
			        filter_list();
			        break;
			}   
		});
        input_field.bind('focus', function(){ 
            input_field.val('');
        });

		input_field.bind('blur', function()
		{ 
			hide_list(); 
		});			
		
	}
	
