const reminderFox_nsIFilePicker = Components.interfaces.nsIFilePicker;
const g_reminderFoxBundle = document.getElementById("reminderFox-bundle");  
const filterCalendar    =g_reminderFoxBundle.getString("rf.options.filepicker.filter.calendar");
const filterPrefs    =g_reminderFoxBundle.getString("rf.options.filepicker.filter.prefs");
const filterSound    =g_reminderFoxBundle.getString("rf.options.filepicker.filter.sound");

const extensionCalendar = ".ics"; 
const extensionSound= ".wav";
const extensionPrefs= ".js";  
var reminderFox_mPositionMax;


function reminderFox_loadOptions() {	
	var	showStatus = reminderFox_getPreferenceValue( REMINDER_FOX_SHOW_STATUS_TEXT, REMINDER_FOX_SHOW_STATUS_TEXT_DEFAULT );	
	document.getElementById("reminderFox-statustext").setAttribute("checked", showStatus);
	
	var	openTime = reminderFox_getPreferenceValue( REMINDER_FOX_PREF_ALERTSLIDER_OPEN_TIME, 5 );	
    var openGroup = document.getElementById("reminderFox-group-alert-remain-open");    
    var alertOpenText = document.getElementById("reminderFox-text-alert-open-text");		
	if ( openTime <= 0 ) {
		openGroup.selectedIndex = 1;
		alertOpenText.setAttribute("value", 5);  // default
		
	}
	else {
		openGroup.selectedIndex = 0;
		alertOpenText.setAttribute("value", openTime);
	}
	
	var	statusLength = reminderFox_getPreferenceValue( REMINDER_FOX_STATUS_TEXT_MAX_LENGTH, 250 );	
	document.getElementById("reminderFox-status-length").setAttribute("value", statusLength);
	
	var showInTabs = reminderFox_getPreferenceValue( REMINDER_FOX_ALARMS_SHOW_IN_TABS, true );						
	var reminderFoxShowInTabs = document.getElementById("reminderFox-showInTabs");	
	if ( showInTabs == true || showInTabs == "true") {
		reminderFoxShowInTabs.selectedIndex = 0; 
	}
	else {
		reminderFoxShowInTabs.selectedIndex = 1; 
	}
	
	var	alertHeight = reminderFox_getPreferenceValue( REMINDER_FOX_PREF_ALERTSLIDER_MAX_HEIGHT, 250 );	
	document.getElementById("reminderFox-alertHeight").setAttribute("value", alertHeight);
	
	var use24HourTime = reminderFox_getPreferenceValue( REMINDER_FOX_USE_24_HOUR_TIME, REMINDER_FOX_USE_24_HOUR_TIME_DEFAULT );	
	document.getElementById("reminderFox-use24Hour").setAttribute("checked", use24HourTime);
	
	var enableContextMenus = reminderFox_getPreferenceValue( REMINDER_FOX_ENABLE_CONTEXT_MENUS, true );	
	document.getElementById("reminderFox-enableContextMenu").setAttribute("checked", enableContextMenus);
	
	var highlightToday = reminderFox_getPreferenceValue( REMINDER_FOX_HIGHLIGHT_TODAYS_REMINDERS, REMINDER_FOX_HIGHLIGHT_TODAYS_REMINDERS_DEFAULT );			
	document.getElementById("reminderFox-highlightToday").setAttribute("checked", highlightToday);
		
	var reminderFoxhideCompleted = reminderFox_getPreferenceValue( REMINDER_FOX_HIDE_COMPLETED_ITEMS, false );	
	document.getElementById("reminderFox-hideCompleted").setAttribute("checked", reminderFoxhideCompleted);		
		
	var showRemindersInTooltip = reminderFox_getPreferenceValue( REMINDER_FOX_SHOW_REMINDERS_IN_TOOLTIP, REMINDER_FOX_SHOW_REMINDERS_IN_TOOLTIP_DEFAULT );						
	document.getElementById("reminderFox-showRemindersTooltip").setAttribute("checked", showRemindersInTooltip);

	var showTodosInTooltip =  reminderFox_getPreferenceValue( REMINDER_FOX_SHOW_TODOS_IN_TOOLTIP, REMINDER_FOX_SHOW_TODOS_IN_TOOLTIP_DEFAULT );					
	document.getElementById("reminderFox-showTodosTooltip").setAttribute("checked", showTodosInTooltip);
	
	var upcomingDays = reminderFox_getPreferenceValue( REMINDER_FOX_UPCOMING_REMINDER_DAYS_PREF, REMINDER_FOX_UPCOMING_REMINDER_DAYS_DEFAULT );	
	document.getElementById("remindersUpcomingDays").setAttribute("value", upcomingDays);

	var defaultEditType = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_EDIT, REMINDER_FOX_DEFAULT_EDIT_DEFAULT );
	var defaultEdit = document.getElementById("reminderFox-default-doubleclick");	
	if ( defaultEditType == "todos" ) {
		defaultEdit.selectedIndex = 1; 
	}
	else {
		defaultEdit.selectedIndex = 0; 
	}
	
	
	var defaultCat = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_CATEGORY );
	if ( defaultCat != null && defaultCat.length > 0 ) {
		var rfCat = document.getElementById("reminderFox-cat");	
		rfCat.setAttribute("checked", true );
		document.getElementById("reminderFox-cat-text").setAttribute("value", defaultCat );
		document.getElementById("reminderFox-cat-text").removeAttribute("disabled");
	}
	
	var showInTooltipDefault = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_SHOW_IN_TOOLTIP, true );						
	document.getElementById("reminderFox-showInTooltip").setAttribute("checked", showInTooltipDefault);

	
	var alertType = reminderFox_getPreferenceValue( REMINDER_FOX_ENABLE_ALERT_PREF, REMINDER_FOX_ENABLE_ALERT_PREF_ALL );							
	var showAlert = document.getElementById("reminderFox-showAlert");	
	
	// if the user has set it to no alerts, the option should be disabled
	if ( alertType == REMINDER_FOX_ENABLE_ALERT_PREF_NONE ) {
		showAlert.setAttribute("checked", "false");	    
	}
	else {
		showAlert.setAttribute("checked", "true");	    
		
		if ( alertType == REMINDER_FOX_ENABLE_ALERT_PREF_ALL ) {  
			document.getElementById("reminderFox-alertList").selectedIndex = 0;
		}
		else if ( alertType == REMINDER_FOX_ENABLE_ALERT_PREF_TODAY ) {  
			document.getElementById("reminderFox-alertList").selectedIndex = 1;		
		}
		else if ( alertType == REMINDER_FOX_ENABLE_ALERT_PREF_UPCOMING ) {  
				document.getElementById("reminderFox-alertList").selectedIndex = 2;
		}
	}
	
	var alertTimeout = reminderFox_getPreferenceValue( REMINDER_FOX_ALERT_TIMEOUT_PREF, REMINDER_FOX_ALERT_TIMEOUT_DEFAULT );	 
	document.getElementById("reminderFox-alertTimeout").setAttribute("value", alertTimeout);

	var upcomingLabel = reminderFox_getPreferenceValue( REMINDER_FOX_UPCOMING_REMINDERS_LABEL, REMINDER_FOX_UPCOMING_REMINDERS_LABEL_DEFAULT );	 
	document.getElementById("upcomingLabelOptions").setAttribute("value", upcomingLabel);
	
	var todaysLabel = reminderFox_getPreferenceValue( REMINDER_FOX_TODAYS_REMINDERS_LABEL, REMINDER_FOX_TODAYS_REMINDERS_LABEL_DEFAULT );
	document.getElementById("todaysLabelOptions").setAttribute("value", todaysLabel);	
	
	var dateListLabel = reminderFox_getPreferenceValue( REMINDER_FOX_LIST_DATE_LABEL, REMINDER_FOX_LIST_DATE_LABEL_DEFAULT );	 
	document.getElementById("dayAppearanceLabel").setAttribute("value", dateListLabel);		
	
	var defaultMoreLabel = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_MORE, REMINDER_FOX_DEFAULT_MORE_DEFAULT_VALUE );	 
	document.getElementById("defaultMoreLabel").setAttribute("value", defaultMoreLabel);	
	
	var defaultSnoozeTime = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULTS_ALARM_SNOOZE_TIME, 5 );	 
	document.getElementById("reminderFox-snoozeTime").setAttribute("value", defaultSnoozeTime);
	
	var defaultSnoozeUnits = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULTS_ALARM_SNOOZE_UNITS, 0 );	 
	document.getElementById("reminderFox-snoozealertTimeUnits").selectedIndex = defaultSnoozeUnits;
	
	var defaultSnoozeAction = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULTS_ALARM_SNOOZE_ACTION, 0 );	 
	document.getElementById("reminderFox-alarm-action").selectedIndex = defaultSnoozeAction;
	
	
	var playSound = reminderFox_getPreferenceValue( REMINDER_FOX_ALARM_SOUND, true );	
	var playSoundAlert = reminderFox_getPreferenceValue( REMINDER_FOX_ALERT_SOUND, true );		
	document.getElementById("reminderFox-alarmSound").setAttribute("checked", playSound );	
	document.getElementById("reminderFox-alertSound").setAttribute("checked", playSoundAlert );	
	// check if user has specified a specific file path for sound in their preferences
	var soundFilePath = reminderFox_getPreferenceValue( REMINDER_FOX_ALARM_SOUND_PATH, "");	 
	
	
	var alarmSoundInterval = reminderFox_getPreferenceValue( REMINDER_FOX_ALARM_SOUND_INTERVAL, -1 );	
	if ( alarmSoundInterval > 0 ) {
		document.getElementById("reminderFox-alarmSoundIntervalTime").value = alarmSoundInterval;
		document.getElementById("reminderFox-alarmSoundInterval").setAttribute("checked", true );	
	}
	else {
		document.getElementById("reminderFox-alarmSoundInterval").setAttribute("checked", false );	
		document.getElementById("reminderFox-alarmSoundIntervalTime").value = 5;  // set default val to 5
	}
	
	document.getElementById("reminderFox-alarm-sound-text-position").setAttribute("value", soundFilePath);
    var group = document.getElementById("reminderFox-alarmSound-group-position");    
	if ( soundFilePath == null || soundFilePath == "" ) {
	    group.selectedIndex = 0;
	}
	else {
	 	group.selectedIndex = 1;
	}
	
    var calStartDay = reminderFox_getPreferenceValue( REMINDER_FOX_CALENDAR_START_DAY, REMINDER_FOX_CALENDAR_START_DAY_DEFAULT );	
	document.getElementById("reminderFox-startDay").selectedIndex = calStartDay;
		
	var calSize= reminderFox_getPreferenceValue( REMINDER_FOX_CALENDAR_SIZE, 1 );
	if ( calSize == 1 ) {	
		document.getElementById("calendarSizeMenu").selectedIndex = 1;
	}
	else 	if ( calSize > 1 ) {	
		document.getElementById("calendarSizeMenu").selectedIndex = 2;
	}
	else {
		document.getElementById("calendarSizeMenu").selectedIndex = 0;
	}
	
	
	var showWeekNums= reminderFox_getPreferenceValue( REMINDER_FOX_SHOW_WEEK_NUMS_PREF, 0 );
	if ( showWeekNums == 0 ) {
		document.getElementById("reminderFox-weekNumberList").setAttribute( "disabled", true );
	}
	else {
		document.getElementById("reminderFox-showWeekNumbers").setAttribute("checked", true);	
		document.getElementById("reminderFox-weekNumberList").removeAttribute( "disabled" );
	}
	
	if ( showWeekNums == 2 ) {	
		document.getElementById("reminderFox-weekNumberList").selectedIndex = 1;
	}
	else {
		document.getElementById("reminderFox-weekNumberList").selectedIndex = 0;
	}
	
		
	// check if user has specified a specific file path in their preferences		
