/**
 * This retrieves the members of a group to display in a form.
 *
 * @param Node group_element
 * @param targetElement
 */
function updateGroupMembers(group_element) {
	group_id = $(group_element).val();
	
	// Collect selected contacts
	contacts = new Array();
	$('input.contact-selected').each(function () {
		contacts.push($(this).val());
	});

	// Collect selected admins
	admins = new Array();
	$('input.manager-selected').each(function () {
		admins.push($(this).val());
	});

	$.getJSON(own_url + "pg/activity/ajax/list_group_members/" + group_id,
		function (data) {
			// Do Contacts
			targetElement = '#activity_form_edit_contact_person';
		
			// Find default option (text)
			defaultText = $(targetElement +' option[value=""]').remove();
			
			// truncate contacts-select
			$(targetElement +' option').remove();
			
			// Add default
			$(targetElement).append(defaultText);
			
			// Add group-members
			for (i=0;i<data.length;i++) {
				name = data[i].name;
				id = data[i].guid;

				// skip already-selected ids
				if (in_array(id, contacts)) {
					continue;
				}

				$(targetElement).append('<option value="'+ id +'">'+ name +'</option>');
			}

			// Do admins
			targetElement = '#activity_form_edit_manager';

			// Find default option (text)
			defaultText = $(targetElement +' option[value=""]').remove();

			// truncate contacts-select
			$(targetElement +' option').remove();

			// Add default
			$(targetElement).append(defaultText);

			// Add group-members
			for (i=0;i<data.length;i++) {
				name = data[i].name;
				id = data[i].guid;

				// skip selected ids
				if (in_array(id, admins)) {
					continue;
				}

				$(targetElement).append('<option value="'+ id +'">'+ name +'</option>');
			}
		}
	);
}

/**
 * This function locks the contact to the activity by replacing the form elements with hidden fields.
 * It also duplicates the form-element and reinitialises the available options.
 *
 * @param Node source
 * @return boolean false to stop propagation
 */
function add_contact(source) {
	if (is_valid_contact(source)) {
		duplicate_form_segment(source)
		lock_contact(source);
	}

	return false;
}

/**
 * Deletes contact from list and feeds the name and ID back into the other selectboxes
 *
 * @param source origin of event
 */
function del_contact(source) {
	dat = $(source).parents('.contact-segment').eq(0);
	dat_extra = dat.next('.contact-segment-extra').eq(0);
	
	dat_extra.remove();
	
	name = $('.contact', dat).eq(0).text();
	id = $('.hidden-id', dat).eq(0).val();
	
	dat.remove();
	
	$('.contact-segment select').append($("<option value=\""+ id +"\">"+ name +"</option>"));
	return false;
}

/** 
 * Verifies if contact in the selectbox is actually a contact.
 *
 * @param source the source lement
 * @return true or false, answering above question.
 */
function is_valid_contact(source)
{
	retval = false;

	contact_form = $(source).parents('.contact-segment').eq(0);
	if ($('.basic-contact', contact_form).val() != "") {
		retval = true;
	}
	
	return retval;
}

/**
 * This converts selectboxes into plain text with hidden fields and adds a remove-link.
 */
function lock_contact(source) {
	contact_form = $(source).parents('.contact-segment').eq(0);

	// Turn self into plain-text with two added fields
	dat = contact_form.find('.basic-contact :selected', contact_form).eq(0);
	fieldname = contact_form.find('.basic-contact', contact_form).eq(0).attr('name');
	name = dat.text();
	val = dat.attr('value');
	
	select_field = $('.basic-contact', contact_form);
	
	$("<p class=\"contact\">"+ name +" <a href=\"#\" class=\"minus_link\" title=\"-\" onclick=\"return del_contact(this);\"></a></p>").insertBefore(select_field);
	$("<input type=\"hidden\" class=\"hidden-id contact-selected\" name=\""+ fieldname +"\" value=\""+ val +"\"/>").insertBefore(select_field);
	
	select_field.next('a.plus_link').remove();
	select_field.remove();
}

/**
 * This duplicates a form-segment and removes double options from form-items.
 *
 * @param node the node to duplicate
 */
function duplicate_form_segment(segment) {
	// Get original
	contact_form = $(segment).parents('.contact-segment').eq(0);
	contact_form_extra = contact_form.next('.contact-segment-extra').eq(0);
	
	last_extra = $('.contact-segment-extra').eq($('.contact-segment-extra').size()-1);
	
	// duplicate
	new_part = contact_form.clone();
	new_extra = contact_form_extra.clone();
	new_part.insertAfter(last_extra);
	new_extra.insertAfter(new_part);
	
	// set defaults and remove used username in the dropdown
	$('.extra-phone', new_extra).val(own_strings.activity_form_contact_phone);
	$('.extra-email', new_extra).val(own_strings.activity_form_contact_email);
	
	var used_members = [];
	$('.basic-contact').each(function () {
		val = $(':selected', this).val();
		if (val != "") {
			used_members.push(parseInt(val, 10));
		}
	});
	
	$('.basic-contact option', new_part).each(function () {
		if (in_array(parseInt($(this).attr('value'), 10), used_members)) {
			$(this).remove();
		}
	});
}

function in_array(needle, haystack) {
	for (var i=0;i<haystack.length;i++) {
		if (haystack[i] == needle) {
			return true;
		}
	}
	
	return false;
}

/**
 * Adds a link field
 *
 * @param source the parent element
 */
function add_link_field(source) {
	ctr = $('.form-links');
	blocks = ctr.find('.field_set');
	last_block = blocks.eq(blocks.size()-1);
	new_block = last_block.clone().insertAfter(last_block);

	new_block.find('input').eq(0).attr('value', '');

	return false;
}

/**
 * Clears an input field if the current value is the "default" value.
 *
 * @param element triggering element
 * @return void
 */
function clearme(element)
{
	var elval = $(element).val();
	if ($(element).hasClass('extra-phone') && elval == own_strings.activity_form_contact_phone) {
		$(element).val('');
	}
	else if ($(element).hasClass('extra-phone') && elval == vac_own_strings.vacancy_form_contact_phone) {
		$(element).val('');
	}
	else if ($(element).hasClass('extra-email') && elval == own_strings.activity_form_contact_email) {
		$(element).val('');
	}
	else if ($(element).hasClass('extra-email') && elval == vac_own_strings.vacancy_form_contact_email) {
		$(element).val('');
	}
}

/**
 * locks the manager field and adds a new selectbox.
 *
 * @param source triggering element
 * @return false if everything went ok (to stop propagation)
 */
function add_manager(source) {
	if (is_valid_manager(source)) {
		list_manager(source);
		remove_manager_from_select(source);
	}
	
	return false;
}

function list_manager(source) {
	select = $(source).prev('select').eq(0);
	option = $(':selected', select);
	
	name = option.text();
	id = option.attr('value');
	
	text = "<p class=\"manager\">"+ name +" <a href=\"#\" class=\"minus_link\" title=\"-\" onclick=\"return del_manager(this);\"></a>";
	text += "<input type=\"hidden\" name=\"activity_form_edit_manager[]\" class=\"manager-selected\" value=\""+ id +"\"/>";
	text += "</p>"

	$(text).insertBefore(select);
}

function remove_manager_from_select(source) {
	$(source).prev('select').eq(0).find(':selected').remove();
}

/**
 * Deletes the manager from the fields and puts it back in the selectbox
 */
function del_manager(source) {
	// Removes parent p-tag and adds name/id to the selectbox
	dat = $(source).parents('p.manager').eq(0);
	
	id = dat.find('input').val();
	name = dat.text();
	
	$('.basic-manager').append($("<option value=\""+ id +"\">"+ name +"</option>"));
	
	dat.remove();
	return false;
}

/** 
 * Verifies if selected manager in the selectbox is actually a manager
 */
