(function($)
{
	var work_filter_name = 'work_filter';
	var work_filter_description_name = 'work_filter_description';
	var work_filter_images_folder = 'images/work_filter/';
	var work_name = 'work';
	var categories_name = 'Categories';
	var categorie_separator = '/';

	function hideElement(el)
	{
		el.slideUp();
	}

	function showElement(el)
	{
		el.slideDown();
	}
	
	function cat_exists_within(activeCats, cats)
	{
		var found = false;
		$.each(cats, function(index, cat)
		{
			if ($.inArray(cat, activeCats) > -1)
			{
				found = true;
				return;
			}
		});

		return found;
	}

	function filter()
	{
		var activeCategories = [];
		
		var work_filter = $('#' + work_filter_name);
		$('li', work_filter).each(function()
		{
			if ($(this).data('selected') === true)
			{
				activeCategories.push($(this).data('description'));
			}
		});

		$('div.' + work_name + ' > dl').each(function()
		{
			var work_dl = $(this);
			$('dt', work_dl).each(function()
			{
				if($(this).text().indexOf(categories_name) >= 0)
				{
					var dd = $(this).next('dd');

					var cats = dd.text().split(categorie_separator);
					
					if(!cat_exists_within(activeCategories, cats))
					{
						hideElement(work_dl.parent());
					}
					else
					{
						showElement(work_dl.parent());
					}

					return;
				}
			});
		});
	}

	function transformWorkFiltersToImages()
	{
		var work_filter = $('#' + work_filter_name);
		work_filter.append('<p id = "' + work_filter_description_name + '"></p>');
		
		$('li', work_filter).each(function(index)
		{
			// get info
			var category = $('input', this)[0].getAttribute('id');
			var checked = $('input', this)[0].checked;
			var image_path = work_filter_images_folder + category.split(work_filter_name + '_')[1] + '.jpg';
			// append info to thingies
			$(this).data('description', $('label', this)[0].firstChild.nodeValue);
			// remove unessecary thingies
			$(this).children().remove();
			// make new thingies
			image_path = 'url(' + image_path + ')';
			$(this).css('background-image', image_path);
			if(checked)
			{
				$(this).css('background-position', 'center bottom');
				$(this).data('selected', true);
			}
			// adding events
			
			$(this).mouseover(function()
			{
				$(this).css('background-position', 'center bottom');
				$('#' + work_filter_description_name).text($(this).data('description'));
			});
			$(this).mouseout(function()
			{
				if (!$(this).data('selected')) { $(this).css('background-position', 'center top'); }
				$('#' + work_filter_description_name).text('');
			});
			$(this).click(function()
			{
				$(this).data('selected', !$(this).data('selected'));
				$(this).css('background-position', $(this).data('selected') ? 'center bottom' : 'center top');
				filter();
			});
		});

		$('input', work_filter).remove();
		work_filter.addClass('work_filter_from_js');
	}
	
	$(document).ready(function()
	{
		transformWorkFiltersToImages();
	});
})(jQuery);