//OS_switching -----------		
//    need to look for OStype info to get the path only
//    this should also migrate old prefs to new (including OStype)
	var savefilePath = rmFx_getStoreFile4OS();
//	var savefilePath = reminderFox_getPreferenceValue( REMINDER_FOX_STORE_FILE );	
	
	// if not, then use default location in profile
	if ( savefilePath == null || savefilePath == "" ) {
		document.getElementById("reminderFox-use-default-file-location").setAttribute("checked", true);		
	}
	else {
		document.getElementById("reminderFox-use-default-file-location").setAttribute("checked", false);
	}
	var currentFilePath = reminderFox_getReminderStoreFile().path;

	document.getElementById("reminderFox-file-location").setAttribute("value", currentFilePath);
	reminderFox_fileLocationChanged();


	var networkSync =  reminderFox_getPreferenceValue( REMINDER_FOX_NETWORK_SYNCHRONIZE, REMINDER_FOX_NETWORK_SYNCHRONIZE_DEFAULT );	 		
	document.getElementById("reminderFox-network-sync").setAttribute("checked", networkSync);

	
    var repeatUpcoming = reminderFox_getPreferenceValue( REMINDER_FOX_REPEAT_UPCOMING_OCCURRENCES, -1 );	
    var repeatGroup = document.getElementById("reminderFox-group-repeat-upcoming");    
    var repeatPositionText = document.getElementById("reminderFox-text-repeat-upcoming");		
	if ( repeatUpcoming == -1 ) {
		repeatGroup.selectedIndex = 0;
	}
	else {
		repeatGroup.selectedIndex = 1;
		repeatPositionText.setAttribute("value", repeatUpcoming);
	}
	
	var repeatPrevious = reminderFox_getPreferenceValue( REMINDER_FOX_REPEAT_PREVIOUS_OCCURRENCES, -1);	
    repeatGroup = document.getElementById("reminderFox-group-repeat-previous");    
    repeatPositionText = document.getElementById("reminderFox-text-repeat-previous");
	if ( repeatPrevious == -1 ) {
		repeatGroup.selectedIndex = 0;
	}
	else {
		repeatGroup.selectedIndex = 1;
		repeatPositionText.setAttribute("value", repeatPrevious);
	}
	
	
	document.getElementById("reminderFox-alarmSound").setAttribute("checked", playSound );	
	document.getElementById("reminderFox-alertSound").setAttribute("checked", playSoundAlert );	
	
	// check if user has specified a specific file path for sound in their preferences
	var soundFilePath = reminderFox_getPreferenceValue( REMINDER_FOX_ALARM_SOUND_PATH, "" );	 
	document.getElementById("reminderFox-alarm-sound-text-position").setAttribute("value", soundFilePath);
    var group = document.getElementById("reminderFox-alarmSound-group-position");    
	if ( soundFilePath == null || soundFilePath == "" ) {
	    group.selectedIndex = 0;
	}
	else {
	 	group.selectedIndex = 1;
	}
	
	
	var allDay = document.getElementById("reminderFox-all-day");	
	var allDayDefault =  reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_ALL_DAY, true );	
	if (  allDayDefault ) { 
		allDay.setAttribute( "checked", true );	
	}
	else {
		allDay.setAttribute( "checked", false );	
	}
	
	
	var defaultFilterReminderIndex = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_FILTER_REMINDER, 0 );
	var filterList = document.getElementById("displayType");
	filterList.selectedIndex = defaultFilterReminderIndex;	
	
	var defaultFilterTodoIndex = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_FILTER_TODO, 0 );
	filterList = document.getElementById("displayTypeTodo");
	filterList.selectedIndex = defaultFilterTodoIndex;	
		
	var repeat = document.getElementById("reminderFox-repeat");	
	var repeatList = document.getElementById("reminderFox-repeatList");	
	var defaultRepeat = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_REPEAT, -1 );	
	if ( defaultRepeat < 0 ) {
		repeat.setAttribute( "checked", false );	
	}
	else {
		repeat.setAttribute("checked", true );
		repeatList.selectedIndex = defaultRepeat;
	}			
	
	var showAlert = document.getElementById("reminderFox-alert");	
	var alarmMinutes = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_ALARM_TIME, -1 );	
	if ( alarmMinutes < 0 ) {		
		showAlert.setAttribute( "checked", false );			
	}
	else {
		showAlert.setAttribute( "checked", true );	
		var alertTime = document.getElementById("reminderFox-alertTime");
		alertTime.label = alarmMinutes;
		var timeUnitsList = document.getElementById('reminderFox-alertTimeUnits');			
		var alarmUnitsIndex;
		try {
			alarmUnitsIndex = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_ALARM_UNITS );	 
		} catch(e) {
		}					
		timeUnitsList.selectedIndex = alarmUnitsIndex;
	}
	
	var remindUntilComplete = document.getElementById("remindUntilComplete");	
	var remindUntilCompleteDefault = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_REMIND_UNTIL_COMPLETED, false );
	remindUntilComplete.setAttribute( "checked", remindUntilCompleteDefault );
	
	// load settings of remote synchronization
	var proto = reminderFox_getPreferenceValue( REMINDER_FOX_PROTO, REMINDER_FOX_DEFAULT_PROTO );		
	var protoMenu = document.getElementById("reminderFox-proto");	
	if ( proto == "ftp" ) {
		protoMenu.selectedIndex = 0; 
	} else if ( proto == "http" ) {
		protoMenu.selectedIndex = 1; 
	}
	else {
		protoMenu.selectedIndex = 2; 
	}

	var address = reminderFox_getPreferenceValue( REMINDER_FOX_ADDRESS, 	 "");
	document.getElementById("reminderFox-text-address").setAttribute("value", address);

	var _username = reminderFox_getPreferenceValue( REMINDER_FOX_USERNAME, "" );	
	document.getElementById("reminderFox-text-username").setAttribute("value", _username);
	


	var loginData = {
	   ljURL : proto + "://" + address,
	    username : _username,
	    password : ''
	};

	loginData = reminderFox_getPassword(loginData);
	if (loginData != null) {
		document.getElementById("reminderFox-text-password").setAttribute("value", loginData.password);
	}
	// end network
	
	// todo lists
	var  reminderFox_todoLists_listbox= document.getElementById("reminderFox_todoLists_listbox");
	// clear existing list items
	while (reminderFox_todoLists_listbox.hasChildNodes()) {
		reminderFox_todoLists_listbox.removeChild(reminderFox_todoLists_listbox.firstChild);
 	}
		
	
	var todoListsArray = reminderFox_getAllCustomTodoLists(); 	 	
	for ( var i = 0; i < todoListsArray.length; i++ )  { 	
		var newItem = document.createElement("listitem");
		newItem.setAttribute( "label", todoListsArray[i]);
		newItem.setAttribute( "value",  todoListsArray[i]);			
		reminderFox_todoLists_listbox.appendChild(newItem);
 	}
	

	readDefaultCategories();
	
	reminderFox_populateBars();
	reminderFox_populatePositions();

	reminderFox_alertChanged();
	reminderFox_alertNotificationChanged();
	reminderFox_repeatChanged();
	reminderFox_groupPositionChanged();
	reminderFox_alarmSoundChanged();	
	reminderFox_alarmSoundGroupPositionChanged();	
	reminderFox_fileLocationChanged();
	reminderFox_ValidateSynchronization();
	reminderFox_repeatPreviousChanged();
	reminderFox_alarmTimeOpenChanged();
	reminderFox_repeatUpcomingChanged();
	
}

function reminderFox_updateShowWeekNums() {
	var show = document.getElementById("reminderFox-showWeekNumbers");
	var showVal = show.getAttribute( "checked" );
	if ( showVal == false || showVal == "false") {
		document.getElementById("reminderFox-weekNumberList").setAttribute( "disabled", true );
	}
	else {
		document.getElementById("reminderFox-weekNumberList").removeAttribute( "disabled" );
	}
}


function reminderFox_exportPrefs() {
	reminderFox_saveOptions();  // save current prefs to a file first, so we get all current settings
	
	var NL = "\n";
	var prefString = "#" + g_reminderFoxBundle.getString("rf.options.prefs.file.header") + NL;
	if ( reminderFox_user_prefs == null ) {
		reminderFox_initUserPrefsArray();
	}
	for ( var pref in reminderFox_user_prefs ) {
		
		var prefValue = reminderFox_getPreferenceValue( pref );
		var prefType = reminderFox_user_prefs[pref];
		if ( prefType == REMINDERFOX_PREF_TYPE.CHAR || prefType == REMINDERFOX_PREF_TYPE.COMPLEX ) {
			prefString = prefString + 'pref("' + REMINDER_FOX_PREF + "." + pref + '", "' + prefValue +'");' + NL;
		}
		else {
			prefString = prefString + 'pref("' + REMINDER_FOX_PREF + "." + pref + '", ' + prefValue + ");" + NL;
		}
	}	
	
	var file = reminderFox_filePickerPreferences(0, window);
    if (!file)
      return;	
      

	if ( file.exists() == false ) {
		file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
	}      
	
	reminderFox_writeStringToFile(prefString, file, true);

	// show success message
	var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
	                    .getService(Components.interfaces.nsIPromptService);
	promptService.alert(window,g_reminderFoxBundle.getString("rf.options.export.success.title"),	  
			g_reminderFoxBundle.getString("rf.options.export.prefs.success.description") );
}

function reminderFox_defaultCatChanged() {
	var showAlert = document.getElementById("reminderFox-cat");	
	var alertVal =  showAlert.getAttribute("checked" );
	if ( alertVal == false || alertVal == "false") {
			document.getElementById("reminderFox-cat-text").setAttribute("disabled", "true");	
	}
	else {
			document.getElementById("reminderFox-cat-text").removeAttribute("disabled" );		
	}
	
}