function is_valid_manager(source) {
	retval = false;
	if ($(source).prev('select').eq(0).val() != "") {
		retval = true;
	}
	
	return retval;
}

/**
 * Enables and disables the "to" date field
 *
 * @param source element triggering the event
 */
function daterange_change(source) {
	range = $('.date-range:checked').attr('value');
	if (range == "single") {
		$('#datetime_end').attr("disabled", "disabled");
		$('div.datepicker_field_end_container').css("display","none");
		$('span.from_date').addClass('hidden');
		//$('input#datetime_end').val($('input#datetime_start').val());
	}
	else {
		$('#datetime_end').removeAttr('disabled');
		$('div.datepicker_field_end_container').css("display","block");
		$('span.from_date').removeClass('hidden');
	}
	
	update_num_days();
}

/**
 * Enables and disables the time-range fields.
 *
 * @param source element triggering the event
 */
function timerange_change(source) {
	range = $('.time-range-radio:checked').attr('value');
	if (range != "same") {
		$('.time-range').attr("disabled", "disabled");
	}
	else {
		$('.time-range').removeAttr('disabled');
	}
	
	if (range == "shifts") {
		$('#activity_form_available_reservations_number').attr("disabled", "disabled");
		$('#activity_form_available_reservations_friends').attr("disabled", "disabled");
		$('#activity_form_available_reservations_friends').removeAttr('checked');
		$('#activity_form_available_reservations_number').val("0");
		$('p.reservations_number_extra_text').removeClass("hidden");
	}
	else {
		$('#activity_form_available_reservations_number').removeAttr('disabled');
		$('#activity_form_available_reservations_friends').removeAttr('disabled');
		$('p.reservations_number_extra_text').addClass("hidden");
	}
	
	// toggle shift forms
	toggleShiftFormsVisibility();
}

/**
 * Enables or disables the publish-date field
 */
function publish_change() {
	range = $('.publish-radio:checked').attr('value');
	
	if (range == 'postpone') {
		$('#publish-date').removeAttr('disabled');
	}
	else {
		$('#publish-date').attr('disabled', 'disabled');
	}
}

/**
 * Enables or disables the reaction-date field
 */
function reaction_change() {
	range = $('.reaction-radio:checked').attr('value');
	
	if (range == 'date') {
		$('#reaction-date').removeAttr('disabled');
	}
	else {
		$('#reaction-date').attr('disabled', 'disabled');
	}
}

/** @{ messages */
/**
 * Returns the base for other functions based on the triggering element
 *
 * @param source the triggering element
 * @return string
 */
function getBase(source) {
	if (source.name.match(/^activity_/)) {
		base = "activity_";
	}
	else {
		base = "vacancy_";
	}
	
	return base;
}

/**
 * replies to selected messages
 *
 * @param source Element triggering the event
 */
function messagesReply(source)
{
	base = getBase(source);
	if (base == 'activity_') {
		ajaxurl = 'pg/activity/ajax/';
	}
	else {
		ajaxurl = 'pg/vacancy/ajax/';
	}

	recps = new Array();
	$('#'+ base +'message_inbox_table_container input.message-checkbox:checked').each(function () {
		message_guid = parseInt($(this).attr('id').match(/_([0-9]+)/)[1], 10);
		recps.push(message_guid);
	});

	$('#recipient-list .recipient-line').remove();

	// Load user-guids, connect them to message-guids and make sure add/remove functionality gets this.
	// We require message-guids later during sending to provide the sender with subjects.
	$.getJSON(own_url + "pg/activity/ajax/get_message_owners/" + array_serialize(recps),
		function (data) {
			var excludes = new Array();
			for (i=0;i<data.length;i++) {
				this_item = data[i];
				
				id = this_item[0];
				name = this_item[1];
				
				excludes.push(id);

				dat = '<dd class="recipient-line"><input type="hidden" name="'+ base +'reply_message_receiver[]" value="'+ id +'"/>'+ name +'<a href="#" onclick="return remRecipient(this);" class="remove" title="verwijderen"><span class="hidden">x</span></a></dd>';
				
				$('#recipient-list').append(dat);
			}

			$('#'+ base +'reply_message_receiver option').each(function() {
				if (this.value != '') {
					$(this).remove();
				}
			})

			// Create list for selectbox
			$.getJSON(own_url + 'pg/activity/ajax/get_senders/'+ cur_entity_guid,
				function (subdata) {
					for (i=0;i<subdata.length;i++) {
						this_item = subdata[i];

						// Skip if item in exclude-array
						if (in_array(this_item[0], excludes)) {
							continue;
						}

						// Add item to selectbox
						dat = '<option value="'+ this_item[0] +'">'+ this_item[1] +'</option>';
						$('#'+ base +'reply_message_receiver').append(dat);
					}
				}
			);
		}
	);

	// Hide and show relevant fields
	$('#message-compose-new').hide();
	$('#message-compose-reply').show();
	$('input[name='+ base +'new_message_subject]').hide();
	$('.subject-label').hide();

	// Fill recipient-hidden with guids
	$('#'+ base +'message_new_message_overlay .message-guids').val(array_serialize(recps));

	emptyNewMessageForm();

	// Display form
	showOverlay(base +'message_new_message_overlay');
}

/**
 * replies to selected applicants
 *
 * @param source Element triggering the event
 */
function messagesApplicants(source)
{
	base = getBase(source);
	
	if (base == 'activity_') {
		ajaxurl = 'pg/activity/ajax/';
	}
	else {
		ajaxurl = 'pg/vacancy/ajax/';
	}

	recps = new Array();
	$('.applicants input.message-checkbox:checked').each(function () {
		message_guid = parseInt($(this).attr('id').match(/_([0-9]+)/)[1], 10);
		recps.push(message_guid);
	});
	
	$('#recipient-list .recipient-line').remove();

	// Load user-guids, connect them to message-guids and make sure add/remove functionality gets this.
	// We require message-guids later during sending to provide the sender with subjects.
	$.getJSON(own_url + "pg/activity/ajax/get_message_owners/" + array_serialize(recps),
		function (data) {
			var excludes = new Array();
			for (i=0;i<data.length;i++) {
				this_item = data[i];
				
				id = this_item[0];
				name = this_item[1];

				excludes.push(id);

				dat = '<dd class="recipient-line"><input type="hidden" name="'+ base +'reply_message_receiver[]" value="'+ id +'"/>'+ name +'<a href="#" onclick="return remRecipient(this);" class="remove" title="verwijderen"><span class="hidden">x</span></a></dd>';
				
				$('#recipient-list').append(dat);
			}

			$('#'+ base +'reply_message_receiver option').each(function() {
				if (this.value != '') {
					$(this).remove();
				}
			})

			// Create list for selectbox
			$.getJSON(own_url + 'pg/activity/ajax/get_senders/'+ cur_entity_guid,
				function (subdata) {
					for (i=0;i<subdata.length;i++) {
						this_item = subdata[i];

						// Skip if item in exclude-array
						if (in_array(this_item[0], excludes)) {
							continue;
						}
						// Add item to selectbox
						dat = '<option value="'+ this_item[0] +'">'+ this_item[1] +'</option>';
						$('#'+ base +'reply_message_receiver').append(dat);
					}
				}
			);//*/
		}
	);

	// Hide and show relevant fields
	$('#message-compose-new').hide();
	$('#message-compose-reply').show();
	$('input[name='+ base +'new_message_subject]').hide();
	$('.subject-label').hide();

	// Fill recipient-hidden with guids
	$('#'+ base +'message_new_message_overlay .message-guids').val(array_serialize(recps));

	emptyNewMessageForm();

	// Display form
	showOverlay(base +'message_new_message_overlay');
}

/**
 * Adds recipient
 */
