/**  
 * Send++    add a 'reminder' with sending a message
 * 			
 * @since
 * 	2008-08-04	Send++  FCC version with Listener to catch the msgId and write to Reminder
 */
function rmFx_msgSendwReminder () {	
// -----------------------------------------------------------
	// clear reminders from memory
	reminderFox_clearRemindersAndTodos();
	var reminders = reminderFox_getReminderEvents();	

	// --- setup an Listener so we can catch the messageId 
	var identity = gAccountManager.getIdentity(document.getElementById("msgIdentity").value);
	rmFx_FCC 	= identity.fccFolder;	// remember 'send folder' for account

	rmFx_setFolderListener("add");
	
	// --- generate Reminder for message
	var newDate = new Date();
	newDate.setDate(newDate.getDate() + 1);	// default to using tomorrow's date for reminder
	var rmFx_SwRm_Reference = reminderFox_generateUniqueReminderId(newDate);

	var org_References = gMsgCompose.compFields.references;
	if (gMsgCompose.compFields.references == null || gMsgCompose.compFields.references == "") {
		gMsgCompose.compFields.references  =  "<" + rmFx_SwRm_Reference + rmFx_ReferenceID +">";
	} else {
		gMsgCompose.compFields.references += " <" + rmFx_SwRm_Reference + rmFx_ReferenceID +">";
	}
	
	var mailIdentifierString = "[" + reminderFox_getBundle().getString("rf.sendw.label") + "++]";
	
	var _subject = GetMsgSubjectElement().value;
	var newReminderToBeAdded = new ReminderFoxEvent
		( rmFx_SwRm_Reference, newDate, mailIdentifierString + " " +_subject); //+ gMsgSubjectElement.value );

	var msgCompFields = gMsgCompose.compFields;
	Recipients2CompFields(msgCompFields);

	newReminderToBeAdded.notes  = reminderFox_getBundle().getString("rf.add.mail.message.sender")	 
			+ ": " + identity.email  +  "\n";
	newReminderToBeAdded.notes +=	reminderFox_getBundle().getString("rf.add.mail.message.recipients")
			+ ": " + msgCompFields.to +  "\n";
		if (msgCompFields.cc != "") {
			newReminderToBeAdded.notes += "    CC:" + msgCompFields.cc + "\n";
		}
		if (msgCompFields.bcc != "") {
			newReminderToBeAdded.notes += "   BCC:" + msgCompFields.bcc + "\n";
		}
		
	var mailDate = new Date();
	mailDate.setDate(mailDate.getDate());   
	newReminderToBeAdded.notes += reminderFox_getBundle().getString("rf.add.mail.message.date")    	 
			+ ": " + rmFxMsgHdrDate(mailDate*1000) +  "\n";
	
	// TB PRIORITY definition converted for RmFx 	
	// the value is not language dependant!!  but the label="&highestPriorityCmd.label;"
	// = [string] "Highest"	= [string] "High"		===>> RmFx 'Important'=1
	// = [string] "Normal"
	// = [string] "Low"		= [string] "Lowest"
	
	if ((msgCompFields.priority == "Highest") || (msgCompFields.priority == "High")) {
			newReminderToBeAdded.priority = 1;		// set RmFx 'Important'=1
	}
	var added = reminderFox_addReminderHeadlessly(newReminderToBeAdded, false );

	if (added == false) {	// [CANCEL] NOT 'added' --> reset the 'References' and don't send
			gMsgCompose.compFields.references = org_References;
	} else {
		// now send the msg

		// msgID will be reset  with nsIMsgCompDeliverMode.Now and .Later 
		// using .Later will store the msg to the FCC Folder
		// before finally sending catch the msgId from for the reminder using Listener
		try {
         GenericSendMessage(nsIMsgCompDeliverMode.Now, true);  // second parameter for PB
		} catch (e) {}
	}
}


///////////////////// -- open messages with  reminder reference -- /////////////
/*	 Open a reminder with the "Edit Reminder" dialog using the 
 *	 msgHdr "References" entry to check the "reminder-ID'.
 *	 a) for search with 'References'
 *	 b) for search of 'reminder.id'
 * 
 *	 "Send with Reminder" adds an item 'References' to the message header
 *	 'reference-ID' :	"[string]@reminderfox"
 *	  - [string] build with reminderfox functions using time and random number,
 *		  this [string] will also being used for reminders UID
 * 
 *	 A normal reply to such a msg will hold that header item value.  
 *	 This function will check for this reference-ID and use any such entry for 
 *	 a search and found-&-open of the initial reminder.
 *	 If multiple references are found a dialog with those reminder references
 *	 are displayed for selection.
 **/