function reminderFox_importPrefs() {
	var NL = "\n";
	var prefString = "#" + g_reminderFoxBundle.getString("rf.options.prefs.file.header") + NL;
	if ( reminderFox_user_prefs == null ) {
		reminderFox_initUserPrefsArray();
	}
	
	
	var file = reminderFox_filePickerPreferences(1, window);
	if (!file)
      return;
				
	var input = reminderFox_readInFileContents( file );	
	

	var contentsArray = reminderFox_splitOnAllNewlines(input);

	var prefSet = false;
	for ( var i = 0; i < contentsArray.length; i++ ) {
		var line = contentsArray[i];
		if ( line != null && reminderFox_trim(line).length > 1 ) {			
			//var index = line.indexOf( 'pref("');
			var index = 'pref("'.length;
			var endIndex = line.indexOf( '", ')
			if ( index != -1 ) { 
				var prefName = line.substring( index, endIndex);
				// remove initial reminderfox id
				var rfPrefix = REMINDER_FOX_PREF + ".";
				
				var rfIndex = prefName.indexOf( rfPrefix);							
				if ( rfIndex == 0  ) {
					prefName = prefName.substring( rfPrefix.length );
					var prefVal;
					line = line.substring( endIndex + '", '.length);
					
					var stringIndex = line.indexOf( '"' );
					var isString = stringIndex == 0;
					if ( isString ) {
						index = 1;
						endIndex = line.indexOf( '");');
						prefVal = line.substring( index, endIndex);			
					}
					else {
						index = 0;
						endIndex = line.indexOf( ');');
						prefVal = line.substring( index, endIndex);			
					}
					if ( endIndex != -1 ) { 											
						reminderFox_setPreferenceValue( prefName, prefVal );
						prefSet = true;						
					}
				}
			}
		}
		
	}	
	
	var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
		                    .getService(Components.interfaces.nsIPromptService);
	if ( prefSet ) {
		// only show success msg if actually succeeded...  that is if ANY pref was set.  
		promptService.alert(window,g_reminderFoxBundle.getString("rf.options.export.success.title"),	  
			g_reminderFoxBundle.getString("rf.options.import.prefs.success.description")  );     
			
		// reload imported options so they now show in the options page
		reminderFox_loadOptions();
	}
	else {
		promptService.alert(window,g_reminderFoxBundle.getString("rf.options.import.failure.title"),	  
			g_reminderFoxBundle.getString("rf.options.import.prefs.failure.description")  );     
	}

}




function reminderFox_todoListsRemove() {
	var  reminderFox_todoLists_listbox= document.getElementById("reminderFox_todoLists_listbox");
	var index = reminderFox_todoLists_listbox.selectedIndex;;
	var child = reminderFox_todoLists_listbox.childNodes[index];
	
	// remove all reminders belonging to this list.  Ask for confirmation
	var currentListName = child.getAttribute( "label" );	
	var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                    .getService(Components.interfaces.nsIPromptService);

	var flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
		promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1;     
	var msg = g_reminderFoxBundle.getString("rf.options.customlist.delete.confirmation.text1") +  " " + currentListName + "?" + "  " +
		g_reminderFoxBundle.getString("rf.options.customlist.delete.confirmation.text2"); 
	
	var buttonPressed = promptService.confirmEx(window,g_reminderFoxBundle.getString("rf.options.customlist.delete.button.title"),
	  msg,
	  flags,g_reminderFoxBundle.getString("rf.options.customlist.delete.button.title"), g_reminderFoxBundle.getString("rf.button.cancel"), null, null, {});
	  
	// cancel pressed
	if ( buttonPressed == 1 ) {	
		return;
	}	
	
	// clear subscription if this list had one
	var subscriptions = reminderFox_getSubscriptions();				
	if ( subscriptions[currentListName] != null ) {
		subscriptions[currentListName] = null;
		reminderFox_writeSubscriptions( subscriptions );
	}	

	var reminderFoxTodosArrayArg =  reminderFox_getReminderTodos();
	reminderFoxTodosArrayArg[currentListName] = new Array();		
	reminderFox_writeOutRemindersAndTodos(false);
	
	// remove from list UI
	reminderFox_todoLists_listbox.removeChild(child);
}

function reminderFox_todoListsMoveUp() {
	var  reminderFox_todoLists_listbox= document.getElementById("reminderFox_todoLists_listbox");
	var index = reminderFox_todoLists_listbox.selectedIndex;;
	
	if ( index > 0 ) {
			var child = reminderFox_todoLists_listbox.childNodes[index-1];
			var moved = reminderFox_todoLists_listbox.removeChild(reminderFox_todoLists_listbox.childNodes[index]);			
			reminderFox_todoLists_listbox.insertBefore( moved, child );
			 reminderFox_todoLists_listbox.selectedIndex = index -1;
	}
}

function reminderFox_todoListsMoveDown() {
	var  reminderFox_todoLists_listbox= document.getElementById("reminderFox_todoLists_listbox");
	var index = reminderFox_todoLists_listbox.selectedIndex;;
	
	if ( index ==  reminderFox_todoLists_listbox.childNodes.length - 2 ) {
		var moved = reminderFox_todoLists_listbox.removeChild(reminderFox_todoLists_listbox.childNodes[index]);			
		reminderFox_todoLists_listbox.appendChild(moved);
		 reminderFox_todoLists_listbox.selectedIndex =  reminderFox_todoLists_listbox.childNodes.length - 1;;
		
	}
	else 	if ( index < reminderFox_todoLists_listbox.childNodes.length - 1 ) {
			var child = reminderFox_todoLists_listbox.childNodes[index];
			var moved = reminderFox_todoLists_listbox.removeChild(reminderFox_todoLists_listbox.childNodes[index+1]);			
			reminderFox_todoLists_listbox.insertBefore( moved, child );
					 reminderFox_todoLists_listbox.selectedIndex = index + 1;
	}
}






function reminderFox_fileLocationChanged() {
	var fileLocationChanged = "true";
	try {
		fileLocationChanged = document.getElementById("reminderFox-use-default-file-location").getAttribute("checked" );
	}
	catch(e) {
	}		
	
	if ( fileLocationChanged == false || fileLocationChanged == "false") {
			document.getElementById("reminderFox-file-location").removeAttribute("disabled" );			
			document.getElementById("reminderFox_file_location_browse").removeAttribute("disabled" );						
	}
	else {
			document.getElementById("reminderFox-file-location").setAttribute("disabled", "true");			
			document.getElementById("reminderFox_file_location_browse").setAttribute("disabled", "true");						
	}
}	
	