function addRecipient(source) {
	name = getBase(source) + 'reply_message_receiver';

	sel = $(source).prev('select').eq(0);
	
	cur = $('option:selected', sel);
	
	dat = '<dd class="recipient-line"><input type="hidden" name="'+ name +'[]" value="'+ cur.val() +'"/>'+ cur.html() +'<a href="#" onclick="return remRecipient(this);" class="remove" title="verwijderen"><span class="hidden">x</span></a></dd>';

	$('#recipient-list').append(dat);
	
	cur.remove();
}

/**
 * Adds recipient
 */
function addRecipientInvite(source) {
	name = getBase(source) + 'reply_message_receiver';

	sel = $(source).prev('select').eq(0);
	
	cur = $('option:selected', sel);
	
	dat = '<dd class="recipient-line"><input type="hidden" name="'+ name +'[]" value="'+ cur.val() +'"/>'+ cur.html() +'<a href="#" onclick="return remRecipient(this);" class="remove" title="verwijderen"><span class="hidden">x</span></a></dd>';

	$('#recipient-list-applicants').append(dat);
	
	cur.remove();
}

/**
 * Removes recipient
 */
function remRecipient(source) {
	dd = $(source).parents('dd');
	
	el_id = '#' + getBase(source) + 'reply_message_receiver';
	
	$(source).remove();
	
	name = dd.text();
	id = $('input', dd).eq(0).val();
	
	dd.remove();
	
	dat = '<option value="'+ id +'">'+ name +'</option>';
	if (source.name.match(/^activity_/)) {
		$(el_id).append(dat);
	}
	else {
		$(el_id).append(dat);
	}
}

/**
 * archives selected messages
 *
 * @param source Element triggering the event
 */
function messagesArchive(source) {

	base = getBase(source);
	if (base == "activity_") {
		tableid = "activity_message_inbox-table";
	}
	else {
		tableid = "vacancy_message_inbox_table";
	}

	messages = new Array();
	$('#'+ tableid +' .message-checkbox:checked').each(function () {
		messages.push(parseInt($(this).attr('name').match(/_([0-9]+)$/)[1], 10));
	});
	
	console.debug(messages);

	// Disable button
	$(source).attr('disabled', 'disabled');

	// Archive the messages
	$.ajax({
		async: false,
		url: own_url + "action/activity/archive",
		type: 'POST',
		data: { messages: array_serialize(messages) }
	});
	
	// Reload inbox and archive segments
	if (base == "activity_") {
		ajaxurl = "pg/activity/ajax/";
	}
	else {
		ajaxurl = "pg/vacancy/ajax/";
	}
	$('#'+ base +'message_inbox_form_container').load(own_url + ajaxurl +'list_inbox/' + cur_entity_guid);
	$('#'+ base +'message_inbox-archived-messages').load(own_url + ajaxurl + 'list_archive/' + cur_entity_guid);
	
	// Enable button
	$(source).removeAttr('disabled');
	location.reload(true);
}

function messageCompose(source)
{
	if (source.name.match(/activity_/)) {
		showOverlay('activity_message_new_message_overlay');
	}
	else {
		showOverlay('vacancy_message_new_message_overlay');
	}
}

function messageReply(source)
{
	base = getBase(source);

	// Load message
	sender_guid = $(source).nextAll('input[name=sender_guid]').val();
	message_guid = $(source).nextAll('input[name=message_guid]').val();
	
	var message = {};
	
	// Load reply screen with AJAX
	$.getJSON(own_url + 'pg/activity/ajax/reply_message/'+ message_guid,
		function (data) {
			// Fill data
			$('input[name='+ base +'new_message_subject]').val(data.subject);
			tinyMCE.get(base +'new_message_text').execCommand('mceSetContent',false, data.content);

			$('#message-compose-new').hide();
			$('#message-compose-reply').show();

			// list possible recipients
			sender_name = "";
			for (i=0;i<data.applicants.length;i++) {
				if (data.applicants[i].guid == data.sender) {
					sender_name = data.applicants[i].name;
					continue;
				}
				dat = "<option value=\""+ data.applicants[i].guid +"\">"+ data.applicants[i].name +"</option>";
				$('#'+ base +'reply_message_receiver').append(dat);
			}
			
			// Add original sender.
			dat = '<dd class="recipient-line"><input type="hidden" name="'+ base +'reply_message_receiver[]" value="'+ data.sender +'"/>'+ sender_name +'<a href="#" onclick="return remRecipient(this);" class="remove" title="verwijderen"><span class="hidden">x</span></a></dd>';
			
			$('#recipient-list').append(dat);

			// ReplaceWith doesn't work! We extract HTML and replace it.
			showOverlay(base +'message_new_message_overlay');
		}
	);
	
	// Close view-message screen
	closeOverlay(source);
	
	// Done!
	return false;
}

function sentView(id, activity)
{
	if (activity) {
		subId = '#activity_message_view_overlay';
		act = true;
	}
	else {
		subId = '#vacancy_message_view_overlay';
		act = false;
	}

	// Load message
	$.getJSON(own_url + "pg/activity/ajax/get_sent_message/" + id,
		function (data) {
			if (data == 'err') {
				alert("helaas is het niet gelukt het bericht te laden");
				// Display an error?
				return false;
			}
			
			$(subId +' .subject').html(data.subject);
			$(subId +' .message-contents').html(data.content);
			$(subId +' .message-date').html(data.timeCreated);
			if (data.timeCreated != data.timeUpdated) {
				$(subId +' .message-change-date').show();
				$(subId +' .message-change-date-label').show();
				$(subId +' .message-date-updated').html(data.timeUpdated);
			}
			else {
				$(subId +' .message-change-date').hide();
				$(subId +' .message-change-date-label').hide();
			}
			
			$(subId +' .sender-guid').val(parseInt(data.senderGuid, 10));
			
			if (act) {
				showOverlay('activity_message_view_overlay');
			}
			else {
				showOverlay('vacancy_message_view_overlay');
			}
		}
	);
	
	return false;
}

function messageView(id, activity)
{
	if (activity) {
		subId = '#activity_message_view_overlay';
		act = true;
	}
	else {
		subId = '#vacancy_message_view_overlay';
		act = false;
	}

	// Load message
	$.getJSON(own_url + "pg/activity/ajax/get_message/" + id,
		function (data) {
			if (data == 'err') {
				alert("helaas is het niet gelukt het bericht te laden");
				// Display an error?
				return false;
			}
			
			$(subId +' .subject').html(data.subject);
			$(subId +' .message-contents').html(data.content);
			$(subId +' .message-date').html(data.timeCreated);
			if (data.timeCreated != data.timeUpdated) {
				$(subId +' .message-change-date').show();
				$(subId +' .message-change-date-label').show();
				$(subId +' .message-date-updated').html(data.timeUpdated);
			}
			else {
				$(subId +' .message-change-date').hide();
				$(subId +' .message-change-date-label').hide();
			}
			
			$(subId +' .sender-guid').val(parseInt(data.senderGuid, 10));
			$(subId +' .message-guid').val(parseInt(id, 10));
			
			if (act) {
				showOverlay('activity_message_view_overlay');
			}
			else {
				showOverlay('vacancy_message_view_overlay');
			}
			
			$("tr#message_row_"+id).removeClass("unread");
		}
	);
	
	return false;
}

/**
 * serializes an one dimensional array
 *
 * @param array in
 * @return string serialized data
 */
function array_serialize(input)
{
	var out = "";
	var total = 0;
	for (var key in input)
	{
		++ total;
		out = out + "s:" +
			String(key).length + ":\"" + String(key) + "\";s:" +
			String(input[key]).length + ":\"" + String(input[key]) + "\";";
	}
	out = "a:" + total + ":{" + out + "}";
	return out;
}

/**
 * Sends the message with settings from popup
 *
 * @param source the triggering element
 */
function sendMessage(source)
{
	$(source).parents('form').get(0).submit();
}

/**
 * Checks or unchecks all checkboxes in the parent-table of the triggering element.
 * It will uncheck when _all_ checkboxes have been checked.
 */