function rmFxReminder4mailOpen(){
	
	var msgHdr = gDBView.hdrForFirstSelectedMessage;
	
	var rmRef=rmFxGetRmRef(msgHdr); // for matched 'References' and 'message-Id' in reminder list
	if (rmRef.length == -1) {return}

	var activeReminders = reminderFox_getReminderEvents();	
	
	if (rmRef.length == 1) {	
			rmFxOpenReminder(rmRef[0], msgHdr.messageId);
	} else { // multiple 'References' entries in a msg found, display them for selection
		var remOptions = { rmReferences : rmRef,
				msgSubject: msgHdr.subject, msgDate: msgHdr.date, msgFrom: msgHdr.author};
		var dlg = window.openDialog("chrome://reminderfox/content/mail/rmFxSendwReminderList.xul",
						"rmFxReminder4mailList", "chrome,centerscreen,resizable,dialog=no",  remOptions);
	}	
}	


function  rmFx_go4it() {   
    var curMsg = document.getElementById('rmFx_ReferencesListbox');
    /*    
	  WINxP and LINUX have different behavior accessing the seletion _
	    WINxp  uses curMsg.currentIndex
	    LINUX  uses curMsg.selectedIndex
	*/
    var currentIndex = -1;
    if (curMsg.currentIndex != null) {
        currentIndex = curMsg.currentIndex;
    } else {
        currentIndex = curMsg.selectedIndex;         
    }
    if (currentIndex == -1) {
        window.close(); // no item selected
        return;
    }
    var selcReminder = window.arguments[0].rmReferences[currentIndex];
    rmFxOpenReminder(selcReminder);
}
	
function rmFxOpenReminder(selcReminder) {   //, messageId){
	// search  for current msgID, if found open that event	
	
	// search in 'reminder' list 
	var activeReminders = reminderFox_getReminderEvents();
	for ( var i = 0; i < activeReminders.length; i++ ) {
		if (activeReminders[i].id ==selcReminder.id) {
			activeReminders[i].messageID = selcReminder.messageID // '<' + messageId + '>';

			//gWtodo open the RL 2010-02-13
			reminderFox_openAddRemindersDialog();
			var added = reminderFox_editEventHeadlessly(activeReminders[i].id, activeReminders[i],true);
			return;
		}
	}	
	// search in 'todo' lists 

	var reminderFoxTodosArrayArg =  reminderFox_getReminderTodos();
	for ( var n in reminderFoxTodosArrayArg ) {
		var todoList = reminderFoxTodosArrayArg[n];
		
	  	for ( var m in todoList ) {	
			if (todoList[m].id == selcReminder.id) {
			var added = reminderFox_editEventHeadlessly(todoList[m].id, todoList[m],false);
			return;
			}
		}
	}

	alert (reminderFox_getBundle().getString("rf.sendw.reminder.error"));	
}

function rmFxReminder4mailList() {
	var subject = window.arguments[0].msgSubject;
	document.getElementById('idSubject')
		.setAttribute("value", reminderFox_getBundle().getString("rf.add.mail.message.subject") +": " + subject);
	
	var author = window.arguments[0].msgFrom;
	document.getElementById('idFrom')
		.setAttribute("value", reminderFox_getBundle().getString("rf.add.mail.message.from") +": " + author);

	var msgDate = rmFxMsgHdrDate (window.arguments[0].msgDate);
	document.getElementById('idDate')
		.setAttribute("value", reminderFox_getBundle().getString("rf.add.mail.message.date") +": "  + msgDate); 
	
	var reminders = window.arguments[0].rmReferences;
	var remNo = window.arguments[0].rmReferences.length;

	for (var n=0; n < remNo; n++) {
		rmFxRListaddItem(n, 
			reminders[n].id,		reminders[n].summary,
			reminders[n].date,	reminders[n].notes);	
	}
}