function reminderFox_updateOptions() {					
	var showStatusText = "true";
	try {
		showStatusText = document.getElementById("reminderFox-statustext").getAttribute("checked" );
	}
	catch(e) {
	}		

	try {
		if ( showStatusText != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_SHOW_STATUS_TEXT, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_SHOW_STATUS_TEXT, true);
		}
	} catch(e) {
	}	
	
	var statusLength = document.getElementById("reminderFox-status-length").value;		
	reminderFox_setPreferenceValue( REMINDER_FOX_STATUS_TEXT_MAX_LENGTH, statusLength);		
	
	var alertHeight = document.getElementById("reminderFox-alertHeight").value;		
	reminderFox_setPreferenceValue( REMINDER_FOX_PREF_ALERTSLIDER_MAX_HEIGHT, alertHeight);		
	
	var use24HourText = "true";
	try {
		use24HourText = document.getElementById("reminderFox-use24Hour").getAttribute("checked" );
	}
	catch(e) {
	}		

	try {
		if ( use24HourText != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_USE_24_HOUR_TIME, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_USE_24_HOUR_TIME, true);
		}
	} catch(e) {
	}	
	
	var enableContextMenus = "true";
	try {
		enableContextMenus = document.getElementById("reminderFox-enableContextMenu").getAttribute("checked" );
	}
	catch(e) {
	}		

	try {
		if ( enableContextMenus != "true" ) {
			reminderFox_setPreferenceValue(REMINDER_FOX_ENABLE_CONTEXT_MENUS, false);
		}
		else {
			reminderFox_setPreferenceValue(REMINDER_FOX_ENABLE_CONTEXT_MENUS, true);
		}
	} catch(e) {
	}	
	
	var highlightToday = "true";
	try {
		highlightToday = document.getElementById("reminderFox-highlightToday").getAttribute("checked" );
	}
	catch(e) {
	}		

	try {
		if ( highlightToday != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_HIGHLIGHT_TODAYS_REMINDERS, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_HIGHLIGHT_TODAYS_REMINDERS, true);
		}
	} catch(e) {
	}	
	
	
	var reminderFoxhideCompleted = "true";
	try {
		reminderFoxhideCompleted = document.getElementById("reminderFox-hideCompleted").getAttribute("checked" );
	}
	catch(e) {
	}		

	try {
		if ( reminderFoxhideCompleted != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_HIDE_COMPLETED_ITEMS, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_HIDE_COMPLETED_ITEMS, true);
		}
	} catch(e) {
	}	
		
		
	var showRemindersInTooltip =	"true";
	try {
		showRemindersInTooltip =	document.getElementById("reminderFox-showRemindersTooltip").getAttribute("checked" );
	}
	catch(e) {
	}		
	try {
		if ( showRemindersInTooltip != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_SHOW_REMINDERS_IN_TOOLTIP, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_SHOW_REMINDERS_IN_TOOLTIP, true);
		}
	} catch(e) {
	}	
	
	// default show in tooltip
	var showDefaultInTooltip =	"true";
	try {
		showDefaultInTooltip =	document.getElementById("reminderFox-showInTooltip").getAttribute("checked" );
	}
	catch(e) {
	}		
	try {
		if ( showDefaultInTooltip != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_DEFAULT_SHOW_IN_TOOLTIP, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_DEFAULT_SHOW_IN_TOOLTIP, true);
		}
	} catch(e) {
	}	
	
	
	
	var networkSync =	"true";;
	try {
		networkSync =	document.getElementById("reminderFox-network-sync").getAttribute("checked" );
	}
	catch(e) {
	}		
	try {
		if ( networkSync != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_NETWORK_SYNCHRONIZE, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_NETWORK_SYNCHRONIZE, true);
		}
	} catch(e) {
	}	
	
	var showTodosInTooltip =	"true";
	try {
		showTodosInTooltip =	document.getElementById("reminderFox-showTodosTooltip").getAttribute("checked" );
	}
	catch(e) {
	}	
	try {
		if ( showTodosInTooltip != "true" ) {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_SHOW_TODOS_IN_TOOLTIP, false);
		}
		else {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_SHOW_TODOS_IN_TOOLTIP, true);
		}
	} catch(e) {
	}	
		
	var upcomingDays =REMINDER_FOX_UPCOMING_REMINDER_DAYS_DEFAULT + "";
	try {
		upcomingDays = document.getElementById("remindersUpcomingDays").value;
	}
	catch(e) {
	}		
	try {
			reminderFox_prefsBranch.setIntPref(REMINDER_FOX_UPCOMING_REMINDER_DAYS_PREF, upcomingDays);
	} catch(e) {
	}		
	
	var defaultSnoozeUnits = 0;
	try {
		defaultSnoozeUnits = document.getElementById("reminderFox-snoozealertTimeUnits").selectedIndex;
	}
	catch(e) {
	}		
	reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULTS_ALARM_SNOOZE_UNITS, defaultSnoozeUnits);
	
	var defaultSnoozeAction = 0;
	try {
		defaultSnoozeAction = document.getElementById("reminderFox-alarm-action").selectedIndex;
	}
	catch(e) {
	}		
	reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULTS_ALARM_SNOOZE_ACTION, defaultSnoozeAction);
	
	var defaultSnoozeTime = 0;
	try {
		defaultSnoozeTime = document.getElementById("reminderFox-snoozeTime").value;
	}
	catch(e) {
	}		
	reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULTS_ALARM_SNOOZE_TIME, defaultSnoozeTime);
	
	
		
	var defaultEditIndex = 0;
	try {
		defaultEditIndex = document.getElementById("reminderFox-default-doubleclick").selectedIndex;
	}
	catch(e) {
	}		
	if ( defaultEditIndex == 1 ) {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_DEFAULT_EDIT, "todos");
	}
 	else {
 			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_DEFAULT_EDIT, "reminders");	
 	}		
	
	var showInTabs = 0;
	try {
		showInTabs = document.getElementById("reminderFox-showInTabs").selectedIndex;
	}
	catch(e) {
	}		
	if ( showInTabs == 0 ) {
		reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_ALARMS_SHOW_IN_TABS, true);
	}
 	else {
 		reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_ALARMS_SHOW_IN_TABS, false);	
 	}
	
	
	var showAlertVal =  true;
	try {
		var showAlert = document.getElementById("reminderFox-showAlert");	
		showAlertVal =  showAlert.getAttribute("checked" );
	}
	catch(e) {
	}	

	var alarmSound = document.getElementById("reminderFox-alarmSound");	
	var alarmSoundVal =  alarmSound.getAttribute("checked" );
	
	var alarmSoundAlert = document.getElementById("reminderFox-alertSound");	
	var alarmSoundAlertVal =  alarmSoundAlert.getAttribute("checked" );	
	
	var alarmEnabled = false;
	var alertEnabled = false;
	if ( alarmSoundVal == false || alarmSoundVal == "false") {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_ALARM_SOUND, false);
	}
	else {
			alarmEnabled = true;
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_ALARM_SOUND, true);
	}
	if ( alarmSoundAlertVal == false || alarmSoundAlertVal == "false") {
			reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_ALERT_SOUND, false);
	}	
	else {
		alertEnabled = true;
		reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_ALERT_SOUND, true);
	}
	
	// update alarm repeat interval
	if ( alarmEnabled ) {
		var alarmInterval = document.getElementById("reminderFox-alarmSoundInterval").getAttribute("checked" );
		if ( alarmInterval == null || alarmInterval == false || alarmInterval == "false") {
			reminderFox_prefsBranch.setIntPref(REMINDER_FOX_ALARM_SOUND_INTERVAL, -1);
		}
		else {
			var interval = document.getElementById("reminderFox-alarmSoundIntervalTime").value;
			reminderFox_prefsBranch.setIntPref(REMINDER_FOX_ALARM_SOUND_INTERVAL,interval);
		}
	}
	else {
		reminderFox_prefsBranch.setIntPref(REMINDER_FOX_ALARM_SOUND_INTERVAL, -1);
	}
	
	if ( alarmEnabled ||  alertEnabled ) {
	    	var group = document.getElementById("reminderFox-alarmSound-group-position");    
		    if ( group.selectedIndex == 0 ) {	
		    	reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ALARM_SOUND_PATH, "");
		    }
		    else {
				var customAlaramFileLocation = document.getElementById("reminderFox-alarm-sound-text-position").value;
				reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ALARM_SOUND_PATH, customAlaramFileLocation);
			}
	}
	

	try {
		reminderFox_prefs.getCharPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_ALARM_SOUND_PATH);
	} catch(e) {
		reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ALARM_SOUND_PATH, REMINDER_FOX_ALARM_SOUND_PATH__DEFAULT);
	}		
	
	var rfCat = document.getElementById("reminderFox-cat");	
	var catChecked =  rfCat.getAttribute("checked" );
	
	if ( catChecked == false || catChecked == "false") {
		reminderFox_setPreferenceValue( REMINDER_FOX_DEFAULT_CATEGORY, "" );
	}
	else {
		var cat = document.getElementById("reminderFox-cat-text").value;		
		reminderFox_setPreferenceValue( REMINDER_FOX_DEFAULT_CATEGORY, cat);		
	}

	var fileLocationChanged = "true";
	try {
		fileLocationChanged = document.getElementById("reminderFox-use-default-file-location").getAttribute("checked" );
	}
	catch(e) {
	}		
	if ( fileLocationChanged == false || fileLocationChanged == "false") {
//gW_OSswitching    mods/adds  to support OS switching		
		rmFx_storeFile4OS(document.getElementById("reminderFox-file-location").value);
	}
	else {
		rmFx_storeFile4OS("");
	}	

	if ( showAlertVal == false  || showAlertVal == "false") {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ENABLE_ALERT_PREF, REMINDER_FOX_ENABLE_ALERT_PREF_NONE);
	}
	else {
		var alertIndex =0;
		try {
			alertIndex = document.getElementById("reminderFox-alertList").selectedIndex;
		}
		catch(e) {
		}		
		try {
			if ( alertIndex == 0 ) {
					reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ENABLE_ALERT_PREF, REMINDER_FOX_ENABLE_ALERT_PREF_ALL);
			}
			if ( alertIndex == 1 ) {
					reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ENABLE_ALERT_PREF, REMINDER_FOX_ENABLE_ALERT_PREF_TODAY);
			}
			if ( alertIndex == 2 ) {
					reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ENABLE_ALERT_PREF, REMINDER_FOX_ENABLE_ALERT_PREF_UPCOMING);
			}	
		}
		catch( e ) {
		}	
	
	}
	
	 var calStartDay; 
	try {
		calStartDay = document.getElementById("reminderFox-startDay").selectedIndex;
	} catch(e) {
		calStartDay = REMINDER_FOX_CALENDAR_START_DAY_DEFAULT;
	}	
	reminderFox_prefsBranch.setIntPref(REMINDER_FOX_CALENDAR_START_DAY, calStartDay);

	 var calSize; 
	try {
		calSize = document.getElementById("calendarSizeMenu").selectedIndex;
	} catch(e) {
		calSize = 1;
	}	
	reminderFox_prefsBranch.setIntPref(REMINDER_FOX_CALENDAR_SIZE, calSize);




	if ( document.getElementById("reminderFox-showWeekNumbers").getAttribute( "checked" ) == false ||  
		document.getElementById("reminderFox-showWeekNumbers").getAttribute( "checked" ) =="false" ) { 
		reminderFox_setPreferenceValue( REMINDER_FOX_SHOW_WEEK_NUMS_PREF, 0  );
	}
	else {
		var selectedIndex = document.getElementById("reminderFox-weekNumberList").selectedIndex;
		if ( selectedIndex == 0 ) {
			reminderFox_setPreferenceValue( REMINDER_FOX_SHOW_WEEK_NUMS_PREF, 1  );
		}
		else {
			reminderFox_setPreferenceValue( REMINDER_FOX_SHOW_WEEK_NUMS_PREF, 2  );
		}
	}

	var oldAlertTimeout;
	try {
		oldAlertTimeout = reminderFox_prefs.getIntPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_ALERT_TIMEOUT_PREF);
	} catch(e) {
	}
	
	var alertTimeout = REMINDER_FOX_ALERT_TIMEOUT_DEFAULT + "";
	try {
		alertTimeout = document.getElementById("reminderFox-alertTimeout").value;
	}
	catch(e) {
	}		
	try {
			reminderFox_prefsBranch.setIntPref(REMINDER_FOX_ALERT_TIMEOUT_PREF, alertTimeout);
	} catch(e) {
	}	

	if ( oldAlertTimeout != alertTimeout ){
		// need to clear the last alert in the case where alert timeout preference was changed 
		try {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_LAST_ALERT, "");	
		} catch(e) {
		}		
	}
	
	var position =-1;
	var positionText;;
	try {
		position = document.getElementById("reminderFox-group-position");
		positionText = document.getElementById("reminderFox-text-position");
	}
	catch(e) {
	}	
	try {
	    if (parseInt(position.selectedItem.value) == -1)
	      reminderFox_prefsBranch.setIntPref(REMINDER_FOX_TOOLBAR_POSITION, -1);
	    else  {    
	        var textPosition = document.getElementById("reminderFox-text-position");
		    if (textPosition.value < 0 || textPosition.value > reminderFox_mPositionMax) {
		      reminderFox_prefsBranch.setIntPref(REMINDER_FOX_TOOLBAR_POSITION, -1);
		     }
		     else {
	    		reminderFox_prefsBranch.setIntPref(REMINDER_FOX_TOOLBAR_POSITION, positionText.value);
	    	}      
	     }
     }
     catch(e) {
     }
	
	var toolbars = REMINDER_FOX_TOOLBAR_DEFAULT;
	try {
		 toolbars = document.getElementById("reminderFox-list-bars");
	}
   catch(e) {
	}	
	try {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_TOOLBAR, toolbars.selectedItem.value);
	}
	catch(e) {
	}	
	

	try {
		var newLabel = document.getElementById("upcomingLabelOptions").value;
		reminderFox_setUnicodePref(REMINDER_FOX_UPCOMING_REMINDERS_LABEL, newLabel);	
	} catch(e) {
	}	
	
	try {
		var newLabel = document.getElementById("todaysLabelOptions").value;
		reminderFox_setUnicodePref(REMINDER_FOX_TODAYS_REMINDERS_LABEL, newLabel);	
	} catch(e) {
	}	
	
	try {
		var newLabel = document.getElementById("dayAppearanceLabel").value;		
		reminderFox_setUnicodePref( REMINDER_FOX_LIST_DATE_LABEL, newLabel);	
	} catch(e) {
	}	
	
	try {
		var newLabel = document.getElementById("defaultMoreLabel").value;		
		reminderFox_setUnicodePref( REMINDER_FOX_DEFAULT_MORE, newLabel);	
	} catch(e) {
	}	
	
	
	var repeatNumber =-1;
	try {
		repeatNumber = document.getElementById("reminderFox-group-repeat-upcoming");
	}
	catch(e) {
	}	
	try {
	    if (parseInt(repeatNumber.selectedItem.value) == -1)
	      reminderFox_prefsBranch.setIntPref(REMINDER_FOX_REPEAT_UPCOMING_OCCURRENCES, -1);
	    else  {    
	        var repeatPosition = document.getElementById("reminderFox-text-repeat-upcoming");
		    if (repeatPosition.value < 0 ) {
		      reminderFox_prefsBranch.setIntPref(REMINDER_FOX_REPEAT_UPCOMING_OCCURRENCES, -1);
		     }
		     else {
	    		reminderFox_prefsBranch.setIntPref(REMINDER_FOX_REPEAT_UPCOMING_OCCURRENCES, repeatPosition.value);
	    	}      
	     }
     }
     catch(e) {
     }	
	
	repeatNumber =-1;
	try {
		repeatNumber = document.getElementById("reminderFox-group-repeat-previous");
	}
	catch(e) {
	}	
	try {
	    if (parseInt(repeatNumber.selectedItem.value) == -1)
	      reminderFox_prefsBranch.setIntPref(REMINDER_FOX_REPEAT_PREVIOUS_OCCURRENCES, -1);
	    else  {    
	        var repeatPosition = document.getElementById("reminderFox-text-repeat-previous");
		    if (repeatPosition.value < 0 ) {
		      reminderFox_prefsBranch.setIntPref(REMINDER_FOX_REPEAT_PREVIOUS_OCCURRENCES, -1);
		     }
		     else {
	    		reminderFox_prefsBranch.setIntPref(REMINDER_FOX_REPEAT_PREVIOUS_OCCURRENCES, repeatPosition.value);
	    	}      
	     }
     }
     catch(e) {
     }	
	 
	 
	// remain open time
	var remainOpenGroup = null;
	try {
		remainOpenGroup = document.getElementById("reminderFox-group-alert-remain-open");
	}
	catch(e) {
	}	
	try {
	    if (parseInt(remainOpenGroup.selectedItem.value) == 1)
	      reminderFox_prefsBranch.setIntPref(REMINDER_FOX_PREF_ALERTSLIDER_OPEN_TIME, 0);
	    else  {    
	        var repeatPosition = document.getElementById("reminderFox-text-alert-open-text");
	    	reminderFox_prefsBranch.setIntPref(REMINDER_FOX_PREF_ALERTSLIDER_OPEN_TIME, repeatPosition.value);
	     }
     }
     catch(e) {
     }	
	 

	// default filters               		
	var filterList = document.getElementById("displayType");	
	reminderFox_setPreferenceValue( REMINDER_FOX_DEFAULT_FILTER_REMINDER, filterList.selectedIndex  );
		
	filterList = document.getElementById("displayTypeTodo");
	reminderFox_setPreferenceValue( REMINDER_FOX_DEFAULT_FILTER_TODO, filterList.selectedIndex  );

 	var allDay = "true";
	try {
		allDay =  document.getElementById("reminderFox-all-day");	
	}
	catch(e) {
	}		
	if ( allDay.getAttribute( "checked" ) == false ||  allDay.getAttribute( "checked" ) =="false" ) { 
		reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_DEFAULT_ALL_DAY, false);
	}
	else {
		reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_DEFAULT_ALL_DAY, true);
	}
	
	
	var repeat = document.getElementById("reminderFox-repeat");	
	if ( repeat.getAttribute( "checked" ) == false  ||  repeat.getAttribute( "checked" ) == "false" ) {
		 reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULT_REPEAT, -1);			
	}
	else {
		var repeatList = document.getElementById("reminderFox-repeatList");	
		var selectedIndex = repeatList.selectedIndex;
		reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULT_REPEAT, selectedIndex);			
	}
	
	var showAlert = document.getElementById("reminderFox-alert");	
	var alertVal =  showAlert.getAttribute("checked" );
	if ( alertVal == true || alertVal == "true") {
		var alertTime = document.getElementById("reminderFox-alertTime");
		var alertTimeVal = alertTime.label;		
		
		if ( reminderFox_isInteger( alertTimeVal ) ) {				
			 reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULT_ALARM_TIME, alertTimeVal);			
			var timeUnitsList = document.getElementById('reminderFox-alertTimeUnits');			
			var timeSelected = timeUnitsList.selectedIndex;
			 reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULT_ALARM_UNITS, timeSelected);			
		}		
	}		
	else {
		 reminderFox_prefsBranch.setIntPref(REMINDER_FOX_DEFAULT_ALARM_TIME, -1);			
	}

	var remindUntilComplete = document.getElementById("remindUntilComplete");	
	var remindUntilCompleteVal =  remindUntilComplete.getAttribute("checked" );
	if ( remindUntilCompleteVal == true || remindUntilCompleteVal == "true" ) { 	
		 reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_DEFAULT_REMIND_UNTIL_COMPLETED, true);					
	}
	else {
		 reminderFox_prefsBranch.setBoolPref(REMINDER_FOX_DEFAULT_REMIND_UNTIL_COMPLETED, false);							
	}
	
	var  reminderFox_todoLists_listbox= document.getElementById("reminderFox_todoLists_listbox");
	var todoListsArray = new Array();
	for ( var i = 0; i < reminderFox_todoLists_listbox.childNodes.length; i++ ) {
		todoListsArray[i] = reminderFox_todoLists_listbox.childNodes[i].getAttribute( "value" );
	}
	reminderFox_setUnicodePref( REMINDER_FOX_TODO_LISTS, todoListsArray);


	// save of remote file options
	reminderFox_saveNetworkOptions();
	// end network
	
	saveCategoriesGroups();
	
	reminderFox_prefs.savePrefFile(null); 
}