function checkAll(source) {
	if ($(source).attr('checked')) {
		$(source).parents('table').eq(0).find('.message-checkbox').attr('checked', 'checked');
	}
	else {
		$(source).parents('table').eq(0).find('.message-checkbox').removeAttr('checked');
	}
}

/** @} */

/** @{ */
function closeOverlay(source)
{
	$(source).parents('.overlay_box').eq(0).addClass('hidden');
	
	return false;
}

function showOverlay(elementId)
{
	if (elementId == "activity_edit_user_data") {
		$('#'+elementId).css('top', 'auto');
		$('#'+elementId).css('bottom', 200);
	}
	
	$('#'+elementId).removeClass('hidden');
}

function emptyNewMessageForm()
{
}

/** @} */

/**
 * serializes the contact info form and put it in the hidden contact_info field of the application form
 *
 * @param source the triggering element
 */
function saveContactInfo(source)
{
	var str = $("form#activity_edit_user_data_form").serialize();
	$("input#contact_info_string").val(str);
	
	$("td#td_confact_info_name").html($("input#user_name").val() + " " + $("input#user_prefix").val() + " " + $("input#user_surname").val());
	$("td#td_confact_info_address").html($("input#user_streetname").val() + " " + $("input#user_streetnumber").val() + " " + $("input#user_streetnumber_suffix").val() + "<br/> " + $("input#user_postcode_number").val() + " " + $("input#user_place").val() + "<br/> " + $("input#user_country").val());
	$("td#td_confact_info_email").html('<a href="mailto:' + $("input#user_email").val() + '">' + $("input#user_email").val() + '</a>');
	$("td#td_confact_info_phone").html($("input#user_phone").val());
	$("td#td_confact_info_mobile_phone").html($("input#user_mobile_phone").val());
	
	if ($("input#user_change_profile:checked").val() == "Change profile") {
		//alert("Ja");
		$.post(own_url + "pg/activity/ajax/save_contact_info", 
			{ 
				user_name: $("input#user_name").val(), 
				user_prefix: $("input#user_prefix").val(),
				user_surname: $("input#user_surname").val(),
				user_streetname: $("input#user_streetname").val(),
				user_streetnumber: $("input#user_streetnumber").val(),
				user_streetnumber_suffix: $("input#user_streetnumber_suffix").val(),
				user_postcode: $("input#user_postcode_number").val(),
				user_place: $("input#user_place").val(),
				user_country: $("input#user_country").val(),
				user_email: $("input#user_email").val(),
				user_phone: $("input#user_phone").val(),
				user_mobile_phone: $("input#user_mobile_phone").val()

			},
			function(data){
				//alert("Opgeslagen");
		});
	}
	
	closeOverlay(source);
}


function submitActivityManageApplicationForm(input,action)
{
	form = $(input).parent().parent();
	
	// Hier moet nog een check of er wel iets geselecteerd is.
	var n = $("#" + form.attr('id') + " input:checked").length;
	if (!n) {
		alert ('Niets geselecteerd!');
		return false;
	}
	
	if (action == 'reserve') {
		$(form).attr("action",own_url + "action/activity/reserve_application");
		
		doen = confirm('Weet je zeker dat je de geselecteerde aanmeldingen op de reservelijst wilt plaatsen?');
		if (doen) {
			$(form).submit();
		}
	}
	if (action == 'delete') {
		$(form).attr("action",own_url + "action/activity/delete_application");
		
		doen = confirm('Weet je zeker dat je de geselecteerde aanmeldingen wilt verwijderen?');
		if (doen) {
			$(form).submit();
		}
	}
	if (action == 'invite') {
		$(form).attr("action",own_url + "action/activity/invite_application");
		
		doen = confirm('Weet je zeker dat je de geselecteerde Doeners wilt uitnodigen?');
		if (doen) {
			$(form).submit();
		}
	}
	else {
		return false;
	}
}

/** @{ shifts */
/**
 * Displays the default shift forms when selecting the shifts radio button
 */
function toggleShiftFormsVisibility()
{
	radio_btn = document.getElementById("activity_form_edit_time_span_03");
	if (radio_btn.checked) {
		$("div#form_section_2").removeClass('hidden');
		$("div#activity_form_mandatory_shifts").removeClass('hidden');
	} 
	else {
		
		$("div#form_section_2").addClass('hidden');
		$("div#activity_form_mandatory_shifts").addClass('hidden');
	}
}

/**
 * Builds the shift type form
 */
function add_shift_type_form()
{
	d = new Date();
	newId = 'new_' + d.getTime();
	
	startdate = $("#datetime_start").val();
	enddate = $("#datetime_end").val();

	if (enddate == "") {
		enddate = startdate;
	}

	num_shifts = $("select#activity_form_create_shiftgroup_day_" + newId + " option:selected").text();
	
	$("p#add_shift_type_link").before('<div id="activity_form_create_shiftgroup_' + newId +'" class="field_group" style="border-top: 1px dotted #B8B8B8;"><p>Laden...</p><p id="remove_shifts_link_' + newId + '" class="left_align"><a href="#" onclick="remove_shifts(\'' + newId + '\'); return false;">Verwijder deze shift</a></p></div>');
	$("p#add_shift_type_link").before('<div id="activity_form_shifts_table" class="activity_form_shifts_table_' + newId + '"></div>');

	$.get(own_url + "pg/activity/ajax/get_shift_type_form/"  + newId + "/" + startdate + "/" + enddate + "/" + num_shifts + "/1",
		function(data){
			$("div#activity_form_create_shiftgroup_" + newId).html(data);
		}
	);
	return false;
}

/**
 * Builds the shifts form for a shift_type
 */
function build_shifts_form(form_id, activity_id)
{
	/* TODO: Bestaande shifts eerst netjes weggooien, ook te reserveringen op deze shifts. Of, shifts opnieuw opbouwen wanneer er al aanmeldingen zijn niet meer mogelijk. */
	
	if (activity_id > 0) {
		do_build = confirm('Zeker weten dat je het schema opnieuw wilt maken? De huidige shifts en de bijbehorende aanmeldingen gaan verloren!')
	}
	else {
		do_build = 1;
	}
	
	if (do_build) {
		$("div.activity_form_shifts_table_" + form_id).html("<p>laden...</p>");
		sameDay = $("input[name='activity_form_create_shiftgroup_schedule_"+form_id+"']:checked").val();
		
		startdate = $("#datetime_start").val();
		enddate = $("#datetime_end").val();
		
		if (enddate == "") {
			enddate = startdate;
		}
		
		num_shifts = $("select#activity_form_create_shiftgroup_day_" + form_id + " option:selected").text();
		
		numShiftsString = '';
		if (sameDay == 'false') {
			$("div#shift_scheme_"+form_id+" select[name^=activity_form_create_shiftgroup_day_]").each(
				function() {
					//alert('Val: ' + $(this).val() );
					if (numShiftsString == '') {
						numShiftsString = numShiftsString + $(this).val();
					}
					else { 
						numShiftsString = numShiftsString + ',' + $(this).val();
					}
				}
			);
			numShiftsString = '?shifts_per_day=' + numShiftsString;
		}
		
		$.get(own_url + "pg/activity/ajax/build_shifts/" + form_id + "/" + startdate + "/" + enddate + "/" + num_shifts + "/1"+numShiftsString,
			function(data){
				$("div.activity_form_shifts_table_" + form_id).html(data+'<p id="remove_shifts_link_' + form_id + '" class="left_align"><a href="#" onclick="remove_shifts(\'' + form_id + '\'); return false;">Verwijder deze shift</a></p>');
			}
		);
	}
}

/**
 * Gets the shifts form for a shift_type
 */
