function showAddParticipant() {
	$("#add_participant").show();
	$("#add_participant input").removeAttr("disabled");
	$("#add_participant input").removeClass("ignore_validate");
	$("#add_participant select").removeAttr("disabled"); 
	$("#add_participant select").removeClass("ignore_validate");
	$("#add_participant textarea").removeAttr("disabled");
	$("#add_csv input").attr("disabled", "disabled");
	$("#add_csv input").addClass("ignore_validate");
	$("#add_csv select").attr("disabled", "disabled");
	$("#add_csv select").addClass("ignore_validate");
	$("#add_csv textarea").attr("disabled", "disabled");
	$("#add_csv textarea").addClass("ignore_validate");
	$("#add_csv").hide();
}

function showAddCsv() {
	$("#add_participant input").attr("disabled", "disabled");
	$("#add_participant input").addClass("ignore_validate");
	$("#add_participant select").attr("disabled", "disabled");
	$("#add_participant select").addClass("ignore_validate");
	$("#add_participant textarea").attr("disabled", "disabled");
	$("#add_participant").hide();
	$("#add_csv").show();
	$("#add_csv input").removeAttr("disabled"); 
	$("#add_csv input").removeClass("ignore_validate");
	$("#add_csv select").removeAttr("disabled"); 
	$("#add_csv select").removeClass("ignore_validate");om
	$("#add_csv textarea").removeAttr("disabled");
	$("#add_csv textarea").removeClass("ignore_validate");
}

/*
function addCompetence(category, artist) {
	$("#vote_"+category).load("/index.php?a=item/vote/add/"+artist);
}
*/

//function

var currentCategory = "";
var currentType = "";

function getCompetenceByCategory(category, parent) {
	currentCategory = category;
	if(currentType != ""){
		getCompetence(currentCategory, currentType, parent);
	}
}

function getCompetenceByType(type, parent) {
	currentType = type;
	if(currentCategory != ""){
		getCompetence(currentCategory, currentType, parent);
	}
}

function getCompetence(category, type, parent) {
	currentCategory = category;
	currentType = type;
	var requestStr = "ajax.php?case=competence&action=list&category_id=" + category + "&filter=" + type + "&parent=" + parent;
	//alert(requestStr);
	var htmlStr = $.ajax({
		url: requestStr,
		async: false
	 }).responseText;
	$("#compContainer").html(htmlStr);
}

//function setCompetenceID(itemID){
//	$("#competence_id").attr("value", itemID);
//}

function addCompetence(competenceID, competenceTitle) {
	var add_competence_index = $("#competences tr").length;
	var in_list = $("#competences #competence_"+competenceID).length;
	$("#selected_competences").show();
	if(!in_list) {
		$("#competences").prepend('\
			<tr id="competence_'+competenceID+'">\
				<td>'+competenceTitle+'<input type="hidden" name="link_competences['+add_competence_index+']" value="'+competenceID+'" /></td>\
				<td><a href="javascript:removeCompetence('+competenceID+')">verwijder</a></td>\
			</tr>\
		');
		$('#competences').tableDnD();
	}
}

function removeCompetence(competenceID) {
	$("#competence_"+competenceID).remove();
	var n_selected = $("#competences tr").length;
	if(n_selected == 0)
		$("#selected_competences").hide();
}

function removeGroup(categoryId) {

}

function selectColumn() {
	var n_checked = $(".batch_select:checked").length;
	if(n_checked > 0) {
		$(".batch_select").removeAttr("checked");
	}
	else {
		$(".batch_select").attr("checked", "checked");
	}
}