function reminderFox_saveNetworkOptions() {
	var protoIndex = 0;
	var proto = '';
	try {
		protoIndex = document.getElementById("reminderFox-proto").selectedIndex;
	}
	catch(e) {
	}		
	if ( protoIndex == 0 ) {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_PROTO, "ftp");
			proto = "ftp://";
	}else if ( protoIndex == 1 ) {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_PROTO, "http");
			proto = "http://";
	}
 	else {
 			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_PROTO, "https");	
			proto = "https://";
 	}	

	var address = "";
	try {
		address = document.getElementById("reminderFox-text-address").value;
		if ( address != null ) {
			// trim protocol from address (it is specified in the dropdown instead)
			if (address.indexOf( "https://") == 0 ) {
				address = address.substring( "https://".length );
			} 
			else if (address.indexOf( "http://") == 0 ) {
				address = address.substring( "http://".length );
			} 
			else if (address.indexOf( "ftp://") == 0 ) {
				address = address.substring( "ftp://".length );
			} 
		}
	}
	catch(e) {
	}		
	try {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_ADDRESS, address);
	} catch(e) {
	}

	var _username = "";
	try {
		_username = document.getElementById("reminderFox-text-username").value;
	}
	catch(e) {
	}		
	try {
			reminderFox_prefsBranch.setCharPref(REMINDER_FOX_USERNAME, _username);
	} catch(e) {
	}

	var _password = "";
	try {
		_password = document.getElementById("reminderFox-text-password").value;
	}
	catch(e) {
	}		
//	if (_password != '') {  // we *do* want to allow the user to 'null' out their password and clear it
		var loginData = {
		    ljURL : proto + address,
		    username : _username,
		    password : _password,
		    savePassword : true
		};
		reminderFox_savePassword(loginData);
//	}	

}
function reminderFox_saveOptions() {
	if ( document.getElementById("reminderFox-apply").getAttribute("disabled" ) != true &&
		document.getElementById("reminderFox-apply").getAttribute("disabled" ) != "true" ) {
		reminderFox_updateOptions();
		reminderFox_updateWindows();
	}		
	document.getElementById("reminderFox-apply").setAttribute("disabled", true);
}

function reminderFox_saveOptionsAndClose() {
	reminderFox_updateOptions();
	window.close();
	if ( document.getElementById("reminderFox-apply").getAttribute("disabled" ) != true &&
		document.getElementById("reminderFox-apply").getAttribute("disabled" ) != "true" ) {
		reminderFox_updateWindows();
	}
}

function reminderFox_updateWindows() {
	try { 
		// update all of the browsers
		var windowEnumerator =  reminderFox_getWindowEnumerator();
		while (windowEnumerator.hasMoreElements()) {
			var currentWindow = windowEnumerator.getNext();		
			currentWindow.reminderFox_moveBox();

			currentWindow.reminderFox_updateRemindersInWindow();			
			currentWindow.reminderFox_clearRemindersAndTodos();
		}
	}
	catch( e ) {
	}
}


function reminderFox_updateButtons(aEvent)
{
  // don't enable the apply button for button presses
  if (aEvent) { 
    if ((aEvent.originalTarget.localName == "button") ||
        (aEvent.originalTarget.getAttribute("type") == "prof")) {
   	 return;
    }
  }

  document.getElementById("reminderFox-apply").removeAttribute("disabled");
}

function reminderFox_repeatChanged() {
	var repeat = document.getElementById("reminderFox-repeat");	
	var repeatVal =  repeat.getAttribute("checked" );
	if ( repeatVal == false || repeatVal == "false") {
			document.getElementById("reminderFox-repeatList").setAttribute("disabled", "true");	
	}
	else {
			document.getElementById("reminderFox-repeatList").removeAttribute("disabled" );
	}
}	

function reminderFox_alertNotificationChanged() { 
	var showAlert = document.getElementById("reminderFox-alert");	
	var alertVal =  showAlert.getAttribute("checked" );
	if ( alertVal == false || alertVal == "false") {
			document.getElementById("reminderFox-alertTime").setAttribute("disabled", "true");	
			document.getElementById("reminderFox-alertTimeUnits").setAttribute("disabled", "true");	
	}
	else {
			document.getElementById("reminderFox-alertTime").removeAttribute("disabled" );
			document.getElementById("reminderFox-alertTimeUnits").removeAttribute("disabled" );
	}

}

function reminderFox_alertChanged() {
	var showAlert = document.getElementById("reminderFox-showAlert");	
	var showAlertVal =  showAlert.getAttribute("checked" );
	if ( showAlertVal == false || showAlertVal == "false") {
			document.getElementById("reminderFox-alertTimeout").setAttribute("disabled", "true");
			document.getElementById("reminderFox-alertList").setAttribute("disabled", "true");
			document.getElementById("reminderFox-showAlert1").setAttribute("disabled", "true");
			document.getElementById("reminderFox-showAlert2").setAttribute("disabled", "true");			
			document.getElementById("reminderFoxDisplay").setAttribute("disabled", "true");			
	}
	else {
			document.getElementById("reminderFox-alertTimeout").removeAttribute("disabled" );
			document.getElementById("reminderFox-alertList").removeAttribute("disabled" );
			document.getElementById("reminderFox-showAlert1").removeAttribute("disabled" );
			document.getElementById("reminderFox-showAlert2").removeAttribute("disabled" );
			document.getElementById("reminderFoxDisplay").removeAttribute("disabled" );
	}
	
}	