function get_shifts_form(form_id)
{
	$("div.activity_form_shifts_table_" + form_id).html("<p>laden...</p>");
	
	startdate = $("#datetime_start").val();
	enddate = $("#datetime_end").val();
	
	if (enddate == "") {
		enddate = startdate;
	} 
	
	num_shifts = $("select#activity_form_create_shiftgroup_day_" + form_id + " option:selected").text();
		
	$.get(own_url + "pg/activity/ajax/build_shifts/" + form_id + "/" + startdate + "/" + enddate + "/" + num_shifts + "/1/false",
		function(data){
			$("div.activity_form_shifts_table_" + form_id).html(data + '<p id="remove_shifts_link_' + form_id + '" class="left_align"><a href="#" onclick="remove_shifts(\'' + form_id + '\'); return false;">Verwijder deze shift</a></p>');
			updateTotalPeople(form_id);
		}
	);
}

/**
 * Remove shifts from the form
 */
function remove_shifts(shift_type_id)
{
	$("div.activity_form_shifts_table_" + shift_type_id).remove();
	$("div#activity_form_create_shiftgroup_" + shift_type_id).remove();
}

/**
 * Change the time of the shifts
 */
function change_shifttimes(shift_type,old_timestamp,when,col)
{
	stamp = new Date();
	stamp.setTime(old_timestamp * 1000);

	old_hours = stamp.getHours();
	old_minutes = stamp.getMinutes();
	if (old_minutes == '0') {
		old_minutes = '00'
	}

	time1 = old_hours + ':' + old_minutes;
	time2 = prompt("Nieuwe tijd (uu:mm): ",time1);

	if (!time2) {
		return;
	}
	
	time = time2.split(':')
	newHour = time[0];
	newMinute = time[1];

	newDate = stamp;
	newDate.setHours(newHour);
	newDate.setMinutes(newMinute);
	newDate.setSeconds(0);

	newStamp = newDate.getTime() / 1000;

	fieldName = "shift_" + when + "time_" + shift_type + "_" + col;

	// Update the date for every shift
	$("input[id^='" + fieldName + "']").each(function () {
		thisOldTimestamp = $(this).val();
		thisOldDate = new Date();
		thisOldDate.setTime(thisOldTimestamp * 1000);
		
		thisNewDate = thisOldDate;
		thisNewDate.setHours(newHour);
		thisNewDate.setMinutes(newMinute);
		thisNewDate.setSeconds(0);
		
		thisNewTimestamp = thisNewDate.getTime() / 1000;
		
		$(this).val(thisNewTimestamp);
	});
	
	$("a#" + when + "time_" + shift_type + "_" + col).html(time2);
}

/**
 *
 */
function switch_shift_table (table_id)
{
	$("a[id^='switchlink_']").removeClass("selected");
	$("table[id^='shifts_table_']").removeClass("active");
	$("table[id^='shifts_table_']").addClass("inactive");
	
	$("a[id='switchlink_" + table_id + "']").addClass("selected");
	$("table[id='shifts_table_" + table_id + "']").removeClass("inactive");
	$("table[id='shifts_table_" + table_id + "']").addClass("active");
}

/**
 *
 */
function click_shift(shift_id) {
	do_click = 1;
	selectedManA = 0;
	selectedManB = 0;
	
	shiftsRowId = $("a#shift_"+shift_id).parent().parent().attr("id");
	shiftsRowNumber = shiftsRowId.split("_");
	shiftsRowNumber = shiftsRowNumber[2];
	
	// Check if there is already an shift selected on this day
	$("tr[id$='_"+shiftsRowNumber+"'] > td > a.selected").each(
		function () {
			do_click = 0;
		}
	);
	
	num_shifts = 0;
	selectedShiftsString = $("input#selected_shifts").val();
	if (selectedShiftsString == "") {
		num_shifts = 0;
	}
	else {
		selectedShiftsArray = selectedShiftsString.split(",");
		num_shifts = selectedShiftsArray.length;
	}
	
	inArray = 0;
	atPosition = 0;
	if (num_shifts > 0) {
		for (i=0;i<=num_shifts;i++) {
			if (selectedShiftsArray[i] == shift_id) {
				inArray = 1;
				atPosition = i;
			}
		}
	}
	
	if (inArray == 1) {
		$("a#shift_"+shift_id).removeClass('selected');
	}
	else {
		if (num_shifts == glNumShifts) {
			alert("Je zit aan het maximaal aantal shifts dat je mag draaien.");
			return false;
		}
		if (do_click == 0) {
			alert("Je mag maar 1 shift per dag selecteren.");
			return false;
		}
		$("a#shift_"+shift_id).addClass('selected');
	}
	
	shiftsTable = $("a#shift_"+shift_id).parent().parent().parent().parent().attr("id");
	newShiftsString = "";
	$("div#activity_shifts_table > table > tbody > tr > td > a.selected").each(
		function () {
			if (newShiftsString != "") {
				newShiftsString = newShiftsString + ",";
			}
			shifId = $(this).attr("id").split("_");
			newShiftsString = newShiftsString + shifId[1];
			
			if ($(this).hasClass("a-shift")) {
				selectedManA = selectedManA + 1;
			}
			if ($(this).hasClass("b-shift")) {
				selectedManB = selectedManB + 1;
			}
			if ($(this).hasClass("ab-shift")) {
				selectedManA = selectedManA + 1;
				selectedManB = selectedManB + 1;
			}
		}
	);
	
	if ($("span#mandatory_a")) {
		$("span#mandatory_a").html(selectedManA);
	}
	if ($("span#mandatory_b")) {
		$("span#mandatory_b").html(selectedManB);
	}
	
	$("input#selected_shifts").val(newShiftsString);
	
	selectedShiftsArray = newShiftsString.split(",");
	totalShifts = selectedShiftsArray.length;
	if (newShiftsString == "") {
		totalShifts = 0;	
	}
	$("span#total_shifts").html(totalShifts);
	
	if (totalShifts == glNumShifts) {
		$("span#total_shifts").removeClass("red");
		$("span#total_shifts").addClass("green");
	}
	else {
		$("span#total_shifts").removeClass("green");
		$("span#total_shifts").addClass("red");
	}
	
	// Gewone verplichte shiftstellers bijwerken
	shiftsTableAr = shiftsTable.split("_");
	shiftTypeId = shiftsTableAr[2];
	selectedShiftsString = "";
	$("table#"+shiftsTable+" > tbody > tr > td > a.selected").each(
		function () {
			if (selectedShiftsString != "") {
				selectedShiftsString = selectedShiftsString + ",";
			}
			shifId = $(this).attr("id").split("_");
			selectedShiftsString = selectedShiftsString + shifId[1];
		}
	);
	selectedShiftsArray = selectedShiftsString.split(",");
	numSelectedShifts = selectedShiftsArray.length;
	if (selectedShiftsString == "") {
		numSelectedShifts = 0;
	}
	
	numNeededShifts = $("span#shift_needed_total_"+shiftTypeId).html();
	
	$("span#shift_total_"+shiftTypeId).html(numSelectedShifts);
	shiftsNeeded = parseInt(parseInt(numNeededShifts) - parseInt(numSelectedShifts));
	if (shiftsNeeded < 0) {
		shiftsNeeded = 0;
	}
	$("span#shift_needed_"+shiftTypeId).html(shiftsNeeded);
	
	if (parseInt(numSelectedShifts) > 0) {
		$("p#mandetory_info_"+shiftTypeId).removeClass("hidden");
	}
	else {
		$("p#mandetory_info_"+shiftTypeId).addClass("hidden");
	}
	
	if (shiftsNeeded == 0) {
		$("span#shift_needed_"+shiftTypeId).removeClass("red");
		$("span#shift_needed_"+shiftTypeId).addClass("green");
		$("span#shift_title_mandetory_"+shiftTypeId).removeClass("red");
		$("span#shift_title_mandetory_"+shiftTypeId).addClass("green");
	}
	else {
		
		$("span#shift_needed_"+shiftTypeId).removeClass("green");
		$("span#shift_needed_"+shiftTypeId).addClass("red");
		$("span#shift_title_mandetory_"+shiftTypeId).removeClass("green");
		$("span#shift_title_mandetory_"+shiftTypeId).addClass("red");
	}
	
	//alert("test: "+shiftTypeId+ " geselecteerd: "+ numSelectedShifts + " nodig: " +shiftsNeeded+ " nodig totaal: " + numNeededShifts);	
	return false;
}

