function updateSelection(is_checked, type, id, counter_field_id, toggleActionSelect) {
	var url = '';
	if (is_checked) {
		url = '/admin.php/wpPersistenceManager/ajaxAddItemToSelection';
	} else {
		url = '/admin.php/wpPersistenceManager/ajaxRemoveItemFromSelection';
	}
	new Ajax.Request(url+"?type="+type+"&id="+id, {
		onSuccess: function(transport){
			eval(transport.responseText);
			updateSelectedItemCount(type, counter_field_id, toggleActionSelect);
		},
		onFailure: ajaxFail
	});
	return;
}

function isItemSelected(type, id) {
	new Ajax.Request("/admin.php/wpPersistenceManager/ajaxIsItemSelected?type="+type+"&id="+id, {
		onSuccess: function(transport){
			return transport.responseText;
		},
		onFailure: ajaxFail
	});
	return;
}

function cleanSelection(type, counter_field_id) {
	new Ajax.Request("/admin.php/wpPersistenceManager/cleanSelection?type="+type, {
		onSuccess: function(transport){
			updateSelectedItemCount(type, counter_field_id);
			unCheckAll(false, type);
			return transport.responseText;
		},
		onFailure: ajaxFail
	});
	return;
}

function updateSelectedItemCount(type, counter_field_id, toggleActionSelect) {
	if (!type.blank()) {
		new Ajax.Request("/admin.php/wpPersistenceManager/ajaxGetSelectedItemCount?type="+type, {
			onSuccess: function(transport){
				var response = parseInt(transport.responseText);

				var counter_items = $$('.' + counter_field_id);
				for(var i = 0; i < counter_items.length; i++){
					counter_items[i].innerHTML = response;
				}
				initCheckAllCheckbox(type);
			},
			onFailure: ajaxFail
		});
	}
	return;
}

function ajaxFail() {
	alert('Erreur lors du traitement...');
}

function checkAll(is_checked, type) {
	togglekAll(is_checked, type, true);
}

function unCheckAll(is_checked, type) {
	togglekAll(is_checked, type, false);
}

function togglekAll(is_checked, type, checked) {
	var checkboxes = $$('.checkbox-' + type);
	for(var i = 0; i < checkboxes.length; i++){
		checkboxes[i].checked = is_checked;
		updateSelection(checkboxes[i].checked, type, checkboxes[i].value, type + "-count", checked);
	}
}

function initCheckAllCheckbox(type) {
	var number = 0;

	var checkboxes = $$('.checkbox-' + type);
	for(var i = 0; i < checkboxes.length; i++){
		if (checkboxes[i].checked) {
			number++;
		}
	}

	$(type + '_all').checked = (number == checkboxes.length);
}