function reminderFox_alarmSoundChanged() {
	var alarmSound = document.getElementById("reminderFox-alarmSound");	
	var alarmSoundVal =  alarmSound.getAttribute("checked" );
	var alertSound = document.getElementById("reminderFox-alertSound");	
	var alertSoundVal =  alertSound.getAttribute("checked" );	

	if ( alarmSoundVal == false || alarmSoundVal == "false") {
		document.getElementById("reminderFox-alarmSoundInterval").setAttribute("disabled", "true");
		document.getElementById("reminderFox-alarmSoundIntervalTime").setAttribute("disabled", "true");
		document.getElementById("reminderFox-alarmIntervalMinutesLabel").setAttribute("disabled", "true");
	}
	else {
		document.getElementById("reminderFox-alarmSoundInterval").removeAttribute("disabled" );
		document.getElementById("reminderFox-alarmSoundIntervalTime").removeAttribute("disabled" );
		document.getElementById("reminderFox-alarmIntervalMinutesLabel").removeAttribute("disabled" );
	}
	reminderFox_alarmIntervalSoundChanged();

	
	if ( (alarmSoundVal == false || alarmSoundVal == "false") && (alertSoundVal == false || alertSoundVal == "false")) {
			document.getElementById("reminderFox-alarmSound-group-position").setAttribute("disabled", "true");
			document.getElementById("sound1").setAttribute("disabled", "true");			
			document.getElementById("sound2").setAttribute("disabled", "true");						
			document.getElementById("reminderFox-alarm-sound-text-position").setAttribute("disabled", "true");
			document.getElementById("reminderFox_sound_browse").setAttribute("disabled", "true");
	}
	else {
			document.getElementById("reminderFox-alarmSound-group-position").removeAttribute("disabled" );
			document.getElementById("sound1").removeAttribute("disabled" );			
			document.getElementById("sound2").removeAttribute("disabled" );						
			document.getElementById("reminderFox-alarm-sound-text-position").removeAttribute("disabled" );
			document.getElementById("reminderFox_sound_browse").removeAttribute("disabled" );
			reminderFox_alarmSoundGroupPositionChanged();			
	}
}	

function reminderFox_alarmIntervalSoundChanged() {
	var alarmInterval = document.getElementById("reminderFox-alarmSoundInterval").getAttribute("checked" );
	var alarmSoundVal = document.getElementById("reminderFox-alarmSound").getAttribute( "checked" );
	
	if ( alarmInterval == null || alarmInterval == false || alarmInterval == "false" || alarmSoundVal == false || alarmSoundVal == "false") {
		document.getElementById("reminderFox-alarmSoundIntervalTime").setAttribute("disabled", "true");
		document.getElementById("reminderFox-alarmIntervalMinutesLabel").setAttribute("disabled", "true");
	}
	else {
		document.getElementById("reminderFox-alarmSoundIntervalTime").removeAttribute("disabled" );
		document.getElementById("reminderFox-alarmIntervalMinutesLabel").removeAttribute("disabled" );
	}
}


function reminderFox_groupPositionChanged() {
    var text = document.getElementById("reminderFox-text-position");
    var textValid = document.getElementById("reminderFox-text-position-valid");
    var group = document.getElementById("reminderFox-group-position");    
    
    if ( group.selectedIndex == 0 ) {
    	text.setAttribute("disabled", "true");
    	textValid.setAttribute("disabled", "true");    
    }
    else {
    	text.removeAttribute("disabled" );
    	textValid.removeAttribute("disabled" );
    }
}	

function reminderFox_alarmTimeOpenChanged() {
    var text = document.getElementById("reminderFox-text-alert-open-text");
    var group = document.getElementById("reminderFox-group-alert-remain-open");    
    
    if ( group.selectedIndex == 1 ) {
    	text.setAttribute("disabled", "true");
    }
    else {
    	text.removeAttribute("disabled" );
    }
}

function reminderFox_repeatPreviousChanged() {
    var text = document.getElementById("reminderFox-text-repeat-previous");
    var group = document.getElementById("reminderFox-group-repeat-previous");    
    
    if ( group.selectedIndex == 0 ) {
    	text.setAttribute("disabled", "true");
    }
    else {
    	text.removeAttribute("disabled" );
    }
}	

function reminderFox_repeatUpcomingChanged() {
    var text = document.getElementById("reminderFox-text-repeat-upcoming");
    var group = document.getElementById("reminderFox-group-repeat-upcoming");    
    
    if ( group.selectedIndex == 0 ) {
    	text.setAttribute("disabled", "true");
    }
    else {
    	text.removeAttribute("disabled" );
    }
}	




function reminderFox_alarmSoundGroupPositionChanged() {
    var text = document.getElementById("reminderFox-alarm-sound-text-position");
    var group = document.getElementById("reminderFox-alarmSound-group-position");    
 	  var button = document.getElementById("reminderFox_sound_browse"); 
    
    if ( group.selectedIndex == 0 ) {
    	text.setAttribute("disabled", "true");
    	button.setAttribute("disabled", "true");
    }
    else {
		var alarmSound = document.getElementById("reminderFox-alarmSound");	
		var alarmSoundVal =  alarmSound.getAttribute("checked" );
		var alertSound = document.getElementById("reminderFox-alertSound");	
		var alertSoundVal =  alertSound.getAttribute("checked" );	
		if ( (alarmSoundVal == false || alarmSoundVal == "false") && (alertSoundVal == false || alertSoundVal == "false")) {    
		    text.setAttribute("disabled", "true");
    		button.setAttribute("disabled", "true");    
		}
		else {
	    	text.removeAttribute("disabled" );
	    	button.removeAttribute("disabled" );    	
	    }
    }
}	

function reminderFox_exportReminders() { 
	var i;

	var reminderFoxEvents = reminderFox_getReminderEvents();
	var reminderFoxTodosArrayArg = reminderFox_getReminderTodos();  //  ALL todos	
	var outputStr = reminderFox_constructReminderOutput(reminderFoxEvents, reminderFoxTodosArrayArg, true);

    //get file
    var file = reminderFox_filePickerExport(0, window);
    if (!file)
      return;	
      
	if ( file.exists() == false ) {
		file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
	}      
	
	reminderFox_writeStringToFile(outputStr, file, true);

	// show success message
	var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
	                    .getService(Components.interfaces.nsIPromptService);
	promptService.alert(window,g_reminderFoxBundle.getString("rf.options.export.success.title"),	  g_reminderFoxBundle.getString("rf.options.export.success.description") );
}	

function reminderFox_importReminders() {
    var overWrite = false;
    var flags;
	var msg;
	var buttonPressed;
	var remindersArray;
	var i;
	var todo;
	var reminder;
     
	var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
	                    .getService(Components.interfaces.nsIPromptService);

	flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
  	 	promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 + 
   		promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_2;
	msg =  g_reminderFoxBundle.getString("rf.options.import.overwriteoradd.description.1") +"\n" +
		g_reminderFoxBundle.getString("rf.options.import.overwriteoradd.description.2") + "\n" +
		g_reminderFoxBundle.getString("rf.options.import.overwriteoradd.description.3");
	buttonPressed = promptService.confirmEx(window,g_reminderFoxBundle.getString("rf.options.import.overwriteoradd.title"),
	  msg,
	  flags, g_reminderFoxBundle.getString("rf.button.add"), g_reminderFoxBundle.getString("rf.button.cancel"), g_reminderFoxBundle.getString("rf.options.import.overwritebutton.title"), null, {});		  
	  

	// cancel pressed
	if (  buttonPressed == 1 ) {
		return ;
	}
	// overwrite pressed
	if ( buttonPressed == 2 ) {	
		// make sure they REAAAAALY want to overwrite
		flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
   			promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1;     
		msg = g_reminderFoxBundle.getString("rf.options.import.overwrite.description");
		buttonPressed = promptService.confirmEx(window,g_reminderFoxBundle.getString("rf.options.import.overwrite.title"),
		  msg,
		  flags,g_reminderFoxBundle.getString("rf.options.import.overwritebutton.title"), g_reminderFoxBundle.getString("rf.button.cancel"), null, null, {});		  
		  
		// cancel pressed
		if ( buttonPressed == 1 ) {	
			return;
		}	
		overWrite = true;
    }     
        
    //get file
    var file =reminderFox_filePickerImport(1, window);
    if (!file)
      return;
				
	var reminderEvents = new Array();
	var reminderTodos = new Array();
	var ignoreExtraInfoIfImportingAdditionalEvents = !overWrite;
	reminderFox_readInRemindersAndTodosICSFromFile(reminderEvents, reminderTodos, file, ignoreExtraInfoIfImportingAdditionalEvents);
		
	// check if we've successfully imported any reminders or todo events		
	var importedSuccess = reminderEvents.length != 0;
	var numTodos = 0;
	for ( var n in reminderTodos ) {
		var importedTodos = reminderTodos[n];
		if ( importedTodos.length > 0 ) {
			importedSuccess = true;
			numTodos += importedTodos.length;
			//break;
		}
	}

	if ( importedSuccess ) { 	
		//gW_ImportwCategories     2011-01-29		<<<---		
		var params = { mode: 'CANCEL', 
			categories:    "importICS", 
			numEvents:     reminderEvents.length /*numEvents*/, 
			numTodos:      numTodos,
			info: "## "  + "import" };
		     
		window.openDialog("chrome://reminderfox/content/mail/rmFxImportWithCategory.xul",
		       "rmFx_ReminderImportwCategory", "chrome,resizable,modal", params);        
		// mode :  CANCEL or OK 
		if (params.mode == 'OK'){ // add the categories to events and todos
		    for ( var i = 0; i < reminderEvents.length; i++ ) {
		        reminder = rmFxUtil.addCategory4Import (reminderEvents[i], params.categories);
		    }     
		    for ( var list in reminderTodos ) {
		        var cList = reminderTodos[list];
		        for (var next in cList) {
		            rmFxUtil.addCategory4Import (cList[next], params.categories);
		        }
		    }
		} 
		//gW_ImportwCategories     2011-01-29   --->>>
		
		var rvEvent = null;
		var rvTodo = null;
		if ( overWrite ) {			
			reminderFoxEvents = reminderEvents;
			reminderFoxTodosArray = reminderTodos;
			
			rvEvent =  {importNo:reminderFoxEvents.length , existNo:0};
			rvTodo = {importNo:numTodos , existNo:0};
		}
		else { 
			// merge
			var existingEvents = reminderFox_getReminderEvents();
			var existingTodos = reminderFox_getReminderTodos();  //  ALL  todos
			rvEvent = reminderFox_mergeEvents(existingEvents, reminderEvents  );
			rvTodo = reminderFox_mergeTodos( existingTodos, reminderTodos );
		
			reminderFoxEvents = existingEvents;
			reminderFoxTodosArray = existingTodos;		
		}
			
		reminderFox_importRemindersUpdateAll(false, null );
		
		var xEvents= g_reminderFoxBundle.getString("rf.html.heading.reminders");
		var xToDos = g_reminderFoxBundle.getString("rf.html.heading.todos");
		var xImported  = g_reminderFoxBundle.getString("rf.reminders.imported");    //"imported";
		var xExists  = g_reminderFoxBundle.getString("rf.reminders.exists");      //"already exists";
		
		
		promptService.alert(window,g_reminderFoxBundle.getString("rf.options.export.success.title"),	  
			g_reminderFoxBundle.getString("rf.options.import.success.description")
			+ "\n\n"  +	xEvents + " : " + rvEvent.importNo + " " + xImported + ",  " 
	     + rvEvent.existNo + " " + xExists +"."  
	     + "\n" + xToDos + " : " + rvTodo.importNo  + " " + xImported + ",  " 
	     + rvTodo.existNo + " " + xExists + "." );

	}
	else {
			promptService.alert(window,g_reminderFoxBundle.getString("rf.options.import.failure.title"),	  
			g_reminderFoxBundle.getString("rf.options.import.prefs.failure.description")  );     
	}     
}	