/**
 *
 */
function init_shifts_form() {
	selectedManA = 0;
	selectedManB = 0;

	selectedShiftsString = $("input#selected_shifts").val();
	if (selectedShiftsString == "") {
		num_shifts = 0;
	}
	else {
		selectedShiftsArray = selectedShiftsString.split(",");
		num_shifts = selectedShiftsArray.length;
	}
	
	$("span#total_shifts").html(num_shifts);
	if (num_shifts >= glNumShifts) {
		$("span#total_shifts").removeClass("red");
		$("span#total_shifts").addClass("green");
	}
	
	for (i=0;i<num_shifts;i++) {
		shift_id = selectedShiftsArray[i];
		$("a#shift_"+shift_id).addClass('selected');
		
		// Enable click_shift() for full shifts if the shift is already selected by the user.
		if ($("a#shift_"+shift_id).html() == "VOL"){
			$("a#shift_"+shift_id).click( 
				function() {
					temp_id = $(this).attr("id");
					temp_id2 = temp_id.split("_");
					shift_id = temp_id2[1];	
					click_shift(shift_id);
					return false;
				}
			);
		}
	}
	
	// Enable click_shift() for full shifts if the shift is already selected by the user.
	for (i=0;i<num_shifts;i++) {
		shift_id = selectedShiftsArray[i];
		if ($("a#shift_"+shift_id).html() == "-1 open" || $("a#shift_"+shift_id).html() == "-2 open" || $("a#shift_"+shift_id).html() == "-3 open") {
			$("a#shift_"+shift_id).click( 
				function() {
					temp_id = $(this).attr("id");
					temp_id2 = temp_id.split("_");
					shift_id = temp_id2[1];	
					click_shift(shift_id);
					return false;
				}
			);
		}	
	}
	
	// Verplichte shifs voor shift_type updaten
	$("div#activity_shifts_table > table").each(
		function () {
			tableId = $(this).attr("id");
			tmpTableId = tableId.split("_");
			shiftTypeId = tmpTableId[2];
			thisNumShifts = $("span#shift_needed_total_"+shiftTypeId).html();//$("span#shift_total_"+shiftTypeId).html();
			thisShiftName = $("a#switchlink_"+shiftTypeId).html();

			selectedShiftsString = "";
			$("table#"+tableId+" > tbody > tr > td > a.selected").each(
				function () {
					if (selectedShiftsString != "") {
						selectedShiftsString = selectedShiftsString + ",";
					}
					shifId = $(this).attr("id").split("_");
					selectedShiftsString = selectedShiftsString + shifId[1];
					
					if ($(this).hasClass("a-shift")) {
						selectedManA = selectedManA + 1;
					}
					if ($(this).hasClass("b-shift")) {
						selectedManB = selectedManB + 1;
					}
					if ($(this).hasClass("ab-shift")) {
						selectedManA = selectedManA + 1;
						selectedManB = selectedManB + 1;
					}
				}
			);
			selectedShiftsArray = selectedShiftsString.split(",");
			numSelectedShifts = selectedShiftsArray.length;
			if (selectedShiftsString == "") {
				numSelectedShifts = 0;
			}
			
			numNeededShifts = $("span#shift_needed_total_"+shiftTypeId).html();
	
			$("span#shift_total_"+shiftTypeId).html(numSelectedShifts);
			shiftsNeeded = parseInt(parseInt(numNeededShifts) - parseInt(numSelectedShifts));
			if (shiftsNeeded < 0) {
				shiftsNeeded = 0;
			}
			$("span#shift_needed_"+shiftTypeId).html(shiftsNeeded);
			
			if (parseInt(numSelectedShifts) > 0) {
				$("p#mandetory_info_"+shiftTypeId).removeClass("hidden");
			}
			else {
				$("p#mandetory_info_"+shiftTypeId).addClass("hidden");
			}
			
			if (shiftsNeeded == 0) {
				$("span#shift_needed_"+shiftTypeId).removeClass("red");
				$("span#shift_needed_"+shiftTypeId).addClass("green");
				$("span#shift_title_mandetory_"+shiftTypeId).removeClass("red");
				$("span#shift_title_mandetory_"+shiftTypeId).addClass("green");
			}
			else {
				
				$("span#shift_needed_"+shiftTypeId).removeClass("green");
				$("span#shift_needed_"+shiftTypeId).addClass("red");
				$("span#shift_title_mandetory_"+shiftTypeId).removeClass("green");
				$("span#shift_title_mandetory_"+shiftTypeId).addClass("red");
			}
			//alert("Data: " + numNeededShifts + " - " + shiftsNeeded + " - " + numSelectedShifts);
		}
	);
	
	showManatoryText = 0;
	if ($("span#mandatory_a")) {
		$("span#mandatory_a").html(selectedManA);
		showManatoryText = 1;
	}
	if ($("span#mandatory_b")) {
		$("span#mandatory_b").html(selectedManB);
		showManatoryText = 1;
	}
	
	if (showManatoryText) {
		$("div#activity_interest").append("<p>Verplichte shifts zijn gemarkeerd met een letter. Van iedere letter moet je minimaal 1 shift doen. 1 shift met beide letters voldoet ook.</p>");
	}
}

/**
 *
 */
function update_num_days() {
	date1 = new Date();
	date2 = new Date();

	date_start = $("input#datetime_start").val();
	date_end = $("input#datetime_end").val();
	
	radio_btn = $("input.date-range:checked").val();

	if (radio_btn == "single") {
		date_end = date_start;
		$("input#datetime_end").val($("input#datetime_start").val());
	}
	
	if (date_start != "") {
		date_start_split = date_start.split("-");
		date_end_split = date_end.split("-");	
		day1 = date_start_split[0];
		month1 = date_start_split[1] -1; //document.getElementById("in_datetime_start_id_month").value -1; // date fix 23-04-2008 @ 9:00
		year1 = date_start_split[2];
		
		day2 = date_end_split[0];
		month2 = date_end_split[1] -1;
		year2 = date_end_split[2];
		
		date1.setFullYear(year1,month1,day1);
		date2.setFullYear(year2,month2,day2);
		
		if (date1 > date2) {
			date2 = date1;
			$("input#datetime_end").val($("input#datetime_start").val());
		}
		
		days = date2 - date1;
		days = (((days / 1000) / 3600) / 24) + 1; 
	}
	else {
		days = 1;
	}

	shift_el = document.getElementById("activity_form_number_compulsory_shifts");
	max_shifts = $("select#activity_form_number_compulsory_shifts option:selected").val();
	
	//if (max_shifts == 0) {
		max_shifts = days;
	//}
	
	for (i=0;i<=days;i=i+1) {
		selectedString = "";
		
		if (i == max_shifts) {
			selectedString = ' selected="selected"';
		}
	
		if (i == 0) {
			shiftElOptions = '<option value="' + i + '"' + selectedString + '>0</option>';
		}
		else {
			optionText = "";
			shiftElOptions = shiftElOptions + '<option value="' + i + '"' + selectedString + '>' + i + optionText + '</option>';
		}
	}
	shift_el.parentNode.innerHTML = 'Iedere deelnemer moet <select name="activity_form_number_compulsory_shifts" size="1" id="activity_form_number_compulsory_shifts" title="activity_form_number_compulsory_shifts" class="small">' + shiftElOptions + '</select> shifts doen tijdens deze activiteit.';
}

/** @} */