function rmFxRListaddItem(n, msgId, subject, dateStr, notes) {
/*  this generate the list entries in form of:
		<richlistitem id="rmFxRefList" value="3333356789-1233"  
					style="border-bottom: 1px dotted sienna;">
			<vbox>
				<label value="Reminder's subjectXXXXX" style="font-weight: bold"/>
				<hbox><spacer width="20px"/><label value="Do 05.02.2008 13:30"/></hbox>
				<hbox><spacer width="20px"/><label value="Notes: xxxxxxxxxxxx"/></hbox>		
			</vbox>
		</richlistitem>
*/
		var rlBox = document.getElementById('rmFx_ReferencesListbox');
		var rlItem = document.createElement("richlistitem");
		rlBox.appendChild(rlItem);
			rlItem.setAttribute("id" , "rlItem" + n);
			rlItem.setAttribute("value" , msgId);
			rlItem.setAttribute("style" , "border-bottom: 1px dotted sienna;");

			var vbox0 = document.createElement("vbox");
			rlItem.appendChild(vbox0);
				vbox0.setAttribute("id" , "vbox0" + n);
				if (n == 1) {
					vbox0.setAttribute("selected" , "true" );
				}

		// RmFx subject
				var labelS = document.createElement("label");
				vbox0.appendChild(labelS);
					labelS.setAttribute("value",  subject);
					labelS.setAttribute("style" , "font-weight: bold");
		// RmFx date
				var hboxD = document.createElement("hbox");
				vbox0.appendChild(hboxD);
					var spacer1 = document.createElement("spacer");
					hboxD.appendChild(spacer1);
					spacer1.setAttribute("width" , "20px");
					
					var labelD = document.createElement("label");
					var bText= reminderFox_getBundle().getString("rf.add.mail.message.date")
					hboxD.appendChild(labelD);
					reminderFox_parseDateTimes(dateStr)
					labelD.setAttribute("value" , bText + ": " + rmFxMsgHdrDate(dateStr*1000));	
					
		// RmFx notes	
				if (notes != null ) {		
				var hboxN = document.createElement("hbox");
				vbox0.appendChild(hboxN);
					var spacer1 = document.createElement("spacer");
					hboxN.appendChild(spacer1);
					spacer1.setAttribute("width" , "20px");
					var labelN = document.createElement("label");
					hboxN.appendChild(labelN);
					var bText= reminderFox_getBundle().getString("rf.add.mail.message.notes")
					labelN.setAttribute("value" , bText + ": " ); 
					
					var notesArr = notes.split("\n");
					try { // just show the first three lines here 
						for (i=0; i< 3; i++){
							var hboxN = document.createElement("hbox");
							vbox0.appendChild(hboxN);
							var spacer1 = document.createElement("spacer");
							hboxN.appendChild(spacer1);
							spacer1.setAttribute("width" , "30px");

							var labelN = document.createElement("label");
							hboxN.appendChild(labelN);
							labelN.setAttribute("value" , notesArr[i]); 
						}
					} catch (e) {}
				}
}

// Get an array with reminders with an UID to be part of the 'References' 
// entry in the message header data
//   param:  msgHdr  
//     if not passed with call, take the msgHdr from the first selected message 
//
function rmFxGetRmRef(msgHdr) {
	if ((msgHdr == "") || (msgHdr == null)) {
		msgHdr = gDBView.hdrForFirstSelectedMessage;
	}
	//	build 'References' string for reminder.id search
	var rmReferences = new Array();
	var refString="";
	
	if ((msgHdr.numReferences > 0)) {
		for (var n=0; n< msgHdr.numReferences; n++) { 
 		//	msgHdr.getStringReference(n) = "1202409095568-924858015@reminderfox"
			if (msgHdr.getStringReference(n).indexOf(rmFx_ReferenceID) > -1) {
					refString += msgHdr.getStringReference(n)
						.substring(0,msgHdr.getStringReference(n).indexOf("@"))+",";	
			}
		}
	} 
	//  check 'reminder.id' 
	// strip out quotes as the extractHeader method returns some 
	// message-id's with extraneous quotes
	// like: "000c01c6941b$6ddb3c30$7be040"@foo.com
	var messageId = "<" +  msgHdr.messageId.replace(new RegExp(/\"/g),"") + ">";
	
	// check 'reminders'
	var j=0;
	var reminderFoxEvents = reminderFox_getReminderEvents();
	for ( var i = 0; i < reminderFoxEvents.length; i++ ) {
		if ((reminderFoxEvents[i].messageID ==  messageId )
				|| (refString.indexOf(reminderFoxEvents[i].id) > -1)){
			rmReferences[j] = reminderFoxEvents[i];
			rmReferences[j].messageID = messageId
			j++;
		}
	}

	// check 'todos'
	var reminderFoxTodosArrayArg =  reminderFox_getReminderTodos();
	for ( var n in reminderFoxTodosArrayArg ) {
		var todoList = reminderFoxTodosArrayArg[n];

		for ( var m in todoList ) {
			if ((todoList[m].messageID == messageId) 
					|| (refString.indexOf(todoList[m].id) > -1)){
				rmReferences[j] = todoList[m];
				rmReferences[j].messageID = messageId;
				j++;
			}
		}
	}

	return rmReferences;    // return an array of all matching reminders and todos
}
