$(function() {

	$("fieldset.close > *:not(legend)").hide();

	$("fieldset.kb_optionlist input.iptswap").click(function() {
		var button   = $(this);
		var fieldset = button.parents("fieldset");

		if (fieldset.hasClass("open")) {
			button.attr("value","klap uit");
			fieldset.removeClass("open").addClass("close");
			fieldset.find("> *:not(legend)").fadeOut();
		} else {
			button.attr("value","klap in");
			fieldset.removeClass("close").addClass("open");
			fieldset.find("> *:not(legend)").fadeIn();
		}
	});

	$("div.totalcount input:checkbox").click(function() {
		var coll = $(this).parents("div.totalcount").find("input:checkbox");
		var map = [];
		var config = $.microFormat($(this).parents("div.totalcount").attr("class"));

		coll.each(function(index, obj) {
			var itemid = $(obj).parents("div:first").find("span.resultnumbers").attr("id").substring($(obj).parents("div:first").find("span.resultnumbers").attr("id").lastIndexOf("_") + 1);
			var checked = (obj.checked) ? 1 : 0;

			map.push('{"Key":' + itemid + ',"Value":' + checked + '}');
		});

		var url = config.url + "=[" + map.join() + "]";

		/* get data and walk through resultnumbers spans */
		$.getJSON(url, function(data) {
			$(data.d).each(function(index,obj) {
				/* get corresponding checkbox */
				var chkb = $("span#item_" + obj.Key).parents("div:first").find("input:checkbox");

				/* set resultnumbers span to value */
				$("span#item_" + obj.Key).text("(" + obj.Value + ")");

				/* disable or enable checkbox based on returned value */
				if (obj.Value == 0) {
					chkb.attr("disabled","disabled");
					chkb.parents("div:first").addClass("disabled");
				} else {
					chkb.removeAttr("disabled");
					chkb.parents("div:first").removeClass("disabled");
				}
			});

			/* set total value */
			$("span#total").text(data.d[0].Value);

		});
	});

});