function downloadReminders() {
	reminderFox_saveNetworkOptions();
	var options = { forceDownload: true };
	window.openDialog('chrome://reminderFox/content/network/download.xul', 'reminderFox-download', 'modal, centerscreen', options);
}

function uploadReminders() { 
	reminderFox_saveNetworkOptions();
	window.openDialog('chrome://reminderFox/content/network/upload.xul', 'reminderFox-upload', 'modal,centerscreen');
}





// split a string at newlines:   \n (Mac, *nix) or \r\n  (windows)
function reminderFox_splitOnAllNewlines(input) {
	// just use common newline to read in lines - check for strings that end in \r (to handle windows \r\n)
	var newline = "\n";
	var returnLine = "\r";
	
	var remindersArray = input.split(newline);	
	for ( var index = 0; index < remindersArray.length; index++ ) {
		var readIn = remindersArray[index];	
		if (readIn.length > 0 &&  readIn.lastIndexOf(returnLine) == readIn.length -1 ) {
			readIn = readIn.substring(0, readIn.length -1 );
			remindersArray[index] = readIn;
		}
	}	
	return remindersArray;
}

function reminderFox_pickSoundFile() {
    //get file
    var file =reminderFox_filePickerImportSound(window);
    if (!file)
      return;
   	var soundFilePath = file.path; 
   	document.getElementById("reminderFox-alarm-sound-text-position").setAttribute("value", soundFilePath);
}

function reminderFox_pickFileLocationFile() {
    //get file
    var file =reminderFox_fileLocationPicker( window);
    if (!file)
      return;
   	var fileLocation = file.path; 
   	document.getElementById("reminderFox-file-location").setAttribute("value", fileLocation);
}



function reminderFox_filePickerImport(aOpen, aWindow) {
    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(reminderFox_nsIFilePicker);  
    //picker.appendFilters( reminderFox_nsIFilePicker.filterText | reminderFox_nsIFilePicker.filterAll );
    picker.appendFilters( reminderFox_nsIFilePicker.filterAll );
    picker.appendFilter( filterCalendar, "*" + extensionCalendar );   
    picker.filterIndex=1;
   	picker.defaultExtension = "ics";
    switch (aOpen) {
      case 0:
        picker.init(aWindow, g_reminderFoxBundle.getString("rf.options.export.filepicker.title"), reminderFox_nsIFilePicker.modeSave);
        break;
      case 1:
        picker.init(aWindow,g_reminderFoxBundle.getString("rf.options.import.filepicker.title"), reminderFox_nsIFilePicker.modeOpen);
        break;
    };
    
    // get the file and its contents
    var res = picker.show();
    if (res == reminderFox_nsIFilePicker.returnCancel)
      return null;
    else
      return picker.file;
}	



function reminderFox_fileLocationPicker( aWindow) {
    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(reminderFox_nsIFilePicker);  
    picker.appendFilters( reminderFox_nsIFilePicker.filterAll );
    picker.appendFilter( filterCalendar, "*" + extensionCalendar );   
    picker.filterIndex=1
   	picker.defaultExtension = "ics";
    picker.init(aWindow, g_reminderFoxBundle.getString("rf.options.filelocation.filepicker.title"), reminderFox_nsIFilePicker.modeOpen);
    
    // get the file and its contents
    var res = picker.show();
    if (res == reminderFox_nsIFilePicker.returnCancel)
      return null;
    else
      return picker.file;
}	


function reminderFox_filePickerImportSound(aWindow) {
    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(reminderFox_nsIFilePicker);  
    picker.appendFilters(  reminderFox_nsIFilePicker.filterAll );
    picker.appendFilter( filterSound, "*" + extensionSound );   
    picker.filterIndex=1;
   	picker.defaultExtension = "wav";
    picker.init(aWindow, g_reminderFoxBundle.getString("rf.options.sound.filepicker.title"), reminderFox_nsIFilePicker.modeOpen);

    // get the file and its contents
    var res = picker.show();
    if (res == reminderFox_nsIFilePicker.returnCancel)
      return null;
    else
      return picker.file;
}	

function reminderFox_filePickerImportPreferences(aWindow) {
    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(reminderFox_nsIFilePicker);  
    picker.appendFilters(  reminderFox_nsIFilePicker.filterAll );
    picker.appendFilter( filterSound, "*" + extensionPrefs );   
    picker.filterIndex=1;
   	picker.defaultExtension = "js";
    picker.init(aWindow, g_reminderFoxBundle.getString("rf.options.prefs.filepicker.title"), reminderFox_nsIFilePicker.modeOpen);

    // get the file and its contents
    var res = picker.show();
    if (res == reminderFox_nsIFilePicker.returnCancel)
      return null;
    else
      return picker.file;
}

function reminderFox_filePickerPreferences(aOpen, aWindow) {
    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(reminderFox_nsIFilePicker);  
   	picker.defaultExtension = "js";
    picker.appendFilter( filterPrefs, "*" + extensionPrefs );   
    picker.appendFilters( reminderFox_nsIFilePicker.filterAll );
    switch (aOpen) {
      case 0:
        picker.init(aWindow, g_reminderFoxBundle.getString("rf.options.prefs.filepicker.title"), reminderFox_nsIFilePicker.modeSave);
        break;
      case 1:
        picker.init(aWindow,g_reminderFoxBundle.getString("rf.options.prefs.filepicker.title"), reminderFox_nsIFilePicker.modeOpen);
        break;
    };
    
    // get the file and its contents
    var res = picker.show();
    if (res == reminderFox_nsIFilePicker.returnCancel)
      return null;
    else
      return picker.file;
}	



function reminderFox_filePickerExport(aOpen, aWindow) {
    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(reminderFox_nsIFilePicker);  
   
   	picker.defaultExtension = "ics";
    picker.appendFilter( filterCalendar, "*" + extensionCalendar );   
    switch (aOpen) {
      case 0:
        picker.init(aWindow, g_reminderFoxBundle.getString("rf.options.export.filepicker.title"), reminderFox_nsIFilePicker.modeSave);
        break;
      case 1:
        picker.init(aWindow,g_reminderFoxBundle.getString("rf.options.import.filepicker.title"), reminderFox_nsIFilePicker.modeOpen);
        break;
    };
    
    // get the file and its contents
    var res = picker.show();
    if (res == reminderFox_nsIFilePicker.returnCancel)
      return null;
    else
      return picker.file;
}	


function reminderFox_concat(c1, c2)
{
  // Concats two collections into an array.
  var c3 = new Array(c1.length + c2.length);
  var x,y = 0;

  for (x = 0; x < c1.length; x++)
    c3[y++] = c1[x];

  for (x = 0; x < c2.length; x++)
    c3[y++] = c2[x];

  return c3;
}

function  reminderFox_populateBars()  {
    // Creates the menuitems for the toolbar selector.
    var win = reminderFox_getWindow();
    var toolbars = win.document.getElementsByTagName("toolbar");
    var statusbars = win.document.getElementsByTagName("statusbar");
    var menubars = win.document.getElementsByTagName("menubar");
    var popup = document.getElementById("reminderFox-popup-bars");
    var x, bar, item, val, list;
    
    // first remove the toolbars already there...
    while (popup.hasChildNodes())
      popup.removeChild(popup.firstChild);
          
    toolbars = reminderFox_concat(toolbars, statusbars);
    toolbars = reminderFox_concat(toolbars, menubars);
    for (x=0; x<toolbars.length; x++) {
      bar = toolbars[x];
      
      //do not include find toolbar
      if (bar.getAttribute("id") == "FindToolbar")
        continue;
             
      item = document.createElement("menuitem");
      item.setAttribute("id", bar.getAttribute("id"));
      item.value = bar.getAttribute("id");         
      if (bar.hasAttribute("toolbarname"))
        item.setAttribute("label", bar.getAttribute("toolbarname"));
      else
        item.setAttribute("label", bar.getAttribute("id"));                 
      popup.appendChild(item);
    }
    
    // add "None" category (can be used to hide status bar ribbon icon)
    item = document.createElement("menuitem");
    item.setAttribute("id", "none");
    item.value = "none"
    item.setAttribute("label", "none");                 
    popup.appendChild(item);
    
    reminderFox_setElement("reminderFox-list-bars", "general.bar", "Char", "reminderFox-popup-bars");    
  }