$(document).ready(function() {
													 
	$(".draggable").draggable();
	
	$(".droppable").droppable({
		/*												
		drop: function(event, ui) {
			$(this).addClass('ui-state-highlight').find('p').html('Dropped!');
		}
		*/
	});
	
	$("ul#controls").show();
		
	/* TREE */
	$$('.tree.readwrite').jstree(
		{
			types: {
				types: {
					group: {
						max_children: -1,
						max_depth: -1,
						valid_children: "all"
					},
					document: {
						max_children: 0,
						max_depth: 0,
						valid_children: "none",
						icon: { image: '/_js/plugin/jstree/_demo/file.png' }
					}					
				}
			},
			plugins : ["themes","html_data","ui","crrm","dnd","types","cookies"]
		}
	);

	$$('.tree.readonly').jstree(
		{
			types: {
				types: {
					group: { 
						max_children: 0,
						max_depth: 0,
						valid_children: "none"
					},
					document: {
						max_children: 0,
						max_depth: 0,
						valid_children: "none",
						icon: { image: '/_js/plugin/jstree/_demo/file.png' }
					}					
				}
			},
			plugins : ["themes","html_data","ui","types","cookies"]
		}
	);

	$$.fn.optionList = function() {
		var output = '<option></option>';
		$$('li > a', $$(this)).each(function() {
			var label = $$(this).text();
			var level = Math.ceil(($$(this).parentsUntil('.tree').length-1)/2);
			var value = $(this).parent().data('item-id');
			if($(this).parent().attr('rel') == "group") {
				output += '<option value="' + value + '">';
				for(i=0;i<level;i++) {
					output += '-';
				}
				output += ' ' + label + '</option>';
			}
		});
		return output;
	};
	
	$$.fn.addCounts = function() {
		$$('li[rel=group]', this).each(function() {
			var a = $$($$('a', this)[0]);
			var em = $$('em', a);
			if(!em.length) {
				a.html(a.html() + ' <em></em>');
				em = $$('em', a);
			}
			em.html('(' + $$('li[rel=document]', this).length + ')');
		});
	};	
	
	$$('.tree').bind('loaded.jstree', function() {
		$$(this).treeUpdate();
	});

	
	$$.fn.treeUpdate = function() {
		$$(this).optionList();
		$$(this).addCounts();
	};

	// rename event triggers after we've created a node
	$$('.tree').bind('rename_node.jstree', function(e, data) {
		var name = data.rslt.name;
		var obj = data.rslt.obj;
		$('#from').html($$(this).treeUpdate());
		$$.get('/ajax.php?case=rename_group&name=' + name + '&item_id=' + $$(obj).data('item-id'), function(e) {
		});
	});

	$$('.tree').bind('remove.jstree', function(e, data) {
		var obj = data.rslt.obj;
		$('#from').html($$(this).treeUpdate());
		$$.get('/ajax.php?case=remove_group&item_id=' + $$(obj).data('item-id'), function(e) {
		});
	});
	
	$$('.tree').bind('create_node.jstree', function(e, data) {
		$('#from').html($$(this).treeUpdate());
		if(data.rslt.parent.length >= 0) {
			var new_parent = data.rslt.parent;
			var parent_id_fragment = '&parent_id=' + $$(new_parent).data('item-id');
		} else {
			var parent_id_fragment = '';
		}
 		var obj = data.rslt.obj; 
		var name = "Nieuwe map";
		var type = $$(this).data('type');
		
		$$.get('/ajax.php?case=add_group&name=' + name + parent_id_fragment + '&type=' + type, function(e) {
			$$(obj).attr('data-item-id', e).attr('id', 'node_' + e);
		}, 'json');		
	});
	
	// rename event triggers after we've created a node
	$$('.tree').bind('move_node.jstree', function(e, data) {
			$('#from').html($$(this).treeUpdate());
			var dragged_node = data.rslt.o;
			var new_parent = data.rslt.np;
			var order_string = '';
			var tree = $$(new_parent).closest('.tree');
			$$('li', tree).each(function(k) { 
				order_string = order_string + $$(this).data('item-id') + ','                
			});
			var type = $$(dragged_node).attr('rel');
			if(type == "group") {
				$.get('/ajax.php?case=set_parent_and_order&node=' + $$(dragged_node).data('item-id') + '&parent=' + $$(new_parent).data('item-id') + '&order=' + order_string);
			} else {
				$.get('/ajax.php?case=set_group&node=' + $$(dragged_node).data('item-id') + '&parent=' + $$(new_parent).data('item-id')); 
			}
	}).delegate("li","click", function(e) {
			if($$(this).attr('rel') == "document") {
				var href = $$(this).data('href');
				if(href) {
					if(e.target.className == "delete") {
						var item_id = $$(this).attr('data-item-id');
						var group_id = $$(this).closest('li[rel="group"]').attr('data-item-id');
						$$(this).remove();
						$.get('/ajax.php?case=unlink_group&item='+item_id+'&group='+group_id, function(data)  {
							window.location.reload(true);
						}, 'json');
						return false;
					}
					window.location = href;
				}
			}
  });

	/*
	$$('.tree_link').live('click', function(e) {
		//window.location = $(this).attr('data-href');
	});
	*/
	
	$$('#create_tree_node').bind('click', function(e, data) {
		e.preventDefault();
		$$('.tree').jstree("create", null, 0, {data: "Nieuwe map"});
	});
	
	$$('#rename_tree_node').bind('click', function(e, data) {
		e.preventDefault();
		$$('.tree').jstree("rename");
	});	
	
	$$('#delete_tree_node').bind('click', function(e, data) {
		e.preventDefault();
		if(confirm('Deze map zal worden verwijderd. Ben je zeker?')) {
			$$('.tree').jstree("remove");
		}
	});	
	


	
	//$("a[title] img").parent().tooltip({showURL: false});
	$("span[title]").tooltip({showURL: false});
	//$("div.name a[title]").tooltip({showURL: false});
	
	
	// Forgot password
	$("#forgot-password-button").click(function() {
		$("#login-wrapper").hide();
		$("#forgot-password").show();
	}); 
	
	// Check all checkboxes
	$("#check_all").click( function() {
			if($$("input[type='checkbox']:not(:checked)").length)
				$("#content input[type='checkbox']").attr('checked', "checked");
			else
				$("#content input[type='checkbox']").removeAttr('checked');
	});
	
	// datepicker
	$(".dateNL").datepicker($.extend({}, 
	$.datepicker.regional["nl"], { 
			duration: "",
			dateFormat: "dd/mm/yy", 
			changeMonth: false, 
			changeYear: false,
			showOn: "both",
			buttonImage: "/img/datepicker/calendar.gif",
			buttonImageOnly: true 
	}));
	
	// datepicker (for end date)
	function customRange(input) {
		return {minDate: $('#start_date').datepicker('getDate')};
	}
	
	$("#end_date").datepicker($.extend({}, 
	$.datepicker.regional["nl"], { 
			duration: "",
			beforeShow: customRange,
			dateFormat: "dd/mm/yy", 
			changeMonth: false, 
			changeYear: false,
			showOn: "both",
			buttonImage: "/img/datepicker/calendar.gif",
			buttonImageOnly: true 
	}));
	
	
	$("#list_select").change(function() {
  	var selected = $(this).val();
		if(selected == "none") {
			$("#add_csv textarea").removeClass("ignore_validate");
			$("#add_csv textarea").removeAttr("disabled");
			$("#add_csv input").removeClass("ignore_validate");
			$("#add_csv input").removeAttr("disabled"); 
		}
		else {
			$("#add_csv input").attr("disabled", "disabled"); 
			$("#add_csv input").addClass("ignore_validate");
			$("#add_csv textarea").attr("disabled", "disabled");
			$("#add_csv textarea").addClass("ignore_validate");
		}
	});
	
	$$("#category_select").change(function() {
		var personal = $$("option[value="+$$(this).val()+"]", $$(this)).hasClass("personal");
		var public = $$("#public").attr("checked");
		if(personal && public) {
			$$("tr#category_select_personal").show();
		}
		else {
			$$("tr#category_select_personal").hide();
		}
	});
	
	$$("#public").change(function() {
		var personal = $$("option[value="+$$("#category_select").val()+"]", $$("#category_select")).hasClass("personal");
		var public_selected = $$("#public_category_select").val();
		var public = $$("#public").attr("checked");
		if(personal && public) {
			$$("tr#category_select_personal").show();
		}
		else if(!public_selected) {
			$$("tr#category_select_personal").hide();
		}
	});
	
	$("#evaluation_grade").change(function() {
  	var selected = $(this).val();
		if(selected == "andere") {
			$(".evaluation_grade_other").show(); 
		}
		else {
			$(".evaluation_grade_other").hide(); 
		}
		if(selected == "geen beoordeling") {
			$(".no_evaluation").show();
			$(".with_evaluation").hide(); 
		}
		else {
			$(".no_evaluation").hide();
			$(".with_evaluation").show(); 
		}
	});
	
	$("#competence_document_type").change(function() {
  	var selected = $(this).val();
		if(selected == "vorming") {
			$("#timeframe-row").show(); 
			$("#timeframe").removeAttr("disabled"); 
		}
		else {
			$("#timeframe-row").hide(); 
			$("#timeframe").attr("disabled", "disabled"); 
		}
	});
	
	$("#start_date").change(function() {
  	var start_date = $(this).val();
		if (!$("#end_date").val())
			$("#end_date").val(start_date);
	});
	
	$(".toggle-competences-button").toggle(
		function () {
			$(this).parent("div").next("div").show();
		},
		function () {
			$(this).parent("div").next("div").hide();
		}
	);
	
	$(".toggle-competence-button").toggle(
		function () {
			$(this).parent("div").next("div").show();
		},
		function () {
			$(this).parent("div").next("div").hide();
		}
	);
	
	$("#toggle-select_template-button").toggle(
		function () {
			$("#select_template").show();
			$(":submit").show();
			$("#select_template select").removeClass("ignore_validate");
			$("#select_template select").removeAttr("disabled");
		},
		function () {
			$("#select_template select").attr("disabled", "disabled");
			$("#select_template select").addClass("ignore_validate");
			$("#select_template").hide();
			$(":submit").hide();
		}
	);
	
	$(".toggle-competence_document_list-button").toggle(
		function () {
			$(this).parent("div").next("div").show();
		},
		function () {
			$(this).parent("div").next("div").hide();
		}
	);
	
	$(".toggle-faq-button").toggle(
		function () {
			$(this).parent("div").next("div").show();
		},
		function () {
			$(this).parent("div").next("div").hide();
		}
	);
	
	// TS 20110816
	$("#save-button", "#prepare").click(function() {
		var form_action = $("#competence_form", "#prepare").attr("action");
		$("#competence_form", "#prepare").attr("action", form_action+"&finish=1");
		$("#competence_form", "#prepare").submit();
	});
	
	// TS 20111219
	$("input.required", "tr.template").addClass("ignore_validate");
	$("span.alert", "tr.template").remove();
	
	
	// TS 20110927
	$(".more_dates:not(.template)").click(function() {
		var checked = $(this).attr("checked");
		if(checked) {
			$(".single_date-row").hide();
			$("input[type='text']", ".single_date-row").attr("disabled","disabled");
			$("input[type='text']", ".single_date-row").addClass("ignore_validate");
			if($("#timeframe-row").is(":visible")) {
				$("input[type='text']", "#timeframe-row").addClass("ignore_validate");
				$(".label span.alert", "#timeframe-row").hide();
			}
			$("input[type='checkbox'].more_dates").attr("checked","checked");
			$("textarea", ".more_dates-row").removeAttr("disabled");
			$("textarea", ".more_dates-row:not(.template)").removeClass("ignore_validate");
			$(".more_dates-row").show();
		}
		else {
			$(".more_dates-row").hide();
			$("textarea", ".more_dates-row").attr("disabled","disabled");
			$("textarea", ".more_dates-row").addClass("ignore_validate");
			$("input[type='checkbox'].more_dates").removeAttr("checked");
			if($("#timeframe-row").is(":visible")) {
				$("input[type='text']", "#timeframe-row:not(.template)").removeClass("ignore_validate");
				$(".label span.alert", "#timeframe-row").show();
			}$("input[type='text']", ".single_date-row").removeAttr("disabled");
			$("input[type='text']", ".single_date-row:not(.template)").removeClass("ignore_validate");
			$(".single_date-row").show();
		}
	});
	
	// TS 20111219
	// AnySurfer label - input fix
	$$(".label").each(function() {
		var label_html = $$.trim($$(this).html());
		//console.log(label_html);
		/*
		if(!label_html) {
			var choice_text = $$.trim($$(this).parent().text());
			console.log(choice_text);
		}
		*/
		if(label_html) {
			$$(this).html("<label>"+label_html+"</label>");
			var input_id = $$(this).parent("tr").find("input:not(input[type=hidden]), textarea, select").attr("id");
			if(!input_id) {
				var input_name = $$(this).parent("tr").find("input:not(input[type=hidden]), textarea, select").attr("name");
				$$(this).parent("tr").find("input:not(input[type=hidden]), textarea, select").attr("id", input_name);
				input_id = $$(this).parent("tr").find("input:not(input[type=hidden]), textarea, select").attr("id");
				//console.log(input_id);
			}
			if(input_id) {
				$$("label", this).attr("for", input_id);
			}
		}
		//console.log(input_id);
	});
	$$("input[type='checkbox']", "th.column").each(function() {
		var input_id = $$(this).attr("id");
		if(!input_id) {
			input_id = "select_all";
			$$(this).attr("id", input_id);
		}
		$(this).append("<label for='"+input_id+"' class='offscreen'>Selecteer alle rijen</label>");
	});
	$$("input[type='checkbox'].batch_select").each(function() {
		var input_id = $$(this).attr("id");
		if(!input_id) {
			input_id = "select_row-"+$(this).val();
			$$(this).attr("id", input_id);
		}
		$(this).append("<label for='"+input_id+"' class='offscreen'>Selecteer deze rij</label>");
	});
	$$("select#birthdate_day").each(function() {
		$(this).attr("title", "Geboortedatum - dag");
	});
	$$("select#birthdate_month").each(function() {
		$(this).attr("title", "Geboortedatum - maand");
	});
	$$("select#birthdate_year").each(function() {
		$(this).attr("title", "Geboortedatum - jaar");
	});
	$$("input.hasDatepicker", "form:not(#statistics_filter)").each(function() {
		$$(this).next("img").after(" <span class='date_format'>(dd/mm/jjjj)</span>");	// TS 20111219 AnySurfer datepicker date_format fix
		$$("label[for="+$$(this).attr('id')+"]").append(" <span class='offscreen'>'(dd/mm/jjjj)'</span>");
	});
	$$("select#birthdate_day").each(function() {
		$$("label[for="+$$(this).attr('id')+"]").append(" <span class='offscreen'>'(dd/mm/jjjj)'</span>");
	});
	$$("select#evaluation_grade").each(function() {
		$$(this).after(" <a href='#' title='Het gekozen beoordelingstype bepaalt welke bijkomende informatievelden zullen getoond worden.' class='help'><img src='/img/help.png' alt='helptekst' /></a>");
	});
	$$("select#competence_document_type", "form:not(#search-form)").each(function() {
		$$(this).after(" <a href='#' title='Wanneer je type \"vorming\" kiest zal een bijkomend informatieveld \"duur\" getoond worden.' class='help'><img src='/img/help.png' alt='helptekst' /></a>");
	});
	$$("input[type=checkbox].more_dates").each(function() {
		$$(this).closest("td").append(" <a href='#' title='Wanneer je kiest voor \"meerdere data\" wordt een tekstveld getoond waarin je vrij verschillende data kan invullen. In het andere geval wordt je gevraagd om een start- en einddatum in te vullen.' class='help'><img src='/img/help.png' alt='helptekst' /></a>");
	});
	$$("select[name=group_select]").each(function() {
		$$(this).after(" <a href='#' title='Wanneer je een groep selecteert, wordt de lijst beperkt tot de competentiedocumenten behorende tot die groep.' class='help'><img src='/img/help.png' alt='helptekst' /></a>");
	});
	$$("img").each(function() {
		if(!$$(this).attr('alt')) {
			//console.log($$(this).attr('src'));
			$$(this).attr('alt'," ");
		}
	});
	$$("input.hasDatepicker#end_date", "form:not(#statistics_filter)").each(function() {
		$$(this).parent("td").attr("colspan", "2");
	});
	$$("#prepare .highlighted td.label").each(function() {
		$$(this).append("<span style='color:#666;'> (ingevuld)</span>");
	});
	var nav_str = $$("h1.title", "#subnavigation").html();
	var title_str = $$("h1.title", "#page, #page-total, #page-total2").html();
	if(title_str.indexOf('<span') > 0)
		title_str = title_str.substr(0, title_str.indexOf('<span'));
	if(nav_str)
		document.title = document.title+" - "+nav_str;
	if(title_str)
		document.title = document.title+" - "+title_str;

	// TS 20110720
	$("#competence_form_real").validate();
	
	// VALIDATE FORMS
	$("#competence_form").validate({
		ignore: ".ignore_validate",
		errorContainer: "#error_message",
		//errorLabelContainer: false,	// TS: onorthodox? blijkt te werken
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("td"));
    },
		errorClass: "invalid",
		rules: {
			upload: {
				required: true,
				remote: "_plugin/check/csv.php"
			}
		}
	});
	
	$("#participant_list_form").validate({
		ignore: ".ignore_validate",
		errorContainer: "#error_message",
		//errorLabelContainer: false,	// TS: onorthodox? blijkt te werken
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("td"));
    },
		errorClass: "invalid",
		rules: {
			upload: {
				required: true,
				remote: "_plugin/check/csv.php"
			}
		}
	});
	
	$("#feedback_form").validate({
		ignore: ".ignore_validate",
		errorContainer: "#error_message",
		//errorLabelContainer: false,	// TS: onorthodox? blijkt te werken
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("td"));
    },
		errorClass: "invalid"
	});
	
		/* form validation REGISTRATIE */
	$("#add_user_form").validate({
		ignore: ".ignore_validate",
		errorContainer: "#error_message",
		//errorLabelContainer: false,	// TS: onorthodox? blijkt te werken
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("td"));
    },
		errorClass: "invalid",
		rules: {
			login: {
				remote: "/ajax_check_login.php"
			},
			password_repeat: {
				equalTo: "#password"
			},
			e_mail: {
				//required: true
				remote: "/ajax_check_email.php"
			}
		},
		messages: {
			login: {
				remote: "<br />Er is al een gebruiker geregistreerd met deze gebruikersnaam."
			},
			paswoord2: {
				equalTo: "<br />Gelieve twee maal hetzelfde paswoord in te voeren."
			},
			e_mail: {
				//required: "test"
				remote: "<br />Er is al een gebruiker geregistreerd met dit e-mail adres."
			}
		}
	});
	
	
	// ADD
	$("#organisation_individual_form_add").validate({
		ignore: ".ignore_validate",
		errorContainer: "#error_message",
		//errorLabelContainer: false,	// TS: onorthodox? blijkt te werken
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("td"));
    },
		errorClass: "invalid",
		rules: {
			login: {
				remote: "/ajax_check_login.php"
			},
			password_repeat: {
				equalTo: "#password"
			},
			e_mail: {
				//required: true
				remote: "/ajax_check_email.php"
			}
		},
		messages: {
			login: {
				remote: "<br />Er is al een medewerker (uit jouw of een andere organisatie) aangemaakt met deze login."
			},
			paswoord2: {
				equalTo: "<br />Gelieve twee maal hetzelfde paswoord in te voeren."
			},
			e_mail: {
				//required: "test"
				remote: "<br />Er is al een gebruiker geregistreerd met dit e-mail adres."
			}
		}
	});
	
	
	// EDIT
	$("#organisation_individual_form_edit").validate({
		ignore: ".ignore_validate",
		errorContainer: "#error_message",
		//errorLabelContainer: false,	// TS: onorthodox? blijkt te werken
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("td"));
    },
		errorClass: "invalid",
		rules: {
			password_repeat: {
				equalTo: "#password"
			},
			e_mail: {
				//required: true
				remote: "/ajax_check_email.php"
			}
		},
		messages: {
			paswoord2: {
				equalTo: "<br />Gelieve twee maal hetzelfde paswoord in te voeren."
			},
			e_mail: {
				//required: "test"
				remote: "<br />Er is al een gebruiker geregistreerd met dit e-mail adres."
			}
		}
	});
	
	/*
	// AJAX ADD COMPETENCE
	var options = { 
			target: '#divToUpdate', 
			url:    'ajax.php', 
			success: function() { 
					alert('Thanks for your comment!'); 
			} 
	}; 
	$(document).ready(function() { 
	// bind 'myForm' and provide a simple callback function 
	$('#add-competence_form').ajaxForm(function() {
																							
		var add_competence_index = $("#competences tr").length;
		var in_list = $("#competences #competence_"+competenceID).length;
		if(!in_list) {
			$("#competences").prepend('\
				<tr id="competence_'+competenceID+'"><input type="hidden" name="link_competences['+add_competence_index+']" value="'+competenceID+'" />\
					<td>'+competenceTitle+'</td>\
					<td><a href="javascript:removeCompetence('+competenceID+')">verwijder</a></td>\
				</tr>\
			');
		}
	}); 
	*/
	
	// AJAX COPY COMPETENCE AND LINK TO ROOT
	$(".root-competence-button").click(function() {
		var target = this;																					
		$.ajax({ 	 
			cache: false,
			url: "/ajax.php",
			data: "case=root_competence&competence_id="+$(this).prev().val(),
			success: function(message) { 
				$(target).parent("div").prev("div").show();
				$(target).parent("div").hide();
			}
		});
	}); 
	
	// AJAX COPY COMPETENCE AND MAKE "BASIS"
	$(".base-competence-button").click(function() {
		alert("hallo");																						
		var target = this;																					
		$.ajax({ 	 
			cache: false,
			url: "/ajax.php",
			data: "case=base_competence&competence_id="+$(this).prev().val(),
			success: function(message) { 
				//alert(message);
				$(target).parent("div").hide();
			}
		});
	}); 
	
	// AJAX COPY (COMPETENCE_DOCUMENT) TEMPLATE AND LINK TO ROOT
	$(".root-template-button").click(function() {
		var target = this;																					
		$.ajax({ 	 
			cache: false,
			url: "/ajax.php",
			data: "case=root_template&template_id="+$(this).prev().val(),
			success: function(message) { 
				$(target).parent("span").prev("span").show();
				$(target).parent("span").hide();
			}
		});
	}); 
	
	// AJAX GROUP ON
	$(".group-on").click(function() {
		var target = this;																					
		$.ajax({ 	 
			cache: false,
			url: "/ajax.php",
			data: "case=group&value="+1,
			success: function(message) { 
				$(target).parent("div").hide();
				$(target).parent("div").prev("div").show();
			}
		});
	}); 
	
	// AJAX GROUP OFF
	$(".group-off").click(function() {
		var target = this;																					
		$.ajax({ 	 
			cache: false,
			url: "/ajax.php",
			data: "case=group&value="+0,
			success: function(message) { 
				$(target).parent("div").hide();
				$(target).parent("div").next("div").show();
			}
		});
	}); 
	

	$("#list_select").change(function() {
  	var selected = $(this).val();
		if(selected == "none") {
			$("#add_csv textarea").removeClass("ignore_validate");
			$("#add_csv textarea").removeAttr("disabled");
			$("#add_csv input").removeClass("ignore_validate");
			$("#add_csv input").removeAttr("disabled"); 
		}
		else {
			$("#add_csv input").attr("disabled", "disabled"); 
			$("#add_csv input").addClass("ignore_validate");
			$("#add_csv textarea").attr("disabled", "disabled");
			$("#add_csv textarea").addClass("ignore_validate");
		}
	});
	
	$("#disclaimer-checkbox").click(function() {
		var checked = $(this).attr("checked");	
		if(checked)
			$("#register-button").removeAttr("disabled");
		else
			$("#register-button").attr("disabled", true);
	});
	
	$('#competences').tableDnD();
	
	// AJAX ADD CATEGORY (competence_document_group of type "user)
	$("#add-group-button").click(function() {
		var name = $("#group_name").val();
		//var href = $(".category > a").eq(0).attr("href");
		var href = document.URL
		if(href.lastIndexOf("&group=") > 0)
			var href_base = href.substr(0, href.lastIndexOf("&group="));
		else
			var href_base = href;
		$.ajax({ 	 
			cache: false,
			url: "/ajax.php",
			data: "case=add_group&name="+name,
			success: function(category_id) { 
				var href = href_base+"&group="+category_id;
				var html = "<div class='block-top-10'><span class='category'><a href='"+href+"'>"+name+"</a></span>&nbsp;&nbsp;<input type='hidden' name='category_id' class='category_id' value='"+category_id+"' /><a href='javascript:void(0)' class='delete-group-button'>verwijder</a></div>";
				// bind delete
				$("#category_list").append(html);
				$("#group_name").val("");
			}
		});
	}); 
	
	// AJAX DELETE CATEGORY (competence_document_group of type "user)
	$(".delete-group-button").click(function() {
		var target = this;																					
		var category_id = $(this).prev("input").val();		
		$.ajax({ 	 
			cache: false,
			url: "/ajax.php",
			data: "case=remove_group&id="+category_id,
			success: function(message) { 
				if(message == "success")
					$(target).parent().remove();
			}
		});
	}); 
	
	$('.combined_link').bind('click', function() { create_combined(); return false; });
	$('.trash_link').bind('click', function() { batch_trash(); return false; });			
	$('.delete_link').bind('click', function() { batch_delete(); return false; });	
	$('.recover_link').bind('click', function() { batch_recover(); return false; });
	$('.finalize_link').bind('click', function() { 
		if(!confirm('De geselecteerde competentiedocumenten finaliseren?'))
			return false;
		//console.log($("form").attr("action"));
		$("form").attr("action", $(this).attr("data-action")).submit();
		return false; 
	});			
	
	
	$$(".edit-map-button").toggle(
		function () {
			var parent_div = $$(this).closest("div.title");
			$$(parent_div).children("a").first().hide();
			$$(parent_div).children("input:text").show();
			$$(this).html("nieuwe naam opslaan");
			return false;
		},
		function () {
			var parent_div = $$(this).closest("div.title");
			var new_name = $$(parent_div).children("input:text").val();
			var item_id = $$(parent_div).children("input:hidden").val();	
			//console.log(new_name);	
			$.ajax({ 	 
				cache: false,
				url: "/ajax.php",
				data: "case=update_group_name&id="+item_id+"&name="+new_name,
				success: function(message) {
					//console.log(message);
					if(message == "success") {
						$$(parent_div).children("a").first().html(new_name);
					}
				}
			});
			$$(parent_div).children("a").first().show();
			$$(parent_div).children("input:text").hide();
			$$(this).html("wijzig naam");
			return false;
		}
	);
	
	$$(".new_document_group_name").keyup(function(event) {
		if(event.keyCode == '13') {
			var parent_div = $$(this).closest("div.title");
			var new_name = $$(this).val();
			var item_id = $$(parent_div).children("input:hidden").val();	
			//console.log(new_name);	
			$.ajax({ 	 
				cache: false,
				url: "/ajax.php",
				data: "case=update_group_name&id="+item_id+"&name="+new_name,
				success: function(message) {
					//console.log(message);
					if(message == "success") {
						$$(parent_div).children("a").first().html(new_name);
					}
				}
			});
			$$(parent_div).children("a").first().show();
			$$(parent_div).children("input:text").hide();
			$$(parent_div).find(".edit-map-button").html("wijzig naam");
			$$(parent_div).find(".edit-map-button").trigger("click");
			return false;
		}
	});

	$('#other').click(function() {
		$('#target').keyup();
	});
	
	// MATCHING PARTICIPANTS
	$$("input[type='checkbox']:not(.check_table)", "div.matching_participants").click(function(e) {
		var mp_id = $$(this).attr('class');
		var p_div = $$(this).closest("div.matching_participants");
		if($$(this).attr('checked')) {
			$$("."+mp_id).attr('checked', "checked");
			$$("table", p_div).each(function() {
				if(!$$("input[type='checkbox']:not(:checked):not(.check_table)", this).length)
					$$("input[type='checkbox'].check_table", this).attr('checked', "checked");
			});
		}
		else {
			$$("."+mp_id+":not(:disabled)").removeAttr('checked');
			$$("table", p_div).each(function() {
				if($$("input[type='checkbox']:not(:checked):not(.check_table)", this).length)
					$$("input[type='checkbox'].check_table", this).removeAttr('checked');
			});
		}
	});
	$$("input[type='checkbox'].check_table", "div.matching_participants").click(function() {
		var mp_id = $$(this).attr('class');
		var p_div = $$(this).closest("div.matching_participants");
		if($$(this).attr('checked')) {
			$$("input[type='checkbox']", $$(this).closest("table")).attr('checked', "checked");
			$$("input[type='checkbox']", $$(this).closest("table")).each(function() {
				if($(this).attr('checked')) {
					$$("input[type='checkbox']:not(.check_table)."+$$(this).attr('class'), p_div).attr('checked', "checked");
					$$("table", p_div).each(function() {
						if(!$$("input[type='checkbox']:not(:checked):not(.check_table)", this).length)
							$$("input[type='checkbox'].check_table", this).attr('checked', "checked");
					});
				}
			});
		}
		else {
			$$("input[type='checkbox']:not(:disabled)", $$(this).closest("table")).removeAttr('checked');
			$$("input[type='checkbox']", $$(this).closest("table")).each(function() {
				if(!$(this).attr('checked')) {
					$$("input[type='checkbox']:not(.check_table, :disabled)."+$$(this).attr('class'), $$(this).closest("div.matching_participants")).removeAttr('checked');
					$$("table", p_div).each(function() {
						if($$("input[type='checkbox']:not(:checked):not(.check_table)", this).length)
							$$("input[type='checkbox'].check_table", this).removeAttr('checked');
					});
				}
			});
		}
	});
	$$("input[type='checkbox'].update_original").click(function() {
		if($(this).attr('checked')) {
			$$("div.matching_participants#p_"+$(this).val()).show();
		}
		else {
			$$("div.matching_participants#p_"+$(this).val()).hide();
		}
	});
	
	
	// STATISTICS FILTER AGE GROUPS
	//$(".add-age_group-button").hide();
	$(".add-age_group-button").click(function() {
		var index = $('.age_group').length;
		var el = $('.age_group:last', $(this).parent());
		var clone = el.clone();
		$(".reset-age_group-button", clone).replaceWith('<a href="javascript:void(0)" class="remove-age_group-button">verwijder</a>');
		$(".remove-age_group-button", clone).bind('click', function() {
			$(this).parent().remove();
		});
		$('input.age_group_from', clone).val(parseInt($('input.age_group_to', clone).val())+1);
		$('input.age_group_to', clone).val('');
		$('input.age_group_from', clone).attr('name', 'age_group['+index+'][from]');
		$('input.age_group_to', clone).attr('name', 'age_group['+index+'][to]');
		clone = el.after(clone);
		//$(this).prev(".age_group").clone().
	}); 
	$(".age_group input").keyup(function() {
		var filled = 1;
		$("input", $(this).parent()).each(function() {
			if(!$(this).val()) {
				filled = 0;
			}
		}); 
		if(filled) {
			$(".add-age_group-button").css('display', 'inline-block');
		}
		else {
			$(".add-age_group-button").hide();
		}
	}); 
	$(".reset-age_group-button").click(function() {
		$('input', $(this).parent()).val('');
		$(".add-age_group-button").hide();
	});
	$(".remove-age_group-button").click(function() {
		$(this).parent().remove();
		if($('.age_group').length == 1) {
			$(".remove-age_group-button").replaceWith('<a href="javascript:void(0)" class="reset-age_group-button">leegmaken</a>');
			$(".reset-age_group-button").bind('click', function() {
				$('input', $(this).parent()).val('');
				$(".add-age_group-button").hide();
			});
		}
	});
	$(".reset-filter-button").click(function() {
		$('input, select', $(this).parent()).val('');
	});
	$(".pdf-button").click(function() {
		$("#statistics_filter").attr("target", "_blank");
	});
	
	
	if($("#page #list.competence_document_individual").length) {
		var id = window.location.hash;
		if(id) {
			$("div.competence_documents"+id).show();
		}
	}
	
	// help texts
	$('a.help').focus(function() {
		tooltip = $(this).attr('title');
		$(this).append('<strong>'+tooltip+'</strong>');
	});
	$('a.help').blur(function() {
		$(this).find('strong').hide();
	});
	
});
	
	
function create_combined() {
	var checkboxes = $('input:checked');
	var ids = '';
	// $('.combined_link').unbind(); 
	$('.combined_link').html('<img style="border: 0" src="/img/ajax.gif" alt="Loading" /> Bezig met het genereren van de PDF');
	
	// get ids
	checkboxes.each(function() {	 
		var name = $(this).attr('name');	// move[x]
		name = name.replace('move[', '');
		name = name.replace(']', '');
		
		ids = ids + '&id[]=' + name;
	});
	
	jQuery.get('/ajax.php?case=merge_pdfs' + ids, '', function(data)  { 
		
		$('.download_button').attr('href', data.url);
		$('.download_button').show();
		$('.combined_link').html('maak gecombineerde pdf');
		
		/*
		$('.combined_link').html('Download de pdf');
		$('.combined_link').attr('href', data.url);
		*/
		
	}, 'json');
}

