/**    
 * mail.js
<br> 
<br>  @since 
<br>   2009-12-17  EndOfSupport for TB1.x 
	   2008-08-04  Open Msg with msgID also with FX (non-mail apps)
<br>   2008-04-14	tagging	- add/delete 'ical-*' tags for messages containing 
 * 									iCal data
<br>   2008-01-19	add TB-priority handling
<br>   2006-11-11	mod for TB1.5/label and TB2.0/tag
<p> 
<br>  @see 
<br>     MessageID-Finder for Mozilla 'messageidfinder-2.0.0.xpi' by markushossner_AT_gmx_DOT_de and 
<br>     'reminderfox-0.9.6.xpi' by Daniel Lee, Tom Mutdosch
 */

var rmFx_currentSummary = null;
var rmFx_ReferenceID = "@" + "reminderfox" 
var rmFx_FCC ="";
var rmFx_cmdID = null;
var rmFx_cmdString = "";

/**
 *  Work with rmFx_cmdLineHandler to support starting 'messenger' (TB/SM/PB) 
 *  with start option:
 *  
<br>    @call  'messenger'.exe -reminderFox {remoteID}            -msgString {details for op}
<br>
<br>    @call  'messenger'.exe -reminderFox UID:refID             -msgString {file path}
<br>    @call  'messenger'.exe -reminderFox COMPOSE:subject       -msgString {compose parameters}
<br>    @call  'messenger'.exe -reminderFox msgID:finalMessageId  -msgString {subject info}
 */ 
function rmFx_startupwMsgId() {
//------------------------------------------------------------------------------
	var startMsg	= window.arguments[0].split("|.|");
	rmFx_cmdID 		= startMsg[0];
	rmFx_cmdString	= startMsg[1];

	//gWTEST Darwin	---------<<< ---------------
	
	var logString = (" startupwMsgId 'remote start': "
			+ "\n rmFx_cmdID: " + rmFx_cmdID
			+ "\n rmFx_cmdString: " + rmFx_cmdString);
	
	var rmFx_consoleService = Components.classes["@mozilla.org/consoleservice;1"]
	     .getService(Components.interfaces.nsIConsoleService);

	rmFx_consoleService.logStringMessage("reminderFox: " + logString);
	// ------------>>> ----------------
		
		
	var cDate = new Date();
	var msgLog = " ** Remote access **  " + rmFx_cmdID + " at: " + cDate;
	try {
		rmFxUtil.dump2Console('general', msgLog);
		rmFxMsg.whichMessenger();
	} catch (ex) {
		var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
		     	                       .getService(Components.interfaces.mozIJSSubScriptLoader);
		loader.loadSubScript("chrome://reminderfox/content/utils/rmFxUtils.js");
		rmFxUtil.dump2Console('general', msgLog);
		rmFxMsg.whichMessenger();
	}
	// -reminderFox UID:refID -msgString mailFile.path
	if (rmFx_cmdID.indexOf('UID:') > -1) {		
		document.title = "Remote send message";	// reminderFox_getBundle().getString("rf.mail.remote.sendmsg");

		document.getElementById('rmFx_msg1').setAttribute("value", rmFx_cmdID);  
		document.getElementById('rmFx_msg2').setAttribute("value", "");
		setTimeout( rmFxMsg.sendwUIDgo, 1000 );
	   		
	// -reminderFox COMPOSE:subject -msgString {compose parameters}
	} else  if (rmFx_cmdID.indexOf('COMPOSE:') > -1) {		
		document.title = "Remote compose message";  // reminderFox_getBundle().getString("rf.mail.remote.composemsg"); 

		var msgString = unescape(rmFx_cmdString).split(";\n;");
		var subject   = msgString[0].substring(8);

		document.getElementById('rmFx_msg1').setAttribute("value", "Subject: " + subject);
		document.getElementById('rmFx_msg2').setAttribute("value", "");
		setTimeout( rmFxMsg.composeMSGgo, 1000 );
		   
	// -reminderFox msgID:finalMessageId -msgString {subject info}
	} else  if (rmFx_cmdID.indexOf('msgID:') > -1) {
		document.title = "Remote open message";	//	reminderFox_getBundle().getString("rf.mail.remote.openmsg");

		document.getElementById('rmFx_msg1').setAttribute("value", unescape(rmFx_cmdString));
		document.getElementById('rmFx_msg2').setAttribute("value", rmFx_cmdID);
		setTimeout( rmFx_retryMsgIdDelayed, 1000 );

	} else {
		alert ("reminderFox call error!")
		return;
	}
}
/**
 *  find message with MsgID ////////////////////////////
 *
 */

function rmFx_retryMsgIdDelayed() {
    var msgHdr = reminderFox_MessageIdFinder(rmFx_cmdID.substring(6));
    if (msgHdr) {
        window.close();
    }   
    else  {  // 'reminderFox_MessageIdFinder' with TB startup will fail because
             //  folder structure not build already
             //  if it fails  -->>  aks for 'retry'
		document.getElementById('msgIDnotFound').setAttribute("hidden", "false");
		document.getElementById('retryMsgId').setAttribute("disabled", "false");  
		sizeToContent();
		window.focus();
    }				
}

function rmFx_retryMsgId() {

	if (rmFx_cmdID.indexOf('UID:') > -1) {
	   rmFxMsg.sendwUIDgo();
		window.close();
	} else {
		var msgHdr = reminderFox_MessageIdFinder(rmFx_cmdID);
		if (msgHdr) {
			window.close();
		}
	}	
}

function reminderFox_changeMessageLabel(addTag) {
	reminderFox_OpenMessageByMessageID(gDBView.hdrForFirstSelectedMessage.messageId /*messageId*/
			,false /*msgOpen*/, addTag, true /*opTag*/)
}

function rmFxMsgHdrDate (dateStr) { 
	var time = new Date();
	time.setTime(dateStr / 1000);
   
	var timeString = reminderFox_mail_getTimeString( time );
	var dateVariableString;
	try {
      dateVariableString = reminderFox_getUnicodePref(REMINDER_FOX_PREF + "." + REMINDER_FOX_LIST_DATE_LABEL);
    	} catch(e) {
	}    
    return reminderFox_getDateVariable( null, time, dateVariableString ) + "  " + timeString;
}


    /**
     * GetSelectedMessages for different TB/SM/PB versions
     * 
     */
	function rmFx_GetSelectedMessages() {
		rmFxMsg.whichMessenger();
		
		if ((gRmFx_Messenger == "TB3") || (gRmFx_Messenger == "SM2")) {
			var mailWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService()
				.QueryInterface(Components.interfaces.nsIWindowMediator)
				.getMostRecentWindow("mail:3pane");
			if (mailWindow) {
				return mailWindow.gFolderDisplay.selectedMessageUris;
			}
		} else {	// valid for all other versions
			return GetSelectedMessages();
		}
	}

/**
<br> *  Add email reminder for current selected message
 *
 */
