function setSelection(uid) {
    var prefix = '.filter_';
    var defaultCssClass = '.filter-me';

    if(uid == 0) {
        $(defaultCssClass).each(function(){
            if(!$(this).hasClass('nohit')) {
                $(this).removeClass('filtered');
                //$(this).show();
            }
        });
    }
    else {
        //$(defaultCssClass).hide();
        $(defaultCssClass).each(function(){
            $(this).addClass('filtered');
        });
        $(prefix+uid).each(function(){
            if(!$(this).hasClass('nohit')) {
                $(this).removeClass('filtered');
                //$(this).show();
            }
        })
    }

    document.location.hash = 'filter_'+uid;
}


function disableNotFoundEntries() {
  var prefix = '.filter_';
  var defaultCssClass = '.filter-me';
  var updateTheSelect = false;
  var theSelect = $('#category-filter');
	var thisOptions = $(theSelect).find('option');
	$(thisOptions).each(function(i){
		var thisVal = $(this).attr('value');
		if(thisVal > 0 && $(prefix+thisVal).length == 0) {
      $(this).remove();
      updateTheSelect = true;
    }
	});
	if(updateTheSelect == true) {
    $.jNice.SelectUpdate(theSelect);
  }
}

function getSelection() {
	var hash = document.location.hash;
	var search = '#filter_'
	var toShow = 0;

	if(hash.indexOf(search) > -1) {
		toShow = hash.substring(search.length);
		setSelection(toShow);
	
    /*if a select filter is on the page, set it to the right value*/
    $('select#category-filter option[value='+toShow+']').attr('selected', 'selected');
    $.jNice.SelectUpdate('#category-filter');
  }
}

function filterByTitle() {
    var brands = $('.single-brand');

    $('#brand-live-filter').focus(function(){
    	if(!$(this).attr('initvalue')) {
        $(this).attr('initvalue', $(this).val());
        $(this).attr('value', '');
        
        /*bugfix: kill all hovers*/
      }
      $('.brandname').remove();
    });
    
    
    $('#brand-live-filter').mouseover(function(){
      /*bugfix: kill all hovers*/
      $('.brandname').remove();      
    });
        
    

    //hover fix for ie6
    /*
		if(jQuery.browser.msie == true && jQuery.browser.version < 7) {
        brands.each(function(){
            var links = $(this).children('a');
            links.mouseover(function(){
                $(this).addClass('hover');
                $(this).children('span').css('display', 'block');
            }).mouseout(function(){
                $(this).removeClass('hover');
                $(this).children('span').css('display', 'none');
            })
        });
    }
    */


    $('#brand-live-filter').bind("change keyup", function() {
        var searchWord = $(this).val().toLowerCase();
        brands.each(function(){
            $(this).addClass('nohit');
            $(this).removeClass('hit');
           var thisTitle = $(this).attr('title').toLowerCase();
           if(thisTitle.indexOf(searchWord) == 0) {
                $(this).removeClass('nohit');
                $(this).addClass('hit');
           }

        });
      });
    $('#brand-live-filter').blur(function(){
        if($(this).val() == '') {
            $(this).val($(this).attr('initvalue'));
        }
    })
}

$(document).ready(function(){
  disableNotFoundEntries();
	getSelection();
  filterByTitle();
});


/*
* Plugin for filtering content elements by attributes
*/

var filterByAttributeSelection;
var filterByAttributeSelects;

(function($) {
	var selection;
	$.fn.filterByAttribute = function(options) {
		filterByAttributeSelection = this;
		filterByAttributeSelects = $('#jobcat, #jobarea, #jobbrand');
		
		filterByAttributeSelects.change(function(){
			selectHandler($(this));			
		});
		updateSelect();
	}
	
	function selectHandler (selector, selection) {
	
		var selValue = $(selector).val();
		var selId = $(selector).attr('name');
		
		//display all?
		if(selValue == '-1') {
			$(filterByAttributeSelection).removeClass(selId+'hidden');
		}
		
		//else, check each element if it should be displayed
		else {
			$(filterByAttributeSelection).each(function(){
				if($(this).attr(selId) && ($(this).attr(selId) != 'disabled') && ($(this).attr(selId) != selValue)) {
					$(this).addClass(selId+'hidden');
				}
				else {
					$(this).removeClass(selId+'hidden');
				}
			});
		}
		updateSelect();
		updateHeader();
	}
	
	function updateHeader(){
		resetHeader();
		var jobcatHeaders = $('.jobcat-header');
		jobcatHeaders.each(function(){
			var headerToCheck = $(this).attr('jobcat');
			var jobTeasers = $('.job-teaser[jobcat='+headerToCheck+']:visible');
			if(jobTeasers.length < 1){
				$(this).css('display', 'none');
			};
		});
	}
	
	function updateSelect(){
		resetFakemenu();
		var selectors = [];
		$(filterByAttributeSelects).each(function(){
			selectors.push($(this).attr('id'));
		});
		
		$(filterByAttributeSelects).each(function(){
			//check if there are visible elements with with the required attribute
			var thisId = $(this).attr('id');
			//store all visible items to only operate on a subselection
			var otherSelectors = [];
			$(selectors).each(function(){
				this.toString() != thisId ? otherSelectors.push(this.toString()) : '';
			});
			
			var otherSelectorString = '';
			$(otherSelectors).each(function(){
				var thisVal = $('#'+this).val();
				if(thisVal != -1) {
					otherSelectorString += '['+this+'=' + thisVal +']';
				}
			});
			
			//iterate over all options - $(this.options) does not work in IE
			var thisOptions = $(this).find('option');
			$(thisOptions).each(function(i){
				var thisVal = $(this).attr('value');
				if(thisVal != -1){
					var visible = $(filterByAttributeSelection).filter('['+thisId+'='+thisVal+']'+otherSelectorString);
					//if no job is available for the selection, disable the link
					if(visible.length < 1) {
						disableFakemenuEntry(thisId, i);
					}
				}
			})
		});
	}
	
	function resetHeader(){
		$('.jobcat-header').css('display', 'block');
	}
	
	function resetFakemenu() {
		$('.disabled-fake-select').removeClass('disabled-fake-select');
		$('.fake-select-replacement').remove();
	}
	
	function disableFakemenuEntry(select, index) {
		var selectTag = $('#'+select);
		var fakeSelectEntry = $(selectTag).parent().find('a[index='+index+']');
		var fakeSelectEntryText = fakeSelectEntry.text();
		fakeSelectEntry.after('<span class="fake-select-replacement">'+fakeSelectEntryText+'</span>');
		fakeSelectEntry.addClass('disabled-fake-select');
		
	}
	
})(jQuery);

$(document).ready(function(){
	jQuery('.job-teaser, .jobcat-header').filterByAttribute();
});