function batch_trash() {
	if(!confirm('Bent u zeker dat u deze items wil verwijderen?')) return FALSE;
	var checkboxes = $('input:checked.batch_select');
	var ids = '';
	// get ids
	checkboxes.each(function() {	 
		ids = ids + '&id[]=' + $(this).val();
	});
	jQuery.get('/ajax.php?case=trash' + ids, '', function(data)  { 
		/*
		checkboxes.each(function() {	 
			$(this).parent().parent().fadeOut(); // remove TR
		});
		*/
		window.location.reload(true);
	}, 'json');
}
function batch_delete() {
	if(!confirm('Bent u zeker dat u deze items DEFINITIEF wil verwijderen?')) return FALSE;
	var checkboxes = $('input:checked.batch_select');
	var ids = '';
	// get ids
	checkboxes.each(function() {	 
		ids = ids + '&id[]=' + $(this).val();
	});
	jQuery.get('/ajax.php?case=delete' + ids, '', function(data)  { 
		/*
		checkboxes.each(function() {	 
			$(this).parent().parent().fadeOut(); // remove TR
		});
		*/
		window.location.reload(true);
	}, 'json');
}
function batch_recover() {
	if(!confirm('Bent u zeker dat u deze items wil herstellen?')) return FALSE;
	var checkboxes = $('input:checked.batch_select');
	var ids = '';
	// get ids
	checkboxes.each(function() {	 
		ids = ids + '&id[]=' + $(this).val();
	});
	jQuery.get('/ajax.php?case=recover' + ids, '', function(data)  { 
		/*
		checkboxes.each(function() {	 
			$(this).parent().parent().fadeOut(); // remove TR
		});
		*/
		window.location.reload(true);
	}, 'json');
}