function reminderFox_thunderBirdAddEmailReminder() {

	try {
		document.getElementById('threadPaneContext').hidePopup();
	} catch (e) {}
	try {
	document.getElementById('messagePaneContext').hidePopup();
	} catch (e) {}

	// with TB3 this is not supported !!
	var msgSelected = rmFx_GetSelectedMessages();
	
	// ("works for all selected messages");	
	if (msgSelected.length > 1) {
		window.GetThreadTree().view.selection.clearSelection();	
	}
	
	for (var nHdr = 0; nHdr < msgSelected.length; nHdr++) {
	
		var i = msgSelected[nHdr].indexOf("#");
		var nextHeader = msgSelected[nHdr].substring(i +1);
		
		var msgDBView = {};
		msgDBView = window.gDBView;
		msgDBView.selectMsgByKey(nextHeader);
		
		var msgHdr = gDBView.hdrForFirstSelectedMessage;

      var rmFxSummary = msgHdr.mime2DecodedSubject;
      var rmFxFrom =  msgHdr.mime2DecodedAuthor;
      var rmFxTo = msgHdr.mime2DecodedRecipients;
      var rmFxPrio =msgHdr.priority;

      //  add text from hightlighted mail-text
      var rmFxDetails = null;
      var focusedWindow = document.commandDispatcher.focusedWindow;
      var selectedText = focusedWindow.getSelection();
      
      if (selectedText != null && selectedText != "") {
         rmFxDetails = "\n\n" +   reminderFox_getBundle().getString("rf.add.mail.message.details") +
            ":\n" +   selectedText.toString();
      }

      // messageID
      // strip out quotes as the extractHeader method returns some message-id's with extraneous quotes
      // like: "000c01c6941b$6ddb3c30$7be040"@foo.com
      var rmFxMessageID = "<" +  msgHdr.messageId.replace(new RegExp(/\"/g),"") + ">";
      var rmFxDate = rmFxMsgHdrDate (msgHdr.date);

      var newDate = new Date();
      newDate.setDate( newDate.getDate() + 1 );  // default to using tomorrow's date for reminder

      var reminderId =reminderFox_generateUniqueReminderId( newDate );
      var mailIdentifierString = reminderFox_getBundle().getString("rf.add.mail.message.mail.identifier");
      var newReminderToBeAdded = new ReminderFoxEvent( reminderId, newDate, mailIdentifierString + " " + rmFxSummary );
      newReminderToBeAdded.messageID = rmFxMessageID;

      // add default message header info to the Notes section
      newReminderToBeAdded.notes =
         reminderFox_getBundle().getString("rf.add.mail.message.sender")      + ": " + rmFxFrom   +  "\n" +
         reminderFox_getBundle().getString("rf.add.mail.message.recipients")   + ": " + rmFxTo   +  "\n" +
         reminderFox_getBundle().getString("rf.add.mail.message.date")         + ": " + rmFxDate   +  "\n" +
         reminderFox_getBundle().getString("rf.add.mail.message.subject")      + ": " + rmFxSummary;

      if ( rmFxDetails != null ) {
         newReminderToBeAdded.notes = newReminderToBeAdded.notes + rmFxDetails;
      }

	// PRIORITY definition for  RmFx and  TB
	// const REMINDER_PRIORITY_NORMAL = null;  // default
	// const REMINDER_PRIORITY_IMPORTANT = 1;
	//	TB header.priority:  6= very high;  5=high;  1=normal;  3=low;  2=very low
	
		if ( msgHdr.priority >= 5 ) { 			// for TB 'very high' and 'high'
			newReminderToBeAdded.priority = 1;	// set RmFx 'Important'
		}
			
		var added = reminderFox_addReminderHeadlessly( newReminderToBeAdded );		
		if (added) {
			rmFx_msgTAGing("Reminderfox", true, "#993399");
		} else {
			// only if more remaining reminders!!
			if ((msgSelected.length - nHdr - 1) > 0) {
				// if the last msg was deleted, ask to terminate all remaining or continue
				var title =	reminderFox_getBundle().getString("rf.add.addreminder.title");
				var msg =	reminderFox_getBundle().getString("rf.add.addreminder.instruction2")
							+	"\n\n" + reminderFox_getBundle().getString("rf.add.addreminder.instruction3") + " » "
							+ (msgSelected.length - nHdr - 1) 
	 						+ " « " +  reminderFox_getBundle().getString("rf.add.addreminder.instruction4");
				var key0 =	reminderFox_getBundle().getString("rf.button.ok");
				var key1 =	"No, terminate."; // reminderFox_getBundle().getString("rf.add.addreminder.cancel"); 
			    	
				if (rmFxUtil.ConfirmEx(title, msg, key0, key1) == 1 ) {  // cancel pressed
					 nHdr = msgSelected.length +1; 
				}
			}
		}			
	}
}
/** 
 * displayMail 
 *
<br>  retrieve and display this reminder's associated email in Thunderbird
 */
function reminderFox_displayMailbyMsgID(recentReminder) {
   reminderFox_openByMessageID(recentReminder);
}


function reminderFox_doShowMail() {
	var currentReminder = getReminderForSelectedItem( );
	if ( currentReminder.messageID != null ) {
		reminderFox_openByMessageID(currentReminder);
	}
	else if ( reminderFox_isGMailEvent(currentReminder) ) {
		 reminderFox_openURL(  currentReminder.url );
		reminderFox_focusBrowser();
	}
}

function reminderFox_doShowMailTodo() {
	var currentTodo = getTodoForSelectedItem( );
	if ( currentTodo.messageID != null ) {	
		reminderFox_openByMessageID(currentTodo);	
	}
	else if ( reminderFox_isGMailEvent(currentTodo) ) {
		 reminderFox_openURL(  currentTodo.url );
		reminderFox_focusBrowser();
	}
}

function reminderFox_doShowMailShortcut() { 
	if ( isReminderTabSelected() ) {
		reminderFox_doShowMail();
	}
	else {
		reminderFox_doShowMailTodo();
	}
}

function reminderFox_openByMessageID(currentReminder){
	var finalMessageId = reminderFox_finalMessageId(currentReminder.messageID);

	rmFx_currentSummary = currentReminder.summary;

	// if using Firefox, this starts (Thunderbird) Messenger App ... 
	// using a specific 'commandLine' Handler 
	
	if(!("@mozilla.org/messenger;1" in Components.classes)) {

		var mailApp = rmFx_MessengerApp();
		if ((mailApp == null) || (mailApp == ""))  {
			rmFxUtil.PromptAlert(reminderFox_getBundle().getString("rf.messenger.notfound"));
            return;
        }
	
		var args = new Array();   
		args [0] = "-reminderFox";
		args [1] = "msgID:" + finalMessageId;    
		args [2] = "-msgString"; 
		args [3] = escape(rmFx_currentSummary); 				// currentReminder.summary;
		
		try {
			go4Process.init(mailApp);
		} catch (ex) {}
		go4Process.run(false, args, args.length);
	
    	return;		// FX schedules TB with msgID:messageID -msgString rmFx_currentSummary
   }   

	if (finalMessageId !="" ) {
		var msg = reminderFox_MessageIdFinder(finalMessageId);

		if (!msg) {
			var strMsgIdNotFound = reminderFox_getBundle().getString("rf.add.mail.messageIdNotFound.message") +
					"\n" + rmFx_currentSummary  + 
					"\n(Message-ID: " + finalMessageId +")";
			rmFxUtil.PromptAlert(strMsgIdNotFound);
			window.setCursor("auto");
		}
	}
}

function reminderFox_finalMessageId(messageId){
 	var midleft = (messageId.toLowerCase()).search("<"); 
 	var finalMessageId;
 	if (midleft == -1)
      	finalMessageId = "";
	else {
 	   var midRight = (messageId.substring(midleft)).search(">");
       finalMessageId =  messageId.substring(midleft + 1, midRight );
	}
	return finalMessageId;
}


   /**
    * Clear the 'Reminder' tag from a message
    * 
    * @note	 this function only works in messenger/ThunderBird 
    * @param messageId
    */
function reminderFox_clearLabelByMessageID(messageId){

 	var finalMessageId = reminderFox_finalMessageId(messageId)
	if (finalMessageId != "" )  reminderFox_OpenMessageByMessageID( finalMessageId, 
			false /*msgOpen*/, 0 /*labelTag*/, false /*opTag*/);
}



/**
 * MessageID features
 * based on: MessageID-Finder for Mozilla by
 * 
 * Markus Hossner - markushossner@gmx.de
 */

const reminderFox_pmpB = 0;		//Boolean
const reminderFox_pmpN = 1;		//Integer
const reminderFox_pmpS = 2;		//Char

var reminderFox_prefRead = false;
var reminderFox_accountURIs = new Array();
var reminderFox_msgWindow;


function reminderFox_MessageIdFinder(strmessageid) {
    
    strmessageid = reminderFox_ExtractMessageID(strmessageid);

	var msgHdr = reminderFox_OpenMessageByMessageID(strmessageid,true);
	return msgHdr;        
}


function reminderFox_getMsgWindow() {
	if ( reminderFox_msgWindow == null ) {
		reminderFox_msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"].
				createInstance(Components.interfaces.nsIMsgWindow);
	}
	return reminderFox_msgWindow;
}


function reminderFox_ExtractMessageID(strmessageid) {
    var midParts = strmessageid.replace(/^<|>$/g, "").split(":");

    switch (midParts.length) {
        case 1:
            strmessageid = strmessageid;
            break;

        case 2:
            if (midParts[0] == "news" || midParts[0] == "nntp") {
                strmessageid = midParts[1].replace(/^\/\/.*?\// ,"");
            } else if (midParts[0] == "mailto") {
                strmessageid = midParts[1];
            }
            break;

        case 3:
            strmessageid = midParts[2].replace(/^.+?\// ,"");
            break;

        default:
            strmessageid = "";
            break;
    }
    return strmessageid;
}


    /**
	 * Message with matching 'messageid' will be processed with tag 'labelTag'
	 * based on option 'msgOpen'.
	 * If 'msgOpen' true the message will be opened.
     *
<p>  *  Message is labeled/tagged with optional parameter 'labelTag' 
<ul> *      TB1.5
<br> *           labelTag = 0 noLabel   =1 ... =5  see Label Options with Pull-Down Menue
<br> *           opTag = not used
</ul>*
<ul> *      TB2.x / TB3.x / SM2 / PB
<br> *         labelTag = string eg:ReminderFox
<br> *         opTag = true: add Tag;  false: remove Tag
</ul>*
    *  @since 2009-04 :  
    *    messages in Template and Draft folders are not opened, but
    *    the folder is selected
    *
    *  @since 2009-07
    *    Postbox support .. needs special handling for open folder/message
    *
    * @note
    *    TB3/SM2 and PB need to select message row in folder
    *
    *   @param messageId
    *   @param msgOpen - true: opens in new window
    *   @param labelTag - 
    *   @param opTag - true: adds, false: deletes the tag
    */
function reminderFox_OpenMessageByMessageID(messageId, msgOpen, labelTag, opTag) {
	
	rmFxMsg.whichMessenger();
	reminderFox_AddNewsServers();   
	window.setCursor("wait");

    var msgHdr = reminderFox_SearchMessageLocally(messageId);
    
    window.setCursor("auto");
    
	if (msgHdr) {
		var folder = msgHdr.folder;	
        var folderUri = folder.URI;
		var messageUri = folder.getUriForMsg(msgHdr);  
            
		var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
		         		                      .getService(Components.interfaces.nsIWindowMediator);
		var winId = windowManager.getMostRecentWindow("mail:3pane");
		
		
        if (gRmFx_Messenger == "TB3") {	 //TB3
			winId.focus();
			winId.document.getElementById('tabmail').openTab("folder", 
				{folder: msgHdr.folder, msgHdr:msgHdr, messagePaneVisible:true } );
        }
        
        if (gRmFx_Messenger == "PB") {				// PB 
        	
			winId.focus();
			winId.MsgOpenNewTabForFolder(folderUri, msgHdr.messageKey /*key*/, false /*aBackground*/)
        }


        if (gRmFx_Messenger == "SM2") {

	        var aTabShowFolderPane  = 1 << 0;
	        var aTabShowMessagePane = 1 << 1;
	        var aTabShowThreadPane  = 1 << 2;

	        var aTabModeFolder = aTabShowMessagePane;
	        	        
	        if (!winId) {
	        	winId = window.openDialog("chrome://messenger/content/", "",
	        		"all,dialog=no");
	        	
	    		winId = windowManager.getMostRecentWindow("mail:3pane");
	        }
	        
        	winId.focus();
        	winId.document.getElementById('tabmail').openTab("3pane",
        		aTabModeFolder, folderUri, msgHdr);    
        }

        // select message in the mail index 
      if (gRmFx_Messenger == "TB2") {         //TB2
    	    // --- if folderUri has '/Template' or '/Drafts' it will not open the message
	        var xShow = ((folderUri.indexOf("/Templates") == -1) && (folderUri.indexOf("/Drafts") == -1)) ;
 
	        // open the message in a new window 
	        if ((msgOpen) && (xShow)){
	            var folder = reminderFox_GetMsgFolderFromUri(folderUri);
	            var messageUri = folder.getUriForMsg(msgHdr);
	                     
	            window.openDialog("chrome://messenger/content/messageWindow.xul", "_blank",
	                              "all,chrome,dialog=no,status,toolbar", messageUri, folderUri, null);
	        }
				        
   			try { 
	            var tree = {};
	            var msgDB = {};
	            var length = {};
	            var wintype = {};
	            var msgDBView = {};
	            var indicesArray = {};
	            reminderFox_msgWindow = reminderFox_getMsgWindow();
	            
	            if (document.firstChild.id == "messengerWindow") {
	            	wintype = window.document.firstChild.getAttribute("windowtype");
	            	reminderFox_msgWindow.SetDOMWindow(window);
	
	            	folder = reminderFox_GetMsgFolderFromUri(folderUri);
	            	msgDB = folder.getMsgDatabase(reminderFox_msgWindow);
	            	msgDB.MarkHdrRead(msgHdr, false, null);
	            	reminderFox_msgWindow.SelectFolder(folderUri);
	
	            	msgDBView = window.gDBView;
	            	if (wintype != "mail:messageWindow") tree = window.GetThreadTree();
	            } else {             	     
	            	wintype = window.opener.document.firstChild.getAttribute("windowtype");
	            	reminderFox_msgWindow.SetDOMWindow(window.opener);
	
	            	folder = reminderFox_GetMsgFolderFromUri(folderUri);
	            	msgDB = folder.getMsgDatabase(reminderFox_msgWindow);
	            	msgDB.MarkHdrRead(msgHdr, false, null);
	            	
	            	reminderFox_msgWindow.SelectFolder(folderUri);
	
	            	msgDBView = window.opener.gDBView;
	            	if (wintype != "mail:messageWindow") tree = window.opener.GetThreadTree();
	            }
 
				if (wintype != "mail:messageWindow") tree.view.selection.clearSelection();
	            msgDBView.selectMsgByKey(msgHdr.messageKey);
	            msgDBView.loadMessageByMsgKey(msgHdr.messageKey);
	            msgDB.MarkHdrRead(msgHdr, true, null);
	            msgDBView.getIndicesForSelection(indicesArray,length);
	            if (wintype != "mail:messageWindow") tree.treeBoxObject
	                                                     .ensureRowIsVisible(indicesArray.value[0]);
	        } catch( e ) { }
		}
	}


    if ((gRmFx_Messenger == "SM2") && (msgHdr == null)) {
		var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
			       .getService(Components.interfaces.nsIWindowMediator);

    	window.openDialog("chrome://messenger/content/", "",
    		"all,dialog=no");
		windowManager.getMostRecentWindow("mail:3pane");
	}

	
	// extract the tag keys from the msgHdr	
	if (msgHdr != null && labelTag != null ) { 	
		rmFx_msgTAGing("Reminderfox", opTag, "#993399" );
		
		// delete all iCal-xxxx tags eg: PUBLISH, REQUEST, REPLY, CANCEL, ICS		
	   	var msgKeyArray = msgHdr.getStringProperty("keywords").split(" ");
   	
	   	if ((opTag == false) && (msgKeyArray.length > 0))  {
	   		for (var n= 0; n< msgKeyArray.length; n++  ) {
  			
	   			if (msgKeyArray[n].indexOf("ical") == 0) {
					try {
						ToggleMessageTag(msgKeyArray[n], false /*tagOp*/, "", false)  //4th param for PB
					} catch (ex) {}
	   			}
			}
	   	}
	}
    window.setCursor("auto");
    return msgHdr;
}


	/**
	* Open a new window with the folder and open message
	*
	* @param uriToOpen - folder uri
	* @param msgID - messageID
	*/
	function rmFx_MsgOpenNewWindowForFolder(uriToOpen, msgID) {
	
	  if (uriToOpen)
	    window.openDialog("chrome://messenger/content/", "_blank", 
	    		"chrome,all,dialog=no", uriToOpen, msgID);
	}


  /**
    * Search for messageid in local folders
    */
function reminderFox_SearchMessageLocally(messageId) {
    var msgHdr = null;
    var folder = null;
    for(var x = 0; x < reminderFox_accountURIs.length && !msgHdr; x++) {  
        folder = reminderFox_GetMsgFolderFromUri(reminderFox_accountURIs[x]).rootFolder;
        msgHdr = reminderFox_SearchInSubFolder(folder, messageId);  
    }
    return msgHdr;
}


  /**
    * Searchs in subfolder 
    */
function reminderFox_SearchInSubFolder(sFolder, messageId) {

    	if ((gRmFx_Messenger == "TB3") || (gRmFx_Messenger == "SM2")) {

		var subfolder = null;
		var msgHdr = null;
		var msgDB = null;
		var currentFolderURI = "";
	
		var done = false;
												
		if (sFolder.hasSubFolders) {
	
			var subfolders = sFolder.subFolders;
			while (subfolders.hasMoreElements()) {			
				var subfolder = subfolders.getNext().QueryInterface(Components.interfaces.nsIMsgFolder);
			//	if (currentFolderURI.substring(1,7) != "news://") {  
					msgHdr = reminderFox_SearchInSubFolder(subfolder, messageId);
			//	}				
				if (!msgHdr) {
					try {	
						var msgDB = subfolder.msgDatabase;
					} catch (ex) {}

					if ( msgDB != null ) msgHdr = msgDB.getMsgHdrForMessageID(messageId);
				}
				if (msgHdr) return msgHdr;	 
				try {
				    subfolders.next();
				} catch(e) {
				    done = true;
				}
			} //while
		} //if (sFolder.hasSubFolders)
		return null;
		
	} else {
		
		if (sFolder.hasSubFolders) {  // TB2.
			var subfolders = sFolder.GetSubFolders();
			var subfolder = null;
			var msgHdr = null;
			var msgDB = null;
			var currentFolderURI = "";
			var done = false;
	  
			while(!done) {
				currentFolderURI = subfolders.currentItem()
	                           .QueryInterface(Components.interfaces.nsIRDFResource).Value;
				subfolder = reminderFox_GetMsgFolderFromUri(currentFolderURI);
	
				if (currentFolderURI.substring(1,7) != "news://") {  
							msgHdr = reminderFox_SearchInSubFolder(subfolder, messageId);
				}
				if (!msgHdr) {
	   
					try {
						reminderFox_msgWindow = reminderFox_getMsgWindow();
						msgDB = subfolder.getMsgDatabase(reminderFox_msgWindow);
					} catch (ex) {
	
					// subfolder.updateFolder(reminderFox_msgWindow); // TM: this call was causing a hang in some instances
					// try {
					// // msgDB = subfolder.getMsgDatabase(reminderFox_msgWindow);
					// } catch (ex) {
					// }
					}
					
					if ( msgDB != null ) {
						msgHdr = msgDB.getMsgHdrForMessageID(messageId);
					}
				}
				if (msgHdr) return msgHdr;
	 
				try {
				    subfolders.next();
				} catch(e) {
				    done = true;
				}
			}
		}  // TB2.   if (sFolder.hasSubFolders)
		return null;				
		// } 
	}
}


    /**
     * Searchs all availible newsserver
     */
function reminderFox_AddNewsServers() {
    if (reminderFox_prefRead == false) {
        var accounts = reminderFox_pmpReadPref("mail.accountmanager.accounts",reminderFox_pmpS);
        if (accounts) {
            var accountsArray = accounts.split(",");
            
            for (var x = 0; x < accountsArray.length; x++) {
                reminderFox_AddNewsServerMenuItem(accountsArray[x]);
            }
            reminderFox_accountURIs.sort(reminderFox_sortAccountUris);
        }

        reminderFox_prefRead = true;
    }
}


   /**
    * Sortfunction for reminderFox_accountURIs Array Local Folder to the rear
    *
    * @param a and b
    * @return  1:	;	-1:
    */
function reminderFox_sortAccountUris(a, b) {

    if (a.search(/Local%20Folders/) != -1) {
        return 1;
    } else if (b.search(/Local%20Folders/) != -1) {
        return -1;
    } else if (a < b) {
        return -1;
    } else if (a > b) {
        return 1;
    } else {
        return 0;
    }
}

 
	/** 
	 * Adds newsserver to the context menu
     *
     */
function reminderFox_AddNewsServerMenuItem(account) {
    var server    = reminderFox_pmpReadPref("mail.account." + account + ".server",reminderFox_pmpS);
    var servertyp = reminderFox_pmpReadPref("mail.server."  + server +  ".type",reminderFox_pmpS);
    var hostname  = reminderFox_pmpReadPref("mail.server."  + server +  ".hostname",reminderFox_pmpS);
    var username  = reminderFox_pmpReadPref("mail.server."  + server +  ".userName",reminderFox_pmpS);

    var accountURI = "";
    
    if (servertyp == "nntp") {
        var servername = reminderFox_pmpReadPref("mail.server." + server + ".name",reminderFox_pmpS);
        var serverport = reminderFox_pmpReadPref("mail.server." + server + ".port", reminderFox_pmpN);
        // var newsservermenuitem;

        if (servername == null) servername = hostname;
        if (serverport == null) serverport = 119;

        accountURI = "news://" + escape(hostname);
    } else if (servertyp == "imap") {
        accountURI = "imap://" + escape(username) + "@" + escape(hostname);
    } else {
        accountURI = "mailbox://" + escape(username) + "@" + escape(hostname);
    }

    if (hostname != null) reminderFox_accountURIs.push(accountURI);
}



	/**
     * Reads the value of pmpName out of the mozilla preferences
     * 
     * @param	pmpName
     * @param	pmpType	Bool,Integer or Char 
     *
     * @return	pmpValue
     */
function reminderFox_pmpReadPref(pmpName, pmpType) {
    var nsIPrefBranch = Components.interfaces.nsIPrefBranch;
    var pref = Components.classes["@mozilla.org/preferences-service;1"]
                         .getService(nsIPrefBranch);
    var pmpValue = null;
    
    if (pref.prefHasUserValue(pmpName)) {
        switch (pmpType) {
            case reminderFox_pmpB:
                pmpValue = pref.getBoolPref(pmpName);
                break;
            case reminderFox_pmpN:
                pmpValue = pref.getIntPref(pmpName);            
                break;
            case reminderFox_pmpS:
                pmpValue = pref.getCharPref(pmpName);
                break;
            default:
                break;
        }
    }
    
    return pmpValue;
}


    /**
      * Get msgfolder from Uri
      * 
      * @param	uri
      * @return	null or msgfolder
      */
function reminderFox_GetMsgFolderFromUri(uri) {
    var msgfolder = null;
    
    try {
        var RDF = Components.classes["@mozilla.org/rdf/rdf-service;1"]
                            .getService(Components.interfaces.nsIRDFService);
        var resource = RDF.GetResource(uri);
        
        if (resource instanceof Components.interfaces.nsIMsgFolder &&
           (resource.parent || resource.isServer))
           msgfolder = resource;
           
    } catch (ex) {}

    return msgfolder;
}


////////////////// end of 'MessageID' //////////////////////////////////////////


//  --- rmFx_folderListener  ----------------------------------------------- ---
/**
 *  folder listener used with   SEND++
 */
   var rmFx_FolderListener = {
      OnItemEvent: function(aFolder, event) {
      },
      OnItemAdded: function(parentItem, item) {
      },
      OnItemIntPropertyChanged: function(aFolder, aProperty, aOldValue, aNewValue) {

       var folderURI  = (gRmFx_Messenger != "PB") 
             ?  aFolder.URI 
             :   aFolder.QueryInterface(Components.interfaces.nsIRDFResource).Value;

         var msg = "FolderListener: OnItemIntPropertyChanged: rmFx_FCC:" + rmFx_FCC
               + "\naFolder.URI: " + folderURI
               + "\n" + aProperty.toString() + "  old: " + aOldValue + "  new: " + aNewValue

         if ((aProperty.toString() == "FolderSize") && (rmFx_FCC == folderURI)) {
            rmFxUtil.dump2Console ('FolderListener', msg)

            if ( aOldValue != aNewValue) {
            var messenger = Components.classes["@mozilla.org/messenger;1"].createInstance()
                        .QueryInterface(Components.interfaces.nsIMessenger);

            var msgUri = reminderFox_GetMsgFolderFromUri(rmFx_FCC).baseMessageURI + "#" + aOldValue;
            var msgHeader = messenger.messageServiceFromURI(msgUri).messageURIToMsgHdr(msgUri);
            var messageId =  msgHeader.messageId;
            var lastReminder = gRmFx_LastEvent;

            // reset the 'send folder' and Listener to process only once
            rmFx_FCC = "";
            rmFx_setFolderListener("remove");

            setTimeout(rmFx_msgTAGing, 100, 'Reminderfox' /*tagName*/, true /*addKey*/,  "#993399", msgHeader);   

            // now update the "lastReminder"  with the ".messageID"
            var activeReminders = reminderFox_getReminderEvents();

            for ( var i = 0; i < activeReminders.length; i++ ) {
               if (activeReminders[i].id == lastReminder.id ) {
                  msg =  (" === found === : " + activeReminders[i].summary);
                  rmFxUtil.dump2Console ('FolderListener', msg);

                  lastReminder.messageID ="<" + messageId.replace(new RegExp(/\"/g),"") + ">";

                  reminderFox_removeElement(activeReminders, i);
                  reminderFox_insertIntoArray(activeReminders, lastReminder, i);
                  reminderFox_writeOutRemindersAndTodos(false);   // isExport
               }
            }
         }
      }
   }
}

function rmFx_setFolderListener(mode) {
	const mailSessionContractID = "@mozilla.org/messenger/services/session;1";
	const nsIMsgMailSession = Components.interfaces.nsIMsgMailSession;
	var mailSession = Components.classes[mailSessionContractID].getService(nsIMsgMailSession);
	var nsIFolderListener = Components.interfaces.nsIFolderListener;

	if (mode == "add") {
		mailSession.AddFolderListener(rmFx_FolderListener, nsIFolderListener.intPropertyChanged);
	}
	if (mode == "remove") {
		mailSession.RemoveFolderListener(rmFx_FolderListener);
	}
}
 
   /**
     *  Utilities for Messages  /////////////////////////////////////////////
<br> *  rmFxMsg ()
     *
     */
function rmFxMsg () {
} 

	rmFxMsg.Compose = function (subject, fromAddress,  toAddresses,
				priority, body, footer, refID, iCalToEmailFile, methodTyp) {
	// =========================================================================	
		if (rmFxMsg.messenger()) {
			var fromId = rmFxMsg.getIdentity (fromAddress);
	
	
			if (iCalToEmailFile != null) {	
				var msgAttachment 				= Components.classes["@mozilla.org/messengercompose/attachment;1"]
															.createInstance(Components.interfaces.nsIMsgAttachment);
				msgAttachment.temporary 		= true;
				msgAttachment.name 				= iCalToEmailFile.leafName;
				msgAttachment.contentType 		= "text/calendar;"		
				msgAttachment.contentTypeParam	= "method=" + methodTyp + "; charset=UTF-8";
	//gWTEST Darwin			msgAttachment.url 				= "file://" + iCalToEmailFile.persistentDescriptor;  
				msgAttachment.url 				= "file://" + iCalToEmailFile.path;  
			}
		  
			// mail header
	   	var composeFields = Components.classes["@mozilla.org/messengercompose/composefields;1"]
	                                 .createInstance(Components.interfaces.nsIMsgCompFields);
			composeFields.useMultipartAlternative = true;
	   
			composeFields.characterSet = "UTF-8";
			composeFields.from 			= fromId.email;
			composeFields.replyTo		= fromId.email;
			
			toAddresses = (toAddresses == "null") ? "" : toAddresses;
			composeFields.to 				= toAddresses;				// ???????????

				function exHtml(xString){
					return xString.replace(new RegExp(/</g),"&lt;").replace(new RegExp(/>/g),"&gt;")
				}
			composeFields.subject 		= subject;			
			composeFields.body 			= exHtml(body + footer);
			composeFields.priority		= priority;

			if (iCalToEmailFile != null) {
				composeFields.addAttachment(msgAttachment);
			}
			// message compose paramaters
			var msgComposeParams					= Components.classes["@mozilla.org/messengercompose/composeparams;1"]
															.createInstance(Components.interfaces.nsIMsgComposeParams);
			msgComposeParams.composeFields 	= composeFields;
			msgComposeParams.identity 			= fromId;
			msgComposeParams.format 			= Components.interfaces.nsIMsgCompFormat.Default;
			msgComposeParams.type 				= Components.interfaces.nsIMsgCompType.New;
			
			// open a composer window
			var messengerCompose = Components.classes["@mozilla.org/messengercompose;1"]
						.getService().QueryInterface(Components.interfaces.nsIMsgComposeService);						
			messengerCompose.OpenComposeWindowWithParams(null, msgComposeParams);

         try { // with Remote send this will fail, also we don't have dialog open to place the status info
			   rmFxCore.statusSet ("Send message by " + fromId.identityName + " pending." , ""); 		//gW RmFxStatusbar 
         } catch (ex) {}
	} else {
		/** -- NO 'messenger' .. (like FX) ----------------------------------- **/
		/*     calling TB -reminderFox COMPOSE:{info about what to compose}     */

		//messageString definition
		var msgString = "Subject:"  + subject 
					+ ";\n;From:"      + fromAddress 
					+ ";\n;To:"        + toAddresses 
					+ ";\n;Body:"      + body 
					+ ";\n;Footer:"    + footer 
					+ ";\n;priority:"  + priority
					+ ";\n;refID:"     + refID;
					
					
		if (iCalToEmailFile != null) {						
				msgString += ";\n;mailFile:"  + iCalToEmailFile.path;
		}
		
		msgString = escape(msgString);

		var mailApp = rmFx_MessengerApp();
		if ((mailApp == null) || (mailApp == ""))  {
			rmFxUtil.PromptAlert(reminderFox_getBundle().getString("rf.messenger.notfound"));
            return;
        }
			
		var args = new Array();   
		args [0] = "-reminderFox";
		args [1] = "COMPOSE:" + subject;
		args [2] = "-msgString"; 
		args [3] = msgString; 		// compose items to be passed
		
		try {
			go4Process.init(mailApp);
			} catch (ex) {}
		go4Process.run(false, args, args.length);

    	return;		// FX schedules TB with COMPOSE:subject -msgString msgString
	 	}
	}


	var deleteSendFileOnCompletion = true;	// this is the tmpFile, not the 'Send' folder copy

	/**
     * Send File
     *
     * @see
     *  http://mxr.mozilla.org/comm-central/source/mailnews/compose/public/nsIMsgSend.idl
     *  http://mxr.mozilla.org/comm-central/source/mailnews/compose/public/nsIMsgCompFields.idl
     *
     * @param subject       the 'subject' the mail comes with	
     * @param fromAddress   the 'FROM' address sending the msg
     * @param toAddresses   the 'TO' addresses to receive the msg (csv)
     * @param body          any message 'body' to be send
     * @param tmpFile       file object containing the message
     */
	rmFxMsg.FileSend = function ( subject, fromAddress, toAddresses, 
												priority, mailFile, refID) {
	// =========================================================================	
		if ( rmFxMsg.messenger()) {		//try	// 'in 'messenger' ??				
			// need different code for TB2 and TB3/SM2 !!!
			if("@mozilla.org/filespec;1" in Components.classes) {
				// this TB2 code
				var mailFileURL = rmFxUtil.getIOService().newFileURI(mailFile).spec;
				mailFile = Components.classes["@mozilla.org/filespec;1"]
			                       .createInstance(Components.interfaces.nsIFileSpec);
				mailFile.URLString = mailFileURL;
			} 
		
			var fromId = rmFxMsg.getIdentity (fromAddress);
		
			var composeFields = Components.classes["@mozilla.org/messengercompose/composefields;1"]
		                                 .createInstance(Components.interfaces.nsIMsgCompFields);
			composeFields.characterSet = "UTF-8";
			composeFields.to 			= toAddresses;
			composeFields.from 			= fromId.identityName;
			composeFields.replyTo		= fromId.identityName;
			
			composeFields.priority		= rmFxMsg.setPriorityString (priority);
	
			
			var messengerSend = Components.classes["@mozilla.org/messengercompose/send;1"]
		                           .createInstance(Components.interfaces.nsIMsgSend);
			messengerSend.sendMessageFile(
		   			fromId,  			/* nsIMsgIdentity */
		            fromId.key,			/* nsIMsgCompFields */
		            composeFields,		/* nsIMsgCompFields */
		            mailFile,			/* nsFileSpec */
		            deleteSendFileOnCompletion,
		            false, 				/* digest_p */
		            	 					/* nsMsgDeliverMode */
						rmFxUtil.getIOService().offline 
							?	Components.interfaces.nsIMsgSend.nsMsgQueueForLater	/* = 1 */
							:	Components.interfaces.nsIMsgSend.nsMsgDeliverNow,	/* = 0 */	
		            null,  		/* nsIMsgDBHdr msgToReplace */
		            null,  		/* nsIMsgSendListener aListener */
		            null,  		/* nsIMsgStatusFeedback aStatusFeedback */
		            "");    		/* password */
	
		} else { // if the above fails .. in 'NON messenger'

			rmFxMsg.sendwUID (refID, mailFile.path);
		}
	} 
	
	/**
	 * File Creation for message
	 * 
	 *  FX:  encodes the whole 'content' string with .encodeUTF8
	 *  TB:  NO encodes the whole 'content'
	 */
	rmFxMsg.FileCreate = function (subject, fromAddress, toAddresses, priority, 
										body, footer, 
										refID, iCalString, methodTyp) {
	//===================================================================== 
		var thisdate = new Date();
	
		// add app info  .. will be added to the 'footer'
		var osInfo = rmFx_opSystemInfo();
		var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] 
			.getService(Components.interfaces.nsIXULAppInfo);
		var appDetails = "\n  " + appInfo.name + " " + appInfo.version 
						     + " (" + appInfo.platformBuildID + ") -- " + osInfo;

		var content =     "MIME-version: 1.0\r\n";
		content +=        "To: " 	+ toAddresses + "\r\n";
		
		if ( rmFxMsg.messenger()) {
			var contentS = "Subject: " + rmFxMsg.encodeMimeHeader(subject) + "\r\n";  
			contentS +=    "From: " 	+ rmFxMsg.getIdentity (fromAddress).identityName + "\r\n"; 
		} else {
			var contentS = "Subject: " + subject + "\r\n";
			contentS +=    "From: " 	+ fromAddress + "\r\n";  
		} 
		content += contentS;
		
		content += "Date :" + rmFxCore.mailDateTime(thisdate, "mailDate") + "\r\n";	
		content += rmFxMsg.setPriorityString(priority) + "\r\n";
		content += "Content-class: urn:content-classes:reminderfox\r\n";

		var newDate = new Date();
		var msgId = reminderFox_generateUniqueReminderId( newDate );
		
		if (refID != "") {
			content
			+= "Reference-ID: <" + refID + rmFx_ReferenceID + ">\r\n"
			 + "In-Reply-To: <" + refID + rmFx_ReferenceID + ">\r\n";
			 + "Message-Id: <" + msgId + rmFx_ReferenceID + ">\r\n";
		//gw_messageID/In-Reply-To w send/reply invitation
		}
		
		// if 'iCalString' and 'methodTyp'  send with iCal attachment		
		if (!!iCalString && !!methodTyp) {
			content	
			+= ("Content-type: multipart/mixed; boundary=\"anhang_1234567890_0987654321\"\r\n"
         +      "\r\n\r\n"
         +      "--anhang_1234567890_0987654321\r\n"
         +      "Content-type: multipart/alternative;\r\n"
         +      " boundary=\"anhang_0987654321_1234567890\"\r\n"
         +      "\r\n\r\n"
         +      "--anhang_0987654321_1234567890\r\n"
         +      "Content-type: text/plain; charset=UTF-8\r\n"
         +      "Content-transfer-encoding: 8BIT\r\n"
         +      "\r\n"
         
         +      body 

		 + "\n-- "  /* footer delimiter line !!! do not delete !  
	      					 this notation will cut the following part from plain-text-reply !*/
		 +  "\n" + footer + appDetails  
	     +  "\n  ________________________________________________"
         +  "\n  " + REMINDER_FOX_PAGE_URL + "\n"

         +      "\r\n\r\n\r\n"
         +      "--anhang_0987654321_1234567890\r\n"
         +      "Content-type: text/calendar; method=" + methodTyp + "; charset=UTF-8\r\n"
         +      "Content-transfer-encoding: 8BIT\r\n"
         +      "\r\n"
         
         +      iCalString
         +      "\r\n\r\n"
         
         +      "--anhang_0987654321_1234567890--\r\n\r\n"

         +      "--anhang_1234567890_0987654321\r\n"
         +      "Content-type: application/ics; name=invite.ics\r\n"
         +      "Content-transfer-encoding: 8BIT\r\n"
         +      "Content-disposition: attachment; filename=invite.ics\r\n"
         +		"\r\n"    /* need an extra line to separate header !! */
         
         +      iCalString	
         +      "\r\n\r\n"
         
         +      "--anhang_1234567890_0987654321--\r\n");
			
		} else {	// send message with inline text
		
			content 
			+= "Content-type: text/plain; charset=UTF-8\r\n" 
			+	"Content-transfer-encoding: 8bit\r\n\r\n" 
			+  body
			 
			+  "\n-- "  /* footer delimiter line !!! do not delete !  
	      					 this notation will cut the following part from plain-text-reply !*/
			+  "\n" + footer + appDetails
			+  "\n  ________________________________________________"
			+  "\n  http://www.reminderfox.org/\n";
		}
		
		if ( !rmFxMsg.messenger()) {
			content = rmFxUtil.encodeUTF8(content);
		}
			
		// ------ write TMP file ---------------
		return  rmFxUtil.makeMsgFile8 (content, rmFxUtil.buildUIDFile(refID));
	}



	rmFxMsg.setPriorityString = function (priority) {
	// =========================================================================
		var cPriority = "";
		switch (priority) {
		case "1":	cPriority		= "X-Priority: 1 (Highest)";	break;					
		case "2":	cPriority		= "X-Priority: 2 (High)"; break;
		case "3":	cPriority		= "X-Priority: 3 (Normal)"; break;
		case "4":	cPriority		= "X-Priority: 4 (Low)"; break;
		case "5":	cPriority		= "X-Priority: 5 (Lowest)"; break;
		default: cPriority		= "X-Priority: 3 (Normal)"; break;
		}
		return cPriority;
	}
	

/////////////////// 'SendFILE' for "NON" messenger   ///////////////////////////
	/**
	 *	use a specific 'commandLine' Handler ... this is the NON 'messenger' part
	 */
	 rmFxMsg.sendwUID = function (reminderID, msgString) {
	// =========================================================================	
		var mailApp = rmFx_MessengerApp();
		if ((mailApp == null) || (mailApp == ""))  {
			rmFxUtil.PromptAlert(reminderFox_getBundle().getString("rf.messenger.notfound"));
            return;
        }
		var osInfo = rmFx_opSystemInfo();

		var args = new Array();   
		args [0] = "-reminderFox";
		args [1] = "UID:"+ (reminderID);
		args [2] = "-msgString"; 

                        //gWTEST platformIsMac; STEEL ????????????                        
		if(osInfo.indexOf("Darwin") != -1) {
			args [3] = Components.classes["@mozilla.org/file/directory_service;1"]
			    .getService(Components.interfaces.nsIProperties)
				.get("TmpD", Components.interfaces.nsIFile);
		} else {
			args [3] = Components.classes["@mozilla.org/file/directory_service;1"]
				.getService(Components.interfaces.nsIProperties)
				.get("Progs", Components.interfaces.nsIFile).path.substring(3);
		}
				
		var cDate = new Date();
		var msgLog = " ** Send with **   UID:" + reminderID + " at: " + cDate;
		rmFxCore.statusSet(msgLog);
		
		try {
			go4Process.init(mailApp);
			} catch (ex) {}
		go4Process.run(false, args, args.length);
		
    	return;		// scheduled TB with UID:reminderID -msgString mailFile.path
    }   
    
    /**
     * 	called from 'commandLine' Handler ... this is the 'messenger' part
     */
	rmFxMsg.sendwUIDgo = function () {
	// ========================================================================
		if (!(rmFx_cmdID.indexOf('UID:') > -1)) { // check transfered code and validity
			return;	// not valid!! Terminate
		}
		window.close();

		var icsFile = rmFxUtil.buildUIDFile(rmFx_cmdID.substring(4))
		
	rmFxUtil.dump2Console ( 'Darwin', "sendwUIDgo icsFile >>" + icsFile + "<<");			//gWTEST Darwin	sendwUIDgo

		
		var icsData = rmFxUtil.readInFileContents(icsFile)
	   						.replace(/(\r\n)/g,"\n");

		if (icsData.indexOf (rmFx_cmdID+"\n") == -1) {
			var msgError = "*** Transfered ICS data has error: -1 ***" 
					+ "\n   data >>" +  rmFx_cmdID + "<<"; 
			rmFxUtil.dump2Console ('error', msgError);
			return;	// not valid!! Terminate
		}
	
		
	/* ----- check if file valid -----   +++2Todo 	 +++2Todo 	 +++2Todo 	 +++2Todo
		var osInfo = rmFx_opSystemInfo();		<<-- with Darwin fails !!
		if(osInfo.indexOf("Darwin") == -1) { 

			if (rmFx_cmdString !=  Components.classes["@mozilla.org/file/directory_service;1"]
						.getService(Components.interfaces.nsIProperties)
						.get("Progs", Components.interfaces.nsIFile).path.substring(3)) {
				var msgError = "*** Transfered ICS data has error: -2 ***";
	 
				rmFxUtil.dump2Console ('error', msgError);
				return;	// not valid!! Terminate
			}
		} else {
			if (rmFx_cmdString !=  Components.classes["@mozilla.org/file/directory_service;1"]
						.getService(Components.interfaces.nsIProperties)
						.get("TmpD", Components.interfaces.nsIFile).path.substring(3)) {
				var msgError = "*** Transfered ICS data has error: -2 (Darwin) ***";
	 
				rmFxUtil.dump2Console ('error', msgError);
				return;	// not valid!! Terminate
			}
		}
	-------------- */

	   var msgString = rmFx_cmdString.split(";\n;");
	
		// retrieve msg infos from 'ics file'  
	   var msgLines = icsData.split("\n");
	   						
	   var toAddresses	= msgLines[1].substring(4);
	   var subject 		= msgLines[2].substring(9);
	   var fromAddress	= msgLines[3].substring(6);
	   var priority 	= msgLines[5].substring(12,13);

		rmFxUtil.makeMsgFile (msgLines.join("\n"), icsFile);	 
	 
		var mailFile = Components.classes["@mozilla.org/file/local;1"]
					.createInstance(Components.interfaces.nsILocalFile);                              
		mailFile.initWithPath(icsFile);
	   
		rmFxMsg.FileSend(
					subject,
					fromAddress, 
					toAddresses, 
					priority, 
					mailFile);	
	}

//////////////////// 'COMPOSE' for NON 'messenger'   ///////////////////////////

    /**
     *   use a specific 'commandLine' Handler ... this is the NON 'messenger' part
     * 
     */
    rmFxMsg.composeMSG = function (reminderID, msgString) {
    // =========================================================================
	var mailApp = rmFx_MessengerApp();
	if ((mailApp == null) || (mailApp == ""))  {
		rmFxUtil.PromptAlert(reminderFox_getBundle().getString("rf.messenger.notfound"));
           return;
        }
		
	var args = new Array();   
	args [0] = "-reminderFox";
	args [1] = "COMPOSE:"+ (reminderID);
	args [2] = "-msgString"; 
	args [3] = msgString;
		
	try {
		go4Process.init(mailApp);
	} catch (ex) {}
	go4Process.run(false, args, args.length);
    	return;		// FX schedules TB with COMPOSE:reminderID -msgString msgString
    }   
    
    /**
     *  called from 'commandLine' Handler ... this is the 'messenger' part
     */
    	rmFxMsg.composeMSGgo = function () {
    	// =========================================================================
    	    if (!(rmFx_cmdID.indexOf('COMPOSE:') > -1)) { // check transfered code and validity
		return;	// not valid!! Terminate
    	    }
    	    window.close();

    	    // retrieve msg infos from passed window parameters
    	    var msgString = unescape(rmFx_cmdString).split(";\n;");
		
    	    var subject       = msgString[0].substring(8);
    	    var fromAddress   = msgString[1].substring(5);
    	    var toAddresses   = msgString[2].substring(3);
    	    var body          = msgString[3].substring(5);
    	    var footer        = msgString[4].substring(7);
    	    var priority      = msgString[5].substring(9);
    	    var refID         = msgString[6].substring(6);
	   
    	    rmFxUtil.dump2Console('Darwin', "composeMSGgo icsFile string >>" + msgString[7] + "<<");			//gWTEST Darwin
		
    	    if (msgString[7] != null) {
    		var icsFile       = msgString[7].substring(9);
    		var mailFile = Components.classes["@mozilla.org/file/local;1"]
						.createInstance(Components.interfaces.nsILocalFile);                              
    		mailFile.initWithPath(icsFile);  
    	    } else {
        	    mailFile = null;
    	    }
	   
	// var toAddresses   = "";
	var methodTyp     = "PUBLISH";
		
	rmFxMsg.Compose (subject, fromAddress,  toAddresses,
		priority, body, footer, refID, mailFile, methodTyp);
	}


//////////////////// utilities 'messenger' /////////////////////////////////////

	rmFxMsg.messenger = function () {
	// =========================================================================
	    return (Components.classes["@mozilla.org/messenger/account-manager;1"] != null);
	}

	rmFxMsg.getAccountMngr = function  () {
	// =========================================================================
	    return Components.classes["@mozilla.org/messenger/account-manager;1"]
				.getService().QueryInterface(Components.interfaces.nsIMsgAccountManager);
	}
	
	rmFxMsg.encodeMimeHeader = function (header) {
	// =========================================================================
	// http://www.xulplanet.com/references/xpcomref/ifaces/nsIMimeConverter.html
	   var mimeConverter = Components.classes["@mozilla.org/messenger/mimeconverter;1"]
	                                  .createInstance(Components.interfaces.nsIMimeConverter);
	   return mimeConverter.encodeMimePartIIStr(rmFxUtil.encodeUTF8(header), false, 
						"UTF-8", header.indexOf(":") + 2, 72);
	}

	/**
	 *   'messenger'       use mail.accountmanager.accounts and identities
	 *   NON 'messenger'   prefs = extensions.reminderFox.mail.sender
	 */
	rmFxMsg.myMailIDs = function () {
	// =========================================================================
	if (rmFxMsg.messenger()) // OK: if we are in 'mail' system (TB, SM)

		{ 	// this is tree pass process to eliminate identities for 'nntp'
			//  sounds complicate ... but didn't found a straight forward process   
			var as = Components.classes["@mozilla.org/messenger/account-manager;1"]
		   	.getService(Components.interfaces.nsIMsgAccountManager).allServers;
			var servers="";
			for (var i = 0; i < as.Count(); ++i) {
				var nextTyp  = as.GetElementAt(i)
					.QueryInterface(Components.interfaces.nsIMsgIncomingServer).type;
				if (nextTyp != "nntp") {
					var nextKey  = as.GetElementAt(i)
						.QueryInterface(Components.interfaces.nsIMsgIncomingServer).key;
					servers += nextKey +",";
				}
			}

			var _prefs = Components.classes["@mozilla.org/preferences-service;1"].
		            getService(Components.interfaces.nsIPrefBranch);	
			var accounts = _prefs.getCharPref("mail.accountmanager.accounts");
	
		   var idstr=""; 
			if (accounts) {
			    var accountsArray = accounts.split(",");    
			    for (var x = 0; x < accountsArray.length; x++) {
					var temp1 = _prefs.getCharPref("mail.account." + accountsArray[x] + ".server");
					if (servers.indexOf(temp1)> -1) { 
					try { idstr += _prefs.getCharPref("mail.account." + accountsArray[x] 
							+ ".identities") +",";}
						catch (ex) {}
					}
				}
			}

			var ids = Components.classes["@mozilla.org/messenger/account-manager;1"].
		                  getService(Components.interfaces.nsIMsgAccountManager).allIdentities;	
			var mailIds = "";
			for (var i = 0; i < ids.Count(); ++i) {
				var nextId  = ids.GetElementAt(i).
									QueryInterface (Components.interfaces.nsIMsgIdentity);
					if (idstr.indexOf(nextId.key)> -1) { 			
						try { mailIds += nextId.identityName + ",";}
							catch (ex) {}
					}
			}
			// delete last comma
			mailIds = mailIds.substring(0,mailIds.length-1);

		} else { // 'NON messenger' .. eg.FX etc ...
			try {
				var mailIds = reminderFox_prefsBranch.getCharPref(REMINDER_FOX_MAIL_SENDER);
			} catch (ex) {}
		}
		return mailIds;
	}

	/** 
	 *	checks all non-nntp servers for valid 'fromAddress'
	 * 	returns the 'identity'
	 * 	If not matching 
	 * 		-- not valid mailName --> take first valid identity for that server
	 * 		-- at all, take 'defaultAccount.defaultIdentity'
	 * 
	 * 	in NON 'messenger' just return the 'fromAddress'
	 */
	rmFxMsg.getIdentity = function (fromAddress) {
	// =========================================================================
		var ids = Components.classes["@mozilla.org/messenger/account-manager;1"].
		                  getService(Components.interfaces.nsIMsgAccountManager).allIdentities;
		if ((fromAddress != null ) &&  (fromAddress != "" )) {
			var returnId = null;
			var xMailAdr ="x";
			var xId = -1;
			for (var i = 0; i < ids.Count(); ++i) {
		
				var nextId  = ids.GetElementAt(i).
									QueryInterface (Components.interfaces.nsIMsgIdentity);
				if ((fromAddress.indexOf(nextId.email) > -1) && (xMailAdr != nextId.email)){
					xMailAdr =nextId.email;
					xId = i;
				}
				if (nextId.identityName == fromAddress) {return nextId;}
			}
		}
	//	return ids.GetElementAt(xId).
	//								QueryInterface (Components.interfaces.nsIMsgIdentity);
	
			// not found at all, return default
		return  rmFxMsg.getAccountMngr().defaultAccount.defaultIdentity;
	}
	 
	 
    /**
    * Checks for the messenger version (TB2, TB3, SM, PB) 
    * and sets the global parameter 'gRmFx_Messenger'
    *
    * @note  this function has to be stored in mail.js for 'remote'
    * access of 'compose', search with 'UID' and 'msgID'
    *  
    * @return   gRmFx_Messenger
    */
    rmFxMsg.whichMessenger = function () {
    // =========================================================================

       var REMINDERFOX_SEAMONKEY_ID = "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}";
       var REMINDERFOX_THUNDERBIRD_ID = "{3550f703-e582-4d05-9a08-453d09bdfdc6}";
       var REMINDERFOX_POSTBOX_ID = "postbox@postbox-inc.com";
        
       var idName = "";
       if (gRmFx_Messenger == null) {
        
            // https://developer.mozilla.org/en/Using_nsIXULAppInfo
            var id;
            if("@mozilla.org/xre/app-info;1" in Components.classes) {
                // running under Mozilla 1.8 or later
                id = Components.classes["@mozilla.org/xre/app-info;1"]
                               .getService(Components.interfaces.nsIXULAppInfo).ID;
            } else {
                try {
                    id = Components.classes["@mozilla.org/preferences-service;1"]
                                 .getService(Components.interfaces.nsIPrefBranch)
                                 .getCharPref("app.id");
                } catch(e) {}
            }
            
            var _prefs = Components.classes["@mozilla.org/preferences-service;1"]
                                            .getService(Components.interfaces.nsIPrefBranch); 
            switch (id) {
                case (REMINDERFOX_POSTBOX_ID) :     idName = "PB"; break;
                case (REMINDERFOX_SEAMONKEY_ID) : {  
                   var tbVersion = _prefs.getCharPref("general.useragent.extra.seamonkey");
                    if (tbVersion.search("/1.") > -1) idName = "SM1";
                    if (tbVersion.search("/2.") > -1) idName = "SM2";
                   break;
                }  
                case (REMINDERFOX_THUNDERBIRD_ID) :  {
                    var tbVersion = _prefs.getCharPref("general.useragent.extra.thunderbird");
                            
                    if (tbVersion.search("/1.") > -1) idName = "TB1";
                    if (tbVersion.search("/2.") > -1) idName = "TB2";
                    if (tbVersion.search("/3.") > -1) idName = "TB3";
                    break;
                }
            }

	        gRmFx_AB3 = (idName == "TB3") || (idName == "SM2"); //  || (msgnrType == "PB")); 
	        gRmFx_Messenger = idName;
        }
        var msg = "gRmFx_Messenger: " + gRmFx_Messenger + "   gRmFx_AB3: " + gRmFx_AB3;        
        rmFxUtil.dump2Console ('gRmFx', msg);

        return gRmFx_Messenger;
    }