function update_activity_searchfilter(getType,getGroup,getPlace) {
	elm_search_type = $("select#activity_search_type");
	elm_search_group = $("select#activity_search_group");
	elm_search_place = $("select#activity_search_place");
	
	time_span = $("input[name='activity_search_radio']:checked").val();
	type = elm_search_type.val();
	group = elm_search_group.val();
	place = elm_search_place.val();
	
	if (type == '') {
		type = "no_val";
	}
	if (group < 1) {
		group = 0;
	}
	if (place == '') {
		place = "no_val";
	}
	if (time_span == '') {
		time_span = "upcomming";
	}
	
	elm_search_type.empty();
	elm_search_type.append('<option>Bezig met laden...</option>');
	elm_search_group.empty();
	elm_search_group.append('<option>Bezig met laden...</option>');
	elm_search_place.empty();
	elm_search_place.append('<option>Bezig met laden...</option>');
	
	$.get(own_url + "/pg/activity/ajax/update_activity_search/"+type+"/"+group+"/"+place+"/"+time_span, 
		function(data){
			topResult = data.split('||||');
			typeOptions = topResult[0].split('//');
			placeOptions = topResult[1].split('//');
			groupOptions = topResult[2].split('//');
			
			elm_search_type.empty();
			elm_search_type.append('<option value="">Soort bijeenkomst</option>');
			for (i=0;i<typeOptions.length;i++) {
				typeSelected = '';
				if (typeOptions[i] == type) {
					typeSelected = ' selected="selected"';
				}
				elm_search_type.append('<option value="'+typeOptions[i]+'"'+typeSelected+'>'+typeOptions[i]+'</option>');
			}
			
			elm_search_group.empty();
			elm_search_group.append('<option value="-1" selected="selected">Organiserende groep</option>');
			for (i=0;i<groupOptions.length;i++) {
				groupValues = groupOptions[i].split("::");
				groupSelected = '';
				if (groupValues[1] == group) {
					groupSelected = ' selected="selected"';
				}
				elm_search_group.append('<option value="'+groupValues[1]+'"'+groupSelected+'>'+groupValues[0]+'</option>');
			}
			
			elm_search_place.empty();
			elm_search_place.append('<option value="">Locatie</option>');
			for (i=0;i<placeOptions.length;i++) {
				placeSelected = '';
				if (placeOptions[i] == place) {
					placeSelected = ' selected="selected"';
				}
				elm_search_place.append('<option value="'+placeOptions[i]+'"'+placeSelected+'>'+placeOptions[i]+'</option>');
			}
		}
	);
}

function update_shifts_per_day_form (shift_type_id, startdate, enddate) {
	startdate = $("input#datetime_start").val();
	enddate = $("input#datetime_end").val();
	sameDay = $("input[name='activity_form_create_shiftgroup_schedule_"+shift_type_id+"']:checked").val();
	$("div#shift_scheme_"+shift_type_id).empty();
	
	$.get(own_url + "/pg/activity/ajax/update_shifts_per_day_form?shift_type_id="+shift_type_id+"&startdate="+startdate+"&enddate="+enddate+"&sameday="+sameDay, 
		function(data){
			$("div#shift_scheme_"+shift_type_id).html(data);
		}
	);
}

function showMandetoryOverlay(elementId,current)
{
	$('#'+elementId).css('top', 'auto');
	$('#'+elementId).css('bottom', 200);
	group = elementId.split('_');
	group = group[2].replace(/\s+$/,'');
	group = group.replace(' ','');
	
	nameString = '';
	
	$('input[name^=shifttype_name]').each(
		function () {
			if (nameString == '') {
				nameString = nameString + $(this).val();
			}
			else { 
				nameString = nameString + ',' + $(this).val();
			}	
		}
	);
	
	returnHtml = "";
	$("div[class^=activity_form_shifts_table_]").each(
		function() {
			
			shiftTypeId = $(this).attr("class");
			shiftTypeIdAr = shiftTypeId.split("_");
			shiftTypeId = shiftTypeIdAr[4];
			if (shiftTypeId == 'new') {
				shiftTypeId = shiftTypeIdAr[4]+"_"+shiftTypeIdAr[5];
			}
			
			returnHtml = returnHtml + "<p><br/><strong>"+$("input#activity_form_create_shiftgroup_shiftname_"+shiftTypeId).val()+"</strong></p>";

			$("div[class=activity_form_shifts_table_"+shiftTypeId+"] > table").each(
				function() {
					//alert(' hier doet iets ' + shiftTypeId);
					tableId = $(this).attr("id");
					returnHtml = returnHtml + '<table style="width: 500px; border: 1px solid #01ADEF;" border="1" cellpadding="3" cellspacing="0"> ';
					// Header hier
					returnHtml = returnHtml + '<tr class="odd header">';

					$("table#"+tableId + " > tbody > tr.header > th").each(
						function() {
							returnHtml = returnHtml + '<th style="border-left: 1px dotted #B8B8B8;" scope="col" class="">'+$(this).html()+'</th>';
						}
					);
					
					returnHtml = returnHtml + '</tr>';
					
					// rest van de tabel hier
					rowClass = "even";
					$("table#"+tableId + " > tbody > tr.row").each(
						function() {
							rowId = $(this).attr("id");
							returnHtml = returnHtml + '<tr class="'+rowClass+'">';
							returnHtml = returnHtml + '<th scope="row" class="column1">'+$("tr#"+rowId+" > th").html()+'</th>';
							
							$("tr#"+rowId+" > td").each(
								function() {
									thisColumn = $(this).attr("class");
									shiftId = $("tr#"+rowId+" > td."+thisColumn+" > input[name^=shift_id]").val();
									
									manVal = 0;
									manVal = $("input#shift_group_"+group+"_"+shiftId).val();
									if (manVal == '1') {
										groupStatus = 'Ja';
									}
									else {
										groupStatus = 'Nee';
									}
								
									returnHtml = returnHtml + '<td style="border-left: 1px dotted #B8B8B8;" class="'+thisColumn+'"><a href="#" id="mandatory_link_'+group+'_'+shiftId+'">'+groupStatus+'</a></td>';
								}
							);
							
							returnHtml = returnHtml + '</tr>';
							
							if (rowClass == 'even') {
								rowClass = 'odd';
							}
							else {
								rowClass = 'even';
							}
						}
					);
					// einde van de rest
					
					returnHtml = returnHtml + '</table>';
				}
			);
		}
	);
	$('#'+elementId+" div").html(returnHtml);
	$('#'+elementId).removeClass('hidden');
	
	$('a[id^=mandatory_link]').click(
		function() {
			linkId = $(this).attr("id");
			allInfo = linkId.split("_");
			group = allInfo[2];
			shiftId = allInfo[3];
			if (shiftId == "new") {
				shiftId = allInfo[3]+"_"+allInfo[4];
			}
			thisLink = $(this);
			addMandetory(thisLink, group, shiftId);
			return false;
		}
	);
}

function sendMailQuestion() {
	if (confirm('Wil je dat alle aanmeldingen een e-mail ontvangen dat deze activiteit is gewijzigd??')) {
		$("input[name=send_mail]").val("yes");
		//return true;
	}
	//return true;
}

function updateTotalPeople(shift_type_id) {
	totalPeople = parseInt(0);

	$("input[class=num_people_"+shift_type_id+"]").each(
		function () {
			totalPeople = parseInt(totalPeople) + parseInt($(this).val());
		}
	);
	
	numShifts = $("select#activity_form_number_compulsory_shifts").val();
	totalPeople = Math.round((totalPeople / parseInt(numShifts))*100) / 100;
	$("span#total_people_"+shift_type_id).html(totalPeople);
}