function reminderFox_ValidateSynchronization() {
	  var text = document.getElementById("reminderFox-text-address");
	  if ( text.value == null || text.value == "" ) {
	  		document.getElementById("reminderFox_network_import_settings").setAttribute("disabled", "true");
	  		document.getElementById("reminderFox_network_export_settings").setAttribute("disabled", "true");
	  		document.getElementById("reminderFox-network-sync").setAttribute("disabled", "true");
	  		document.getElementById("reminderFox-network-auto-desc").setAttribute("disabled", "true");
	  		document.getElementById("reminderFox-text-username").setAttribute("disabled", "true");
	  		document.getElementById("reminderFox-text-password").setAttribute("disabled", "true");
	  		
	  }
	  else {
	  		document.getElementById("reminderFox_network_import_settings").removeAttribute( "disabled" );
	  		document.getElementById("reminderFox_network_export_settings").removeAttribute( "disabled" );
	  		document.getElementById("reminderFox-network-sync").removeAttribute( "disabled" );
	  		document.getElementById("reminderFox-network-auto-desc").removeAttribute( "disabled" );
	  		document.getElementById("reminderFox-text-username").removeAttribute( "disabled" );
	  		document.getElementById("reminderFox-text-password").removeAttribute( "disabled" );
	  }
	  
	 
}


  function reminderFox_populatePositions()   {
    var barid = document.getElementById("reminderFox-list-bars").selectedItem.getAttribute("id");
    var win = reminderFox_getWindow();
    var bar = win.document.getElementById(barid);

    if (!bar)
      reminderFox_mPositionMax = 0;
    else {
      var len = bar.childNodes.length;
    
      //don't include ourself in count
      if (win.document.getElementById("reminderFox-statusLabel").parentNode == bar)
        len--;
    
      reminderFox_mPositionMax = len;
        
    }

    var val;
	try {	
		val = reminderFox_getPreferenceValue( REMINDER_FOX_TOOLBAR_POSITION );	 
	} catch(e) {
		val = -1;
	}		

    var val2 = reminderFox_getPreferenceValue( REMINDER_FOX_TOOLBAR);	 
    var text = document.getElementById("reminderFox-text-position");
    var radio = document.getElementsByAttribute("group", "position");
    var group = document.getElementById("reminderFox-group-position");
    var x, el;
    
    //set max value
    text.value = reminderFox_mPositionMax;
    
    //mark always last
    if (val == -1) {
      for (x=0; x < radio.length; x++) {
        if (parseInt(radio[x].value) == val) {
          group.selectedItem = radio[x];
          break;
        }
      }
    }
    
    //mark specific position
    else {
      for (x=0; x < radio.length; x++) {
        if (parseInt(radio[x].value) != -1) {
          group.selectedItem = radio[x];
          break;
        }
      }    
      if (barid != val2) {
        text.value = reminderFox_mPositionMax;
      } else {
        if (val < 0)
          text.value = reminderFox_mPositionMax;
        else if (val > reminderFox_mPositionMax)
          text.value = 0;
        else
          text.value = val; 
      }
    }
    
    // update the error label
    el = document.getElementById("reminderFox-text-position-valid");
    el.setAttribute("value", "(0-"+reminderFox_mPositionMax+")");
  }
  
  function  reminderFox_getWindow()  {
    //XXX may need to change this code if main window of a supported app is not "navigator:browser"
    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
    var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].getService(Components.interfaces.nsIWindowWatcher);
    var top = wm.getMostRecentWindow("navigator:browser");
	if ( !top ) {
	 	top = wm.getMostRecentWindow("mail:3pane");
	}
	if ( !top ) {
		top = wm.getMostRecentWindow("mail:messageWindow");
	}
	if ( !top ) {
		top = wm.getMostRecentWindow("calendarMainWindow");
	}
	
		
    if (!top) {
    
    var guid;
          try {
        var app = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);    
        guid = app.ID;
      } catch(e) {
        var appBranch = reminderFox_prefs.getBranch(null);
        try {
          guid = appBranch.getCharPref("app.id");
        } catch(e) {
          guid = "{86c18b42-e466-45a9-ae7a-9b95ba6f5640}";
        };    
      };
    
      switch (guid) {
        case "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}":
        case "{3db10fab-e461-4c80-8b97-957ad5f8ea47}":
   //     case "{xulStart@xulrunner.gNeandr}":
        default:        
          top = ww.openWindow(null, "chrome://browser/content/browser.xul", "_blank", "chrome,all,dialog=no", "about:blank");
          break;
        case "{86c18b42-e466-45a9-ae7a-9b95ba6f5640}":
          top = ww.openWindow(null, "chrome://navigator/content/navigator.xul", "_blank", "chrome,all,dialog=no", "about:blank");
          break;
      };
    };
    return top;  
  }
  
  
    function reminderFox_setElement(aName, aPref, aType, aGroup)  {
    var x, el, els, val;
    
    el = document.getElementById(aName);
    
    val = reminderFox_prefs.getCharPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_TOOLBAR);
    //val = eval("this.mBranch.get" + aType + "Pref('" + aPref + "')");
    switch (el.localName) {
      case "checkbox":
        el.checked = val;
        break;
      case "textbox":
        el.value = val;
        break;
      case "menulist":
        els = document.getElementById(aGroup).childNodes;        
        for (x=0; x < els.length; x++) {
          if (((aType == "Int") ? parseInt(els[x].value) : els[x].value) == val) {
            el.selectedItem = els[x];
            break;
          }
        }      
        break;            
      case "radiogroup":
        els = document.getElementsByAttribute("group", aGroup);        
        for (x=0; x < els.length; x++) {
          if (((aType == "Int") ? parseInt(els[x].value) : els[x].value) == val) {
            el.selectedItem = els[x];
            break;
          }
        }      
        break;
    }  
  }
  
  
function reminderFox_openCustomizeUpcomingLabelWindow() {
	var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
	var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
	var topWindow = windowManagerInterface.getMostRecentWindow("window:upcomingLabelOptions");
  
	if (topWindow) {
		topWindow.focus();
   	}
   	else {
   		var newOptions = { variableString:  document.getElementById("upcomingLabelOptions").value }
		window.openDialog("chrome://reminderfox/content/options/upcomingLabelOptions.xul", "upcomingLabelOptions", "chrome,resizable,modal", newOptions);
		document.getElementById("upcomingLabelOptions").value = newOptions.variableString;
			
		var upcomingLabelPref= reminderFox_getPreferenceValue( REMINDER_FOX_UPCOMING_REMINDERS_LABEL );	 
		if (upcomingLabelPref != newOptions.variableString)
			document.getElementById("reminderFox-apply").removeAttribute("disabled");
	}
}

function reminderFox_openCustomizeTodayLabelWindow() {
	var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
	var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
	var topWindow = windowManagerInterface.getMostRecentWindow("window:upcomingLabelOptions");
  
	if (topWindow) {
		topWindow.focus();
   	}
   	else {
   		var newOptions = { variableString:  document.getElementById("todaysLabelOptions").value }
		window.openDialog("chrome://reminderfox/content/options/upcomingLabelOptions.xul", "todaysLabelOptions", "chrome,resizable,modal", newOptions);
		document.getElementById("todaysLabelOptions").value = newOptions.variableString;
		var upcomingLabelPref = reminderFox_getPreferenceValue( REMINDER_FOX_TODAYS_REMINDERS_LABEL );
		if (upcomingLabelPref != newOptions.variableString)
			document.getElementById("reminderFox-apply").removeAttribute("disabled");
	}
}



function reminderFox_loadCustomizeUpcomingLabelWindow() {
	var upcomingLabel = window.arguments[0].variableString;
	document.getElementById("upcomingLabelText").setAttribute("value", upcomingLabel);
}

function reminderFox_saveCustomizeUpcomingLabel() {
	var upcomingLabel = document.getElementById("upcomingLabelText").value;
	window.arguments[0].variableString = upcomingLabel;
	window.close();	
}
function reminderFox_openCustomizeReminderListDateWindow() {
	var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
	var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
	var topWindow = windowManagerInterface.getMostRecentWindow("window:reminderListDateOptions");
  
	if (topWindow) {
		topWindow.focus();
   	}
   	else {
   		var newOptions = { variableString:  document.getElementById("dayAppearanceLabel").value }
		window.openDialog("chrome://reminderfox/content/options/listDateLabelOptions.xul", "listDateLabelOptions", "chrome,resizable,modal", newOptions);
		document.getElementById("dayAppearanceLabel").value = newOptions.variableString;
		var dayAppearanceLabelPref =  reminderFox_getPreferenceValue( REMINDER_FOX_LIST_DATE_LABEL );
		if (dayAppearanceLabelPref != newOptions.variableString)
			document.getElementById("reminderFox-apply").removeAttribute("disabled");
	}
}

function reminderFox_loadDefaultMoreWindow() {
	var upcomingLabel = window.arguments[0].variableString;
	document.getElementById("defaultMoreText").setAttribute("value", upcomingLabel);
}

function reminderFox_saveDefaultMoreLabel() {
	var upcomingLabel = document.getElementById("defaultMoreText").value;
	window.arguments[0].variableString = upcomingLabel;
	window.close();	
}
function reminderFox_openCustomizeDefaultMoreWindow() {
	var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
	var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
	var topWindow = windowManagerInterface.getMostRecentWindow("window:reminderListDefaultMoreOptions");
  
	if (topWindow) {
		topWindow.focus();
   	}
   	else {
   		var newOptions = { variableString:  document.getElementById("defaultMoreLabel").value }
		window.openDialog("chrome://reminderfox/content/options/defaultMoreOptions.xul", "defaultMoreOptions", "chrome,modal,resizable", newOptions);
		document.getElementById("defaultMoreLabel").value = newOptions.variableString;
		var dayAppearanceLabelPref =  reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_MORE );
		if (dayAppearanceLabelPref != newOptions.variableString)
			document.getElementById("reminderFox-apply").removeAttribute("disabled");
	}
}

function addOrEditListItem(addOrEdit) {
	var currentListName = null;
	var url = null;
	var subscriptions = reminderFox_getSubscriptions();		
	if (addOrEdit == 1 ) {  // edit
		var catCurList = document.getElementById('reminderFox_todoLists_listbox');
		var selCatItem = catCurList.currentIndex;
		
		if (selCatItem == -1) {return;}  /* no item selecetd */
		
		currentListName = catCurList.childNodes[selCatItem].getAttribute( "label");
		url = subscriptions[currentListName];
	}
	var originalListName = currentListName;
	var callOptions = { added: false,  addEvent: addOrEdit,  currentItem: currentListName, subscription: url  };
	window.openDialog("chrome://reminderfox/content/options/addCustomList.xul",
		"reminderFox-editAdd-categories", "chrome,resizable,modal", callOptions );
	if ( callOptions.added == true ) {
		if (addOrEdit == 0 ) {  // add
			var reminderFox_todoLists_listbox= document.getElementById("reminderFox_todoLists_listbox");
			var newItem = document.createElement("listitem");
			var newListName = callOptions.currentItem;
			newItem.setAttribute( "label", newListName);
			newItem.setAttribute( "value", newListName);
			
			reminderFox_todoLists_listbox.appendChild(newItem);						
		}
		else {
			if ( originalListName != callOptions.currentItem ) {  // name has changed - save out to new name....
				catCurList.childNodes[selCatItem].setAttribute( "label", callOptions.currentItem );
				catCurList.childNodes[selCatItem].setAttribute( "value", callOptions.currentItem );
				var reminderFoxTodosArrayArg =  reminderFox_getReminderTodos();
				var reminderTodos = reminderFoxTodosArrayArg[originalListName];
				if ( reminderTodos != null && reminderTodos.length > 0 ) {
					 reminderFoxTodosArrayArg[callOptions.currentItem] = reminderTodos;
					 reminderFoxTodosArrayArg[originalListName] = new Array();		
					 
					 reminderFox_writeOutRemindersAndTodos(false);									 
				}		
			}	
		}
		
		// if subscription has changed (added/edited/removed), then update the preference								
		if ( subscriptions[callOptions.currentItem] != callOptions.subscription ) {
			subscriptions[callOptions.currentItem] = callOptions.subscription; 
			reminderFox_writeSubscriptions( subscriptions );
		}												

		
	
		
	}
			
}

