function setRmCategories(event) {
/* -------called by pull-down "add/delete" one catItem to "inputRmCategories" box;
	the 'inputRmCategories' box is read by 'addReminderDialog.js' 
*/
	var selectCat = event.label.replace(/[,]/g, "\\,");
	var inputCats = categoriesClean(document.getElementById('inputRmCategories').value);
	
	// check if selected item in input string 
	if (!((',' + inputCats + ',').indexOf(',' + selectCat + ',') > -1) )  { 
		newString =	selectCat + ',' + inputCats;		// *	add item 
	} else {   													// * 	delete Item 
		var inputCatsArray = categoriesArray(inputCats);
		var cCount = inputCatsArray.length; 

		var newString ="";
		for (i = 0; i < cCount; i ++) {
			var curCat = (inputCatsArray[i]);
			if ((selectCat.toLowerCase() != escCommas(curCat.toLowerCase())) && (curCat != "")) {
				newString +=  escCommas(curCat) + ",";
			}
		}
	}
	document.getElementById('inputRmCategories').value = categoriesNoDup(newString);
}

	
function rmSetupCategories() {
/* --------- this adds the current perfs-categories to the pull-down-menu
*/
	var itemTextbox = document.getElementById('inputRmCategories');
	var itemCur = itemTextbox.value;
	
	var curCatArray = categoriesArray(itemCur)
	var cCount = curCatArray.length; 

	/* first we delete all cat-items categories, hold the 'manage-menuitem' */
	
	var mList = document.getElementById('categories-menupopup');
	var count = mList.childNodes.length;
	
	while ( count-- ) {
		var child = mList.childNodes[count];	
		if (child.getAttribute( "value") != 3) {
			mList.removeChild(mList.childNodes[count]);
		}
	}
	var m1 = document.createElement("menuseparator");
	(mList.insertBefore(m1,mList.childNodes[0]));
		
	/* now we read both categories 'user' and 'standard' from prefs */
	// -- first we add the 'standard' cat-items --
	var rmCategoriesStandard = rmReadCategories2prefs();
	var catArray = categoriesArray(rmCategoriesStandard)
	var count2 = catArray.length
	var mCount = count2 +1;  /* rem the pos for 'user' items */
 
	while ( count2 -- ) {
		var m1 = document.createElement("menuitem");
		var newItem =reminderFox_trim(catArray[count2]);
		 // apply parameters
			m1.setAttribute("type" , "checkbox");
			m1.setAttribute("value" , "2");
			m1.setAttribute("oncommand", "setRmCategories(this);");
			m1.setAttribute("label", newItem);
			
			for (var i=0; i<cCount; i++) {
				if (newItem.toLowerCase() == reminderFox_trim(curCatArray[i].toLowerCase())) {
					m1.setAttribute("checked",true);
				}
			}
		// insert the new element into the DOM before node 0
		(mList.insertBefore(m1,mList.childNodes[0]));
	}


	var m1 = document.createElement("menuseparator");
	(mList.insertBefore(m1,mList.childNodes[mCount]));
	
	// -- second we add the 'user' cat-items --
	catArray = getUserCategories(); 
	
	var count2 = catArray.length

	while ( count2 -- ) {
		newItem =reminderFox_trim(catArray[count2]);
		if (newItem != "") {
		var checkCat = false;
		var m1 = document.createElement("menuitem");
		 // apply parameters
			 m1.setAttribute("type" , "checkbox");
			 m1.setAttribute("value" , "1");
			 m1.setAttribute("oncommand", "setRmCategories(this);");
			 m1.setAttribute("label", newItem);
			for (i=0; i<cCount; i++) {
				if (newItem.toLowerCase() == reminderFox_trim(curCatArray[i].toLowerCase())) {
					m1.setAttribute("checked",true);
				}
			}
		// insert the new element into the DOM before node 0
		(mList.insertBefore(m1,mList.childNodes[mCount]));
		}
	}	
}