function check_application() {
	errorString = "";
	num_shifts = 0;
	selectedShiftsString = 0;
	cant_force_application = true;
	available_shifts = 0;
	selectedShiftsString = $("input#selected_shifts").val();
	if (selectedShiftsString) {
		selectedShiftsArray = selectedShiftsString.split(",");
		num_shifts = selectedShiftsArray.length;
	}

	$("table.shift_table > tbody > tr[id^=shiftrow_]").each(
		function() {
			this_id = $(this).attr("id");
			rowAvailable = 0;
			$("tr#"+this_id+" > td > a").each(
				function() {
					// inhoud van a tag controleren
					//alert("ja: "+$(this).html());
					tagContent = $(this).html();
					
					if (tagContent != "VOL") {
						rowAvailable = 1;
					}
				}
			);
			
			if (rowAvailable > 0) {
				available_shifts = available_shifts + 1;
			}
		}
	);
	
	if (glNumShifts > available_shifts) {
		cant_force_application = false;
		//alert("Te doen: " + glNumShifts + " - mogelijk: " + available_shifts);
	}
	
	// Totaal aantal shifts check
	if (glNumShifts > num_shifts) {
		// Checken of het minimaal aantal shifts nog wel kan?
		if (cant_force_application) {
			errorString = errorString + "Je hebt nog niet genoeg shifts geselecteerd.\n";
		}
	}
	
	// Verplichte schifts per schift_type check
	selectedGroupA = 0;
	selectedGroupB = 0;
	$("div#activity_shifts_table > table").each(
		function () {
			tableId = $(this).attr("id");
			tmpTableId = tableId.split("_");
			shiftTypeId = tmpTableId[2];
			thisNumShifts = $("span#shift_needed_total_"+shiftTypeId).html();//$("span#shift_total_"+shiftTypeId).html();
			thisShiftName = $("a#switchlink_"+shiftTypeId).html();

			selectedShiftsString = "";
			$("table#"+tableId+" > tbody > tr > td > a.selected").each(
				function () {
					if (selectedShiftsString != "") {
						selectedShiftsString = selectedShiftsString + ",";
					}
					shifId = $(this).attr("id").split("_");
					selectedShiftsString = selectedShiftsString + shifId[1];
					
					// Verplichte shiftgroup check
					if ($(this).hasClass("a-shift")) {
						selectedGroupA = 1;
					}
					if ($(this).hasClass("b-shift")) {
						selectedGroupB = 1;
					}
					if ($(this).hasClass("ab-shift")) {
						selectedGroupA = 1;
						selectedGroupB = 1;
					}
				}
			);
			selectedShiftsArray = selectedShiftsString.split(",");
			numSelectedShifts = selectedShiftsArray.length;
			if (selectedShiftsString == "") {
				numSelectedShifts = 0;
			}
			
			if (thisNumShifts) {
				if (thisNumShifts > numSelectedShifts) {
					if (numSelectedShifts > 0) {
						if (cant_force_application) {
							errorString = errorString + "Je hebt nog niet genoeg shifts van '"+thisShiftName+"' geselecteerd.\n";
						}
					}
				}
			}
		}
	);
	
	// Verplichte shiftsgroepen check (A/B)
	if (glNeedGroupA == 1) {
		if (selectedGroupA == 0) {
			errorString = errorString + "Je moet een verplichte shift uit groep A selecteren.\n";
		}
	}
	if (glNeedGroupB == 1) {
		if (selectedGroupB == 0) {
			errorString = errorString + "Je moet een verplichte shift uit groep B selecteren.\n";
		}
	}
	
	// Zijn er foutmeldigen?
	if (errorString != "") {
		//alert("Foutmelding: \n\n" + errorString);
		alert(errorString + " ");
		return false;
	}
}

function check_activity_submit() {
	// TODO: Hier al een check op de begin en einddatum?
	
	errorString = "";
	timeRange = $("input[name=activity_form_edit_time_span]:checked").val();
	//alert("time range: "+timeRange);
	//return false;
	
	if (timeRange == "shifts") {
		checkTable = $("table[id^=shift_table_]").attr('id');
		if (checkTable==undefined) {
			errorString = "Er zijn geen shifts aangemaakt!";
		}
	}
	
	// Zijn er foutmeldigen?
	if (errorString != "") {
		alert("Foutmelding: \n\n" + errorString);
		return false;
	}
}

function addMandetory(thisLink, group, shiftId) {
	manVal = $("input#shift_group_"+group+"_"+shiftId).val();
	if ($(thisLink).html() == 'Ja') { // groep uitzetten
		$(thisLink).html('Nee');
	}
	else { // group aanzetten
		$(thisLink).html('Ja');
	}
}

function switch_shift_mandatory(shiftTypeId) {
	checkedStatus = $("input#activity_form_shift_number_minimum_"+shiftTypeId).attr('checked');
	
	if (checkedStatus) {
		$("select#activity_form_edit_shifts_amount_"+shiftTypeId).removeAttr('disabled');
	}
	else {
		$("select#activity_form_edit_shifts_amount_"+shiftTypeId).attr('disabled','disabled');
	}
}

function switch_total_mandatory() {
	checkedStatus = $("input#activity_form_edit_shifts_mandatory").attr('checked');
	if (checkedStatus) {
		$(".mandatory_table_setup").removeClass('hidden');
	}
	else {
		$(".mandatory_table_setup").addClass('hidden');
	}
}

function build_mandatory_table(popup,shift_group) {
	// Huidige tabel leeggooien
	$("tr[id^='man_shift_"+shift_group+"']").remove();
	// Geselecteerde verplichte shifts resetten
	$("input[id^=shift_group_"+shift_group+"_]").val("0");
	
	newHTML = "";
	shiftClass = "odd";
	
	// Geselecteerde shifts zoeken
	$('a[id^=mandatory_link]').each(
		function () {
			if ($(this).html() == 'Ja') {
				if (shiftClass == "odd") {
					shiftClass = "even";
				}
				else {
					shiftClass = "odd";
				}
				
				// shift_id achterhalen
				shiftId = $(this).attr("id");
				shiftId = shiftId.split("_");
				if (shiftId[3] == "new") {
					shiftId = shiftId[3]+"_"+shiftId[4];
				}
				else {
					shiftId = shiftId[3]
				}
				
				$("input#shift_group_"+shift_group+"_"+shiftId).val("1"); // Verplichte shift ook echt instellen
				
				shiftTypeId = $("input[class=shifttype_"+shiftId+"]").val();
				shiftTypeTitle = $("input#activity_form_create_shiftgroup_shiftname_"+shiftTypeId).attr("value");
				
				startDate = new Date();
				endDate = new Date();
				
				startDate.setTime($("input.starttime_"+shiftId).val() * 1000);
				endDate.setTime($("input.endtime_"+shiftId).val() * 1000);
				
				shiftDate = addLeadingZero(startDate.getDate()) + "-"+addLeadingZero(startDate.getMonth()+1)+"-"+startDate.getFullYear();
				shiftStarttime = addLeadingZero(startDate.getHours())+":"+addLeadingZero(startDate.getMinutes());
				shiftEndtime = addLeadingZero(endDate.getHours())+":"+addLeadingZero(endDate.getMinutes());
				
				newHTML = newHTML + '';
				newHTML = newHTML + '<tr id="man_shift_'+shift_group+'_'+shiftId+'" class="'+shiftClass+'">';
				newHTML = newHTML + '<td><strong>'+shiftTypeTitle+' '+shiftDate+',</strong> '+shiftStarttime+' - '+shiftEndtime+'</td>';
				newHTML = newHTML + '<td>&nbsp;</td>';
				newHTML = newHTML + '</tr>';

			}
		}
	);
	
	$("table#activity_form_mandatory_shifts_table_"+shift_group).append(newHTML);
	
	closeOverlay(popup);
	
	$('#mandetory_shifts_'+shift_group+" div").html("<p>Shifts konden niet geladen worden...</p>");
}

function addLeadingZero (input) {
	output = input.toString();
	
	//alert("bla: "+output);
	if (output.length < 2) {
		output = "0"+output;
	}
	return output;
}