$(function() {
	$("#sitesearch").bind("submit",function(){
		submitSearch();
		return false;
	});
	
	$("a.keyword").click(function(){
		var keyword = $(this).text();
		$("#sitesearch input[name='searchText']").val(keyword);
		submitSearch();
		return false;
	});

	$('.filterblok .toggle').live('click', function() {
		$(this).parent().toggleClass('collapsed');
	});
	$('.filterblok .vwselectie a').live('click', function() {
		$(this).parents('.filterblok').find('input').attr('checked', false)
		                              .attr('indeterminate', false);
		return false;
	});
	$('.filterblok li:has(ul) > input').click(function() {
		var isChecked = $(this).attr('checked');
		$(this).parents('li:has(ul):first').find('input').attr('checked', isChecked)
		                                                 .attr('indeterminate', false);
	});
	$('.filterblok input').click(function() {
		checkParentForSelection($(this));
	});
	$(".filterblok .wikiwijs-widget-Panel-commit").click(function(){
		submitSearch();
		return false;
	});
	$(".filterblok .wikiwijs-widget-NestedSelectionList").each(function(){
		initParentForSelection($(this));
	});
	
	$('.kenmerken a').click(function() {
		$(".featureblok").hide();
		var kenmerkblokid = $(this).parent().attr('id').replace('kenmerk_', 'filter_');
		$('#' + kenmerkblokid).show();
		return false;
	});
	$(".featureblok").each(function() {
		var filterblok = $(this);
		$(".vwselectie a", filterblok).click(function() {
			var elems = $("input[type='checkbox']", filterblok);
			elems.attr('indeterminate', false);
			elems.attr('checked', false);
			return false;
		});
		$(".kruisje", filterblok).click(function() {
			$(this).parents('.featureblok').hide();
			return false;
		});
	});
	$(".featureblok .wikiwijs-widget-CheckboxGroup-selectAll").click(function(){
		var isChecked = $(this).attr('checked');
		$(this).parents('.featureblok').find('input').attr('checked', isChecked);
		return true;
	});
	$(".featureblok .wikiwijs-widget-Panel-commit").click(function(){
		submitSearch();
		return false;
	});
	
	$(".drilldown").each(function() {
		var filterDrilldown = this;
		submitDrilldown(filterDrilldown);
	});
});

function initParentForSelection(elem) {
	var group = elem.children('li.wikiwijs-widget-CheckboxGroup');
	group.each(function() {
		// recurse upwards the tree
		$(this).children('ul').each(function() {
			initParentForSelection($(this));
		});
		$(this).children('input').each(function() {
			checkParentForSelection($(this));
		});
	});
}

function checkParentForSelection(elem) {
	var group = elem.parents('li:has(ul):first');
	var allChecked = group.find('ul > li > input:not(:checked)').length == 0;
	var allUnchecked = group.find('ul > li > input:checked').length == 0;
	group.children('input').attr('checked', allChecked)
	                       .attr('indeterminate', !allChecked && !allUnchecked);
	group.each(function() {
		// recurse upwards the tree
		checkParentForSelection($(this));
	});
}

function getSector() {
	var loc = document.location.href;
	var sectorStart = loc.indexOf('/sector/');
	if (sectorStart > -1) {
		sectorStart = sectorStart + '/sector/'.length;
		var sectorEnd = loc.indexOf('/', sectorStart);
		if (sectorEnd > -1) {
			var sector = loc.substring(sectorStart, sectorEnd);
			return sector;
		}
	}
	return "all";
}

var submittedSearch = false;
function submitSearch() {
	if (!submittedSearch) {
		var searchText = $("#sitesearch input[type='text']").val();
//		if (searchText.length == 1 ) {
//			alert("Zoek met minimaal 2 karakters");
//		}
//		else {
			submittedSearch = true;
			
			var form = $("#sitesearchfiltered");
			form.find("input").remove().end()
			
			addHiddenField(form, "searchText", searchText);
			
			$(".filterblok input[type='checkbox']").each( function() {
				if ($(this).attr('checked')) {
					addHiddenField(form, $(this).attr("name"), $(this).val());
				}
			});
			$(".selectiegroep input[type='checkbox']").each( function() {
				if ($(this).attr('checked')) {
					addHiddenField(form, $(this).attr("name"), $(this).val());
				}
			});
		
			$('.filterblok').each(function() {
				var state = $(this).find('.wikiwijs-widget-CheckboxGroup').each(function() {
					if (!$(this).hasClass("collapsed")) {
						addHiddenField(form, "filterState", $(this).attr("id"));
					}
				});
			});
			
			form.submit();
//		}
	}
}

function submitDrilldown(filterDrilldown) {
	
		var map = new Object();
		
		var searchText = $("#sitesearch input[type='text']").val();
		addToMap(map, "searchText", searchText);
		
		$(".filterblok input[type='checkbox']").each( function() {
			if ($(this).attr('checked')) {
				addToMap(map, $(this).attr("name"), $(this).val());
			}
		});
		$(".selectiegroep input[type='checkbox']").each( function() {
			if ($(this).attr('checked')) {
				addToMap(map, $(this).attr("name"), $(this).val());
			}
		});
		addToMap(map, "drilldown", filterDrilldown.id);
		searchDrilldownService.drilldown(map, 
			{	
			    callback: function(data) {
							$("li", filterDrilldown).each( function() {
								var chackboxValue = $("input[type='checkbox']:first", this).val();
								if (chackboxValue != 'SELECT-ALL') {
									var dataCount = 0;
									if (data != null && typeof data == 'object') {
										if ( data[chackboxValue] ) {
											dataCount = data[chackboxValue];
										}
									}

									if (dataCount == 0) {
										$(this).remove();
									}
									
									var counter = $('<span class="resulttxt">(' + dataCount + ')</span>');
									$("label:first", this).append(counter);
								}
							});
							$("div.toggle ~ ul", filterDrilldown).each(function() {
								var elem = $(this);
								if ( elem.children("li").size() < 1 ) {
									elem.parent().children("div.toggle").remove();
									elem.parent().removeClass('wikiwijs-widget-CheckboxGroup');
									elem.parent().addClass('wikiwijs-widget-NestedSelectionList-leaf');
								}
							});
						},
				errorHandler:function(message) { /* ignore, drilldown not availlable */ }
			}
		);
}

function addHiddenField(form, name, value) {
	var input = $("<input type='hidden' name='" + name + "' value='' />");
	input.attr('value', value)
	form.append(input);
}

function addToMap(map, name, value) {
	if (! map[name]) {
		map[name] = new Array();
	}
	var length = map[name].length;
	map[name][length] = value;
}