// go through all reminders and todos and get all referenced categories that are not defined
// in the standard categories
function getUserCategories() {
	var reminders;
	var reminderFoxTodosArrayArg;
	var reminderFoxListWindow = rmFx_getWindow("window:reminderFoxEdit");	 
	// get reminders and todos model from the list window if possible - this allows you to get the latest categories even if not yet saved to 
	// the ics file yet
	 if (reminderFoxListWindow) {
	 	reminders = reminderFoxListWindow.reminderFox_getReminderEvents();
	 	reminderFoxTodosArrayArg =  reminderFoxListWindow.reminderFox_getReminderTodos();
	 }
	 else {
	 	reminders = reminderFox_getReminderEvents();
	 	reminderFoxTodosArrayArg =  reminderFox_getReminderTodos();
	 }
	
	var rmCategoriesStandard = rmReadCategories2prefs();
	var rmCatMainArray = categoriesArray(rmCategoriesStandard)
	var userCategories = new Array();
	for ( var i = 0; i < reminders.length; i++ ) {
		if ( reminders[i].categories != null && reminders[i].categories !=  "" ) {
			var currentReminderCategories = categoriesArray(reminders[i].categories)
			for ( var j = 0; j < currentReminderCategories.length; j++ ) {
				var category = currentReminderCategories[j];
				if (!containedInList(rmCatMainArray, category)) {
					// add unique category to list (but only if not it default categories)
					if (!containedInList( userCategories, category)) {
						userCategories[userCategories.length] = category;
					}
				}
			}
		}
	}
	// now search the todo's as well
	for ( var n in reminderFoxTodosArrayArg ) {
		var reminderTodos = reminderFoxTodosArrayArg[n];
		for (  i = 0; i < reminderTodos.length; i++ ) {
			if ( reminderTodos[i].categories != null && reminderTodos[i].categories !=  "" ) {
				var currentReminderCategories = categoriesArray(reminderTodos[i].categories)
				for ( var j = 0; j < currentReminderCategories.length; j++ ) {	
					var category = currentReminderCategories[j];
					if (!containedInList(rmCatMainArray, category)) {
						// add unique category to list (but only if not it default categories)
						if (!containedInList(userCategories, category)) {
							userCategories[userCategories.length] = category;
						}
					}
				}
			}
		}
	}
	return userCategories.sort();
}

function containedInList( existingList, userCategory ) {
	for (var j=0; j< existingList.length; j++) {
			if (reminderFox_trim(existingList[j].toLowerCase()) == reminderFox_trim(userCategory.toLowerCase())) {
				return true;
			}
		}
		return false;
}


function manageCategories() {
/* -------------------------------------  --- -
*/	
	window.openDialog("chrome://reminderfox/content/categories/manageCategories.xul",
			"reminderFox-manage-categories", "chrome,resizable,modal" );
}



	function categoriesNoDup(catA) {
		var catAA = categoriesArray(catA);
		var catB = ",";
		for (var n=0; n< catAA.length; n ++) {
			if (catB.toLowerCase().indexOf(',' + escCommas(catAA[n].toLowerCase()) + ',') == -1) {
				catB += escCommas(catAA[n]) + ',';
			}
		}
		return categoriesClean(catB);
	}

	function categoriesClean(str) {			// lead-/trailing comma, single comma/spc
		str = str.replace(/(   )/g, " ").replace(/(  )/g, " ");
		str = str.replace(/,,,|,,/g, ",").replace(/ ,/g, ",").replace(/, /g, ",")
			.replace(/[,]+$/, '').replace(/^[,]+/, '')
			.replace(/,,,|,,/g, ","); 
		return str;
	}

	function escCommas(strItem) 		{ return strItem.replace(/[,]/g, "\\,"); }

	function categoriesArray(categoriesString) {
		if (!categoriesString) {
			return [];
    	}
    	// \u001A is the unicode "SUBSTITUTE" character
		function revertCommas(name) { return name.replace(/\u001A/g, ","); }
		return categoriesString.replace(/\\,/g, "\u001A").split(",").map(revertCommas);
	}	

