home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / mozil06.zip / bin / chrome / messenger.jar / content / messenger / messengercompose / MsgComposeCommands.js < prev    next >
Text File  |  2001-02-14  |  49KB  |  1,685 lines

  1. /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2.  * The contents of this file are subject to the Netscape Public
  3.  * License Version 1.1 (the "License"); you may not use this file
  4.  * except in compliance with the License. You may obtain a copy of
  5.  * the License at http://www.mozilla.org/NPL/
  6.  * 
  7.  * Software distributed under the License is distributed on an "AS
  8.  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  9.  * implied. See the License for the specific language governing
  10.  * rights and limitations under the License.
  11.  * 
  12.  * The Original Code is Mozilla Communicator client code, released
  13.  * March 31, 1998.
  14.  * 
  15.  * The Initial Developer of the Original Code is Netscape
  16.  * Communications Corporation. Portions created by Netscape are
  17.  * Copyright (C) 1998-1999 Netscape Communications Corporation. All
  18.  * Rights Reserved.
  19.  */
  20.  
  21. var msgCompDeliverMode = Components.interfaces.nsIMsgCompDeliverMode;
  22. var msgCompSendFormat = Components.interfaces.nsIMsgCompSendFormat;
  23. var msgCompConvertible = Components.interfaces.nsIMsgCompConvertible;
  24. var msgCompType = Components.interfaces.nsIMsgCompType;
  25.  
  26. var accountManagerContractID   = "@mozilla.org/messenger/account-manager;1";
  27. var accountManager = Components.classes[accountManagerContractID].getService(Components.interfaces.nsIMsgAccountManager);
  28.  
  29. //var mailSessionContractID   = "@mozilla.org/messenger/services/session;1";
  30. //var mailSession = Components.classes[mailSessionContractID].getService(Components.interfaces.nsIMsgMailSession);
  31.  
  32. var messengerMigratorContractID   = "@mozilla.org/messenger/migrator;1";
  33.  
  34. var msgComposeService = Components.classes["@mozilla.org/messengercompose;1"].getService();
  35. msgComposeService = msgComposeService.QueryInterface(Components.interfaces.nsIMsgComposeService);
  36.  
  37. var commonDialogsService = Components.classes["@mozilla.org/appshell/commonDialogs;1"].getService();
  38. commonDialogsService = commonDialogsService.QueryInterface(Components.interfaces.nsICommonDialogs);
  39.  
  40. var msgCompose = null;
  41. var MAX_RECIPIENTS = 0;
  42. var currentAttachment = null;
  43. var documentLoaded = false;
  44. var windowLocked = false;
  45. var contentChanged = false;
  46. var currentIdentity = null;
  47. var defaultSaveOperation = "draft";
  48.  
  49. var Bundle = srGetStrBundle("chrome://messenger/locale/messengercompose/composeMsgs.properties"); 
  50.  
  51. var other_header = "";
  52. var update_compose_title_as_you_type = true;
  53. var sendFormat = msgCompSendFormat.AskUser;
  54. var prefs = Components.classes["@mozilla.org/preferences;1"].getService();
  55. if (prefs) {
  56.     prefs = prefs.QueryInterface(Components.interfaces.nsIPref);
  57.     if (prefs) {
  58.         try {
  59.             update_compose_title_as_you_type = prefs.GetBoolPref("mail.update_compose_title_as_you_type");
  60.         }
  61.         catch (ex) {
  62.             dump("failed to get the mail.update_compose_title_as_you_type pref\n");
  63.         }
  64.         try {
  65.             other_header = prefs.CopyCharPref("mail.compose.other.header");
  66.         }
  67.         catch (ex) {
  68.              dump("failed to get the mail.compose.other.header pref\n");
  69.         }
  70.     }
  71. }
  72.  
  73. var stateListener = {
  74.     NotifyComposeFieldsReady: function() {
  75.         documentLoaded = true;
  76.     },
  77.  
  78.     SendAndSaveProcessDone: function() {
  79.         dump("\n RECEIVE SaveAndSendProcessDone\n\n");
  80.         windowLocked = false;
  81.       CommandUpdate_MsgCompose();
  82.     }
  83. };
  84.  
  85. // i18n globals
  86. var currentMailSendCharset = null;
  87. var g_send_default_charset = null;
  88. var g_charsetTitle = null;
  89.  
  90.  
  91. var defaultController =
  92. {
  93.   supportsCommand: function(command)
  94.   {
  95.     switch (command)
  96.     {
  97.       //File Menu
  98.       case "cmd_attachFile":
  99.       case "cmd_attachPage":
  100.       case "cmd_close":
  101.       case "cmd_saveDefault":
  102.       case "cmd_saveAsFile":
  103.       case "cmd_saveAsDraft":
  104.       case "cmd_saveAsTemplate":
  105.       case "cmd_sendNow":
  106.       case "cmd_sendLater":
  107.       case "cmd_quit":
  108.       
  109.       //Edit Menu
  110.       case "cmd_pasteQuote":
  111.       case "cmd_find":
  112.       case "cmd_findNext":
  113.       case "cmd_account":
  114.       case "cmd_preferences":
  115.       
  116.       //View Menu
  117.       case "cmd_showComposeToolbar":
  118.       case "cmd_showFormatToolbar":
  119.  
  120.       //Insert Menu
  121.       case "cmd_insert":
  122.       case "cmd_link":
  123.       case "cmd_anchor":
  124.       case "cmd_image":
  125.       case "cmd_hline":
  126.       case "cmd_table":
  127.       case "cmd_insertHTML":
  128.       case "cmd_insertChars":
  129.       case "cmd_insertBreak":
  130.       case "cmd_insertBreakAll":
  131.  
  132.       //Format Menu
  133.       case "cmd_format":
  134.       case "cmd_decreaseFont":
  135.       case "cmd_increaseFont":
  136.       case "cmd_bold":
  137.       case "cmd_italic":
  138.       case "cmd_underline":
  139.       case "cmd_strikethrough":
  140.       case "cmd_superscript":
  141.       case "cmd_subscript":
  142.       case "cmd_nobreak":
  143.       case "cmd_em":
  144.       case "cmd_strong":
  145.       case "cmd_cite":
  146.       case "cmd_abbr":
  147.       case "cmd_acronym":
  148.       case "cmd_code":
  149.       case "cmd_samp":
  150.       case "cmd_var":
  151.       case "cmd_removeList":
  152.       case "cmd_ul":
  153.       case "cmd_ol":
  154.       case "cmd_dt":
  155.       case "cmd_dd":
  156.       case "cmd_listProperties":
  157.       case "cmd_indent":
  158.       case "cmd_outdent":
  159.       case "cmd_objectProperties":
  160.       case "cmd_InsertTable":
  161.       case "cmd_InsertRowAbove":
  162.       case "cmd_InsertRowBelow":
  163.       case "cmd_InsertColumnBefore":
  164.       case "cmd_InsertColumnAfter":
  165.       case "cmd_SelectTable":
  166.       case "cmd_SelectRow":
  167.       case "cmd_SelectColumn":
  168.       case "cmd_SelectCell":
  169.       case "cmd_SelectAllCells":
  170.       case "cmd_DeleteTable":
  171.       case "cmd_DeleteRow":
  172.       case "cmd_DeleteColumn":
  173.       case "cmd_DeleteCell":
  174.       case "cmd_DeleteCellContents":
  175.       case "cmd_NormalizeTable":
  176.       case "cmd_tableJoinCells":
  177.       case "cmd_tableSplitCell":
  178.       case "cmd_editTable":
  179.  
  180.       //Options Menu
  181.       case "cmd_selectAddress":
  182.       case "cmd_spelling":
  183.       case "cmd_outputFormat":
  184. //      case "cmd_quoteMessage":
  185.       case "cmd_rewrap":
  186.  
  187.         return true;
  188.  
  189.       default:
  190. //        dump("##MsgCompose: command " + command + "no supported!\n");
  191.         return false;
  192.     }
  193.   },
  194.   
  195.   isCommandEnabled: function(command)
  196.   {
  197.     //For some reason, when editor has the focus, focusedElement is null!.
  198.     var focusedElement = top.document.commandDispatcher.focusedElement;
  199.  
  200.     switch (command)
  201.     {
  202.       //File Menu
  203.       case "cmd_attachFile":
  204.       case "cmd_attachPage":
  205.       case "cmd_close":
  206.       case "cmd_saveDefault":
  207.       case "cmd_saveAsFile":
  208.       case "cmd_saveAsDraft":
  209.       case "cmd_saveAsTemplate":
  210.       case "cmd_sendNow":
  211.       case "cmd_sendLater":
  212.         return !windowLocked;
  213.       case "cmd_quit":
  214.         return true;
  215.  
  216.       //Edit Menu
  217.       case "cmd_pasteQuote":
  218.       case "cmd_find":
  219.       case "cmd_findNext":
  220.         //Disable the editor specific edit commands if the focus is not into the body
  221.         return /*!focusedElement*/false;
  222.       case "cmd_account":
  223.       case "cmd_preferences":
  224.         return true;
  225.  
  226.       //View Menu
  227.       case "cmd_showComposeToolbar":
  228.         return true;
  229.       case "cmd_showFormatToolbar":
  230.         return msgCompose.composeHTML;
  231.  
  232.       //Insert Menu
  233.       case "cmd_insert":
  234.         return !focusedElement;
  235.       case "cmd_link":
  236.       case "cmd_anchor":
  237.       case "cmd_image":
  238.       case "cmd_hline":
  239.       case "cmd_table":
  240.       case "cmd_insertHTML":
  241.       case "cmd_insertChars":
  242.       case "cmd_insertBreak":
  243.       case "cmd_insertBreakAll":
  244.         return /*!focusedElement*/false;
  245.     
  246.       //Options Menu
  247.       case "cmd_selectAddress":
  248.         return !windowLocked;
  249.       case "cmd_spelling":
  250.         return !focusedElement;
  251.       case "cmd_outputFormat":
  252.         return msgCompose.composeHTML;
  253. //      case "cmd_quoteMessage":
  254. //        return mailSession && mailSession.topmostMsgWindow;
  255.       case "cmd_rewrap":
  256.         return !msgCompose.composeHTML && !focusedElement;
  257.       
  258.       //Format Menu
  259.       case "cmd_format":
  260.         return !focusedElement;
  261.       case "cmd_decreaseFont":
  262.       case "cmd_increaseFont":
  263.       case "cmd_bold":
  264.       case "cmd_italic":
  265.       case "cmd_underline":
  266.       case "cmd_strikethrough":
  267.       case "cmd_superscript":
  268.       case "cmd_subscript":
  269.       case "cmd_nobreak":
  270.       case "cmd_em":
  271.       case "cmd_strong":
  272.       case "cmd_cite":
  273.       case "cmd_abbr":
  274.       case "cmd_acronym":
  275.       case "cmd_code":
  276.       case "cmd_samp":
  277.       case "cmd_var":
  278.       case "cmd_removeList":
  279.       case "cmd_ul":
  280.       case "cmd_ol":
  281.       case "cmd_dt":
  282.       case "cmd_dd":
  283.       case "cmd_listProperties":
  284.       case "cmd_indent":
  285.       case "cmd_outdent":
  286.       case "cmd_objectProperties":
  287.       case "cmd_InsertTable":
  288.       case "cmd_InsertRowAbove":
  289.       case "cmd_InsertRowBelow":
  290.       case "cmd_InsertColumnBefore":
  291.       case "cmd_InsertColumnAfter":
  292.       case "cmd_SelectTable":
  293.       case "cmd_SelectRow":
  294.       case "cmd_SelectColumn":
  295.       case "cmd_SelectCell":
  296.       case "cmd_SelectAllCells":
  297.       case "cmd_DeleteTable":
  298.       case "cmd_DeleteRow":
  299.       case "cmd_DeleteColumn":
  300.       case "cmd_DeleteCell":
  301.       case "cmd_DeleteCellContents":
  302.       case "cmd_NormalizeTable":
  303.       case "cmd_tableJoinCells":
  304.       case "cmd_tableSplitCell":
  305.       case "cmd_editTable":
  306.         return /*!focusedElement*/false;
  307.  
  308.       default:
  309. //        dump("##MsgCompose: command " + command + " disabled!\n");
  310.         return false;
  311.     }
  312.   },
  313.   
  314.   doCommand: function(command)
  315.   {
  316.     switch (command)
  317.     {
  318.       //File Menu
  319.       case "cmd_attachFile"         : if (defaultController.isCommandEnabled(command)) AttachFile();           break;
  320.       case "cmd_attachPage"         : AttachPage();           break;
  321.       case "cmd_close"              : DoCommandClose();       break;
  322.       case "cmd_saveDefault"        : Save();                 break;
  323.       case "cmd_saveAsFile"         : SaveAsFile(true);       break;
  324.       case "cmd_saveAsDraft"        : SaveAsDraft();          break;
  325.       case "cmd_saveAsTemplate"     : SaveAsTemplate();       break;
  326.       case "cmd_sendNow"            : if (defaultController.isCommandEnabled(command)) SendMessage();          break;
  327.       case "cmd_sendLater"          : if (defaultController.isCommandEnabled(command)) SendMessageLater();     break;
  328.       case "cmd_account"            : MsgAccountManager();    break;
  329.       case "cmd_preferences"        : DoCommandPreferences(); break;
  330.  
  331.       //View Menu
  332.       case "cmd_showComposeToolbar" : goToggleToolbar('composeToolbar', 'menu_showComposeToolbar'); break;
  333.       case "cmd_showFormatToolbar"  : goToggleToolbar('FormatToolbar', 'menu_showFormatToolbar');   break;
  334.  
  335.       //Options Menu
  336.       case "cmd_selectAddress"      : if (defaultController.isCommandEnabled(command)) SelectAddress();         break;
  337. //      case "cmd_quoteMessage"       : if (defaultController.isCommandEnabled(command)) QuoteSelectedMessage();  break;
  338.       case "cmd_rewrap"             : editorShell.Rewrap(false);                                                break;
  339.  
  340.       default: 
  341. //        dump("##MsgCompose: don't know what to do with command " + command + "!\n");
  342.         return;
  343.     }
  344.   },
  345.   
  346.   onEvent: function(event)
  347.   {
  348. //    dump("DefaultController:onEvent\n");
  349.   }
  350. }
  351.  
  352. function SetupCommandUpdateHandlers()
  353. {
  354. //  dump("SetupCommandUpdateHandlers\n");
  355.   top.controllers.insertControllerAt(0, defaultController);
  356. }
  357.  
  358. function CommandUpdate_MsgCompose()
  359. {
  360. //  dump("\nCommandUpdate_MsgCompose\n");
  361.   try {
  362.   
  363.   //File Menu
  364.   goUpdateCommand("cmd_attachFile");
  365.   goUpdateCommand("cmd_attachPage");
  366.   goUpdateCommand("cmd_close");
  367.   goUpdateCommand("cmd_saveDefault");
  368.   goUpdateCommand("cmd_saveAsFile");
  369.   goUpdateCommand("cmd_saveAsDraft");
  370.   goUpdateCommand("cmd_saveAsTemplate");
  371.   goUpdateCommand("cmd_sendNow");
  372.   goUpdateCommand("cmd_sendLater");
  373.   goUpdateCommand("cmd_quit");
  374.  
  375.   //Edit Menu
  376.   goUpdateCommand("cmd_pasteQuote");
  377.   goUpdateCommand("cmd_find");
  378.   goUpdateCommand("cmd_findNext");
  379.   goUpdateCommand("cmd_account");
  380.   goUpdateCommand("cmd_preferences");
  381.  
  382.   //View Menu
  383.   goUpdateCommand("cmd_showComposeToolbar");
  384.   goUpdateCommand("cmd_showFormatToolbar");
  385.   
  386.   //Insert Menu
  387.   if (msgCompose.composeHTML)
  388.   {
  389.     goUpdateCommand("cmd_insert");
  390.     goUpdateCommand("cmd_link");
  391.     goUpdateCommand("cmd_anchor");
  392.     goUpdateCommand("cmd_image");
  393.     goUpdateCommand("cmd_hline");
  394.     goUpdateCommand("cmd_table");
  395.     goUpdateCommand("cmd_insertHTML");
  396.     goUpdateCommand("cmd_insertChars");
  397.     goUpdateCommand("cmd_insertBreak");
  398.     goUpdateCommand("cmd_insertBreakAll");
  399.   }
  400.   
  401.   //Format Menu
  402.   if (msgCompose.composeHTML)
  403.   {
  404.     goUpdateCommand("cmd_format");
  405.     goUpdateCommand("cmd_decreaseFont");
  406.     goUpdateCommand("cmd_increaseFont");
  407.     goUpdateCommand("cmd_bold");
  408.     goUpdateCommand("cmd_italic");
  409.     goUpdateCommand("cmd_underline");
  410.     goUpdateCommand("cmd_strikethrough");
  411.     goUpdateCommand("cmd_superscript");
  412.     goUpdateCommand("cmd_subscript");
  413.     goUpdateCommand("cmd_nobreak");
  414.     goUpdateCommand("cmd_em");
  415.     goUpdateCommand("cmd_strong");
  416.     goUpdateCommand("cmd_cite");
  417.     goUpdateCommand("cmd_abbr");
  418.     goUpdateCommand("cmd_acronym");
  419.     goUpdateCommand("cmd_code");
  420.     goUpdateCommand("cmd_samp");
  421.     goUpdateCommand("cmd_var");
  422.     goUpdateCommand("cmd_removeList");
  423.     goUpdateCommand("cmd_ul");
  424.     goUpdateCommand("cmd_ol");
  425.     goUpdateCommand("cmd_dt");
  426.     goUpdateCommand("cmd_dd");
  427.     goUpdateCommand("cmd_listProperties");
  428.     goUpdateCommand("cmd_indent");
  429.     goUpdateCommand("cmd_outdent");
  430.     goUpdateCommand("cmd_objectProperties");
  431.     goUpdateCommand("cmd_InsertTable");
  432.     goUpdateCommand("cmd_InsertRowAbove");
  433.     goUpdateCommand("cmd_InsertRowBelow");
  434.     goUpdateCommand("cmd_InsertColumnBefore");
  435.     goUpdateCommand("cmd_InsertColumnAfter");
  436.     goUpdateCommand("cmd_SelectTable");
  437.     goUpdateCommand("cmd_SelectRow");
  438.     goUpdateCommand("cmd_SelectColumn");
  439.     goUpdateCommand("cmd_SelectCell");
  440.     goUpdateCommand("cmd_SelectAllCells");
  441.     goUpdateCommand("cmd_DeleteTable");
  442.     goUpdateCommand("cmd_DeleteRow");
  443.     goUpdateCommand("cmd_DeleteColumn");
  444.     goUpdateCommand("cmd_DeleteCell");
  445.     goUpdateCommand("cmd_DeleteCellContents");
  446.     goUpdateCommand("cmd_NormalizeTable");
  447.     goUpdateCommand("cmd_tableJoinCells");
  448.     goUpdateCommand("cmd_tableSplitCell");
  449.     goUpdateCommand("cmd_editTable");
  450.   }
  451.  
  452.   //Options Menu
  453.   goUpdateCommand("cmd_selectAddress");
  454.   goUpdateCommand("cmd_spelling");
  455.   goUpdateCommand("cmd_outputFormat");
  456. //  goUpdateCommand("cmd_quoteMessage");
  457.   goUpdateCommand("cmd_rewrap");
  458.   
  459.   } catch(e) {}
  460. }
  461.  
  462. function DoCommandClose()
  463. {
  464.   if (ComposeCanClose())
  465.     CloseWindow()
  466. }
  467.  
  468. function DoCommandPreferences()
  469. {
  470.   goPreferences('messengercompose.xul', 'chrome://messenger/content/messengercompose/pref-composing_messages.xul')
  471. }
  472.  
  473. function ToggleWindowLock()
  474. {
  475.   windowLocked = !windowLocked;
  476.   CommandUpdate_MsgCompose();
  477. }
  478.  
  479. function GetArgs()
  480. {
  481.     var args = new Object();
  482.     var originalData = document.getElementById("args").getAttribute("value");
  483.     var data = "";
  484.     var separator = String.fromCharCode(1);
  485.  
  486.     var quoteChar = "";
  487.     var prevChar = "";
  488.     var nextChar = "";
  489.     for (var i = 0; i < originalData.length; i ++, prevChar = aChar)
  490.     {
  491.         var aChar = originalData.charAt(i)
  492.         var aCharCode = originalData.charCodeAt(i)
  493.         if ( i < originalData.length - 1)
  494.             nextChar = originalData.charAt(i + 1);
  495.         else
  496.             nextChar = "";
  497.  
  498.         if (aChar == quoteChar && (nextChar == "," || nextChar == ""))
  499.         {
  500.             quoteChar = "";
  501.             data += aChar;
  502.         }
  503.         else if ((aCharCode == 39 || aCharCode == 34) && prevChar == "=") //quote or double quote
  504.         {
  505.             if (quoteChar == "")
  506.                 quoteChar = aChar;
  507.             data += aChar;
  508.         }
  509.         else if (aChar == ",")
  510.         {
  511.             if (quoteChar == "")
  512.                 data += separator;
  513.             else
  514.                 data += aChar 
  515.         }
  516.         else
  517.             data += aChar 
  518.     }
  519.     
  520.     var pairs = data.split(separator);
  521. //    dump("Compose: argument: {" + data + "}\n");
  522.  
  523.     for (i = pairs.length - 1; i >= 0; i--)
  524.     {
  525.         var pos = pairs[i].indexOf('=');
  526.         if (pos == -1)
  527.             continue;
  528.         var argname = pairs[i].substring(0, pos);
  529.         var argvalue = pairs[i].substring(pos + 1);
  530.         if (argvalue.charAt(0) == "'" && argvalue.charAt(argvalue.length - 1) == "'")
  531.             args[argname] = argvalue.substring(1, argvalue.length - 1);
  532.         else
  533.           try {
  534.         args[argname] = unescape(argvalue);
  535.       } catch (e) {args[argname] = argvalue;}
  536.     dump("[" + argname + "=" + args[argname] + "]\n");
  537.     }
  538.     return args;
  539. }
  540.  
  541. function WaitFinishLoadingDocument(msgType)
  542. {
  543.     if (documentLoaded)
  544.     {
  545.         //If we are in plain text, we nee to set the wrap column
  546.         if (! msgCompose.composeHTML)
  547.             try
  548.             {
  549.                 window.editorShell.wrapColumn = msgCompose.wrapLength;
  550.             }
  551.             catch (e)
  552.             {
  553.                 dump("### window.editorShell.wrapColumn exception text: " + e + " - failed\n");
  554.             }
  555.             
  556.         CompFields2Recipients(msgCompose.compFields, msgType);
  557.         SetComposeWindowTitle(13);
  558.         AdjustFocus();
  559.         try {
  560.         window.updateCommands("create");
  561.         } catch(e) {}
  562.     }
  563.     else
  564.         setTimeout("WaitFinishLoadingDocument(" + msgType + ");", 200);
  565. }
  566.  
  567. function ComposeStartup()
  568. {
  569.     dump("Compose: ComposeStartup\n");
  570.  
  571.     //dump("Get arguments\n");
  572.     var args = GetArgs();
  573.  
  574.     //dump("fill in Identity menulist\n");
  575.     var identityList = document.getElementById("msgIdentity");
  576.     var identityListPopup = document.getElementById("msgIdentityPopup");
  577.  
  578.     if (identityListPopup) {
  579.         fillIdentityListPopup(identityListPopup);
  580.     }
  581.  
  582.     var identity = null;
  583.     if (args.preselectid)
  584.         identity = getIdentityForKey(args.preselectid);
  585.     else
  586.     {
  587.        // no preselect, so use the default account
  588.        var identities = accountManager.defaultAccount.identities;      
  589.       if (identities.Count() >= 1)
  590.           identity = identities.QueryElementAt(0, Components.interfaces.nsIMsgIdentity);
  591.         else
  592.         {
  593.         identities = GetIdentities();
  594.         identity = identities[0];
  595.       }      
  596.     }
  597.    
  598.     for (i=0;i<identityListPopup.childNodes.length;i++) {
  599.         var item = identityListPopup.childNodes[i];
  600.         var id = item.getAttribute('id');
  601.         if (id == identity.key) {
  602.             identityList.selectedItem = item;
  603.             break;
  604.         }
  605.     }
  606.     LoadIdentity(true);
  607.  
  608.     if (msgComposeService)
  609.     {
  610.         // this is frustrating, we need to convert the preselect identity key
  611.         // back to an identity, to pass to initcompose
  612.         // it would be nice if there was some way to actually send the
  613.         // identity through "args"
  614.         
  615.         msgCompose = msgComposeService.InitCompose(window, args.originalMsg, args.type, args.format, args.fieldsAddr, identity);
  616.         if (msgCompose)
  617.         {
  618.             //Creating a Editor Shell
  619.             var editorElement = document.getElementById("content-frame");
  620.             if (!editorElement)
  621.             {
  622.                 dump("Failed to get editor element!\n");
  623.                 return;
  624.             }
  625.             var editorShell = editorElement.editorShell;
  626.             if (!editorShell)
  627.             {
  628.                 dump("Failed to create editorShell!\n");
  629.                 return;
  630.             }
  631.             
  632.             // save the editorShell in the window. The editor JS expects to find it there.
  633.             window.editorShell = editorShell;
  634.             dump("Created editorShell\n");
  635.  
  636.             // setEditorType MUST be call before setContentWindow
  637.             if (msgCompose.composeHTML)
  638.             {
  639.                 window.editorShell.editorType = "htmlmail";
  640.                 dump("editor initialized in HTML mode\n");
  641.             }
  642.             else
  643.             {
  644.                 //Remove HTML toolbar, format and insert menus as we are editing in plain text mode
  645.                 document.getElementById("FormatToolbar").setAttribute("hidden", true);
  646.                 document.getElementById("formatMenu").setAttribute("hidden", true);
  647.                 document.getElementById("insertMenu").setAttribute("hidden", true);
  648.                 document.getElementById("menu_showFormatToolbar").setAttribute("checked", false);
  649.  
  650.  
  651.                 window.editorShell.editorType = "textmail";
  652.                 dump("editor initialized in PLAIN TEXT mode\n");
  653.             }
  654.             window.editorShell.webShellWindow = window;
  655.             window.editorShell.contentWindow = window._content;
  656.  
  657.             // Do setup common to Message Composer and Web Composer
  658.             EditorSharedStartup();
  659.  
  660.             var msgCompFields = msgCompose.compFields;
  661.             if (msgCompFields)
  662.             {
  663.                 if (args.body) //We need to set the body before setting
  664.                          //msgCompose.editor;
  665.           {
  666.             if (args.bodyislink == "true")
  667.             {
  668.               if (msgCompose.composeHTML)
  669.               {
  670.                 var cleanBody;
  671.                 try {
  672.                   cleanBody = unescape(args.body);
  673.                 } catch(e) { cleanBody = args.body;}
  674.  
  675.                 msgCompFields.SetBody("<BR><A HREF=\"" + args.body +
  676.                                       "\">" + cleanBody + "</A><BR>");
  677.               }
  678.               else
  679.                 msgCompFields.SetBody("\n<" + args.body + ">\n");
  680.             }
  681.             else
  682.               msgCompFields.SetBody(args.body);
  683.           }
  684.  
  685.                 if (args.to)
  686.                     msgCompFields.SetTo(args.to);
  687.                 if (args.cc)
  688.                     msgCompFields.SetCc(args.cc);
  689.                 if (args.bcc)
  690.                     msgCompFields.SetBcc(args.bcc);
  691.                 if (args.newsgroups)
  692.                     msgCompFields.SetNewsgroups(args.newsgroups);
  693.                 if (args.subject)
  694.                     msgCompFields.SetSubject(args.subject);
  695.                 if (args.attachment)
  696.                     msgCompFields.SetAttachments(args.attachment);
  697.                 dump("args newshost = " + args.newshost + "\n");
  698.                 if (args.newshost)
  699.                     msgCompFields.SetNewshost(args.newshost);
  700.             
  701.                 var subjectValue = msgCompFields.GetSubject();
  702.                 if (subjectValue != "") {
  703.                     document.getElementById("msgSubject").value = subjectValue;
  704.                 }
  705.                 var attachmentValue = msgCompFields.GetAttachments();
  706.                 if (attachmentValue != "") {
  707.                    var atts =  attachmentValue.split(",");
  708.                     for (var i=0; i < atts.length; i++)
  709.                     {
  710.                         AddAttachment(atts[i]);
  711.                     }
  712.                 }
  713.             }
  714.              
  715.             // Now that we have an Editor AppCore, we can finish to initialize the Compose AppCore
  716.             msgCompose.editor = window.editorShell;
  717.             
  718.             msgCompose.RegisterStateListener(stateListener);
  719.  
  720.             // call updateCommands to disable while we're loading the page
  721.           try {
  722.             window.updateCommands("create");
  723.           } catch(e) {}
  724.             
  725. //        SetupCommandUpdateHandlers();
  726.             WaitFinishLoadingDocument(args.type);
  727.         }
  728.     }
  729. }
  730.  
  731. function ComposeLoad()
  732. {
  733.     dump("\nComposeLoad from XUL\n");
  734.     
  735.     SetupCommandUpdateHandlers();
  736.  
  737.     verifyAccounts();    // this will do migration, if we need to.
  738.  
  739.     if (other_header != "") {
  740.         var selectNode = document.getElementById('msgRecipientType#1');
  741.  
  742.         selectNode = selectNode.childNodes[0];
  743.         var opt = document.createElement('menuitem');
  744.         opt.setAttribute("data", "addr_other");
  745.         opt.setAttribute("value", other_header + ":");
  746.         selectNode.appendChild(opt);
  747.     }
  748.  
  749.     // See if we got arguments.
  750.     if ( window.arguments && window.arguments[0] != null ) {
  751.         // Window was opened via window.openDialog.  Copy argument
  752.         // and perform compose initialization (as if we were
  753.         // opened via toolkitCore's ShowWindowWithArgs).
  754.         document.getElementById( "args" ).setAttribute( "value", window.arguments[0] );
  755.         ComposeStartup();
  756.     }
  757.     window.tryToClose=ComposeCanClose;
  758.  
  759. }
  760.  
  761. function ComposeUnload(calledFromExit)
  762. {
  763.     dump("\nComposeUnload from XUL\n");
  764.     
  765.     msgCompose.UnregisterStateListener(stateListener);
  766.     if (msgCompose && msgComposeService)
  767.         msgComposeService.DisposeCompose(msgCompose, false);
  768. }
  769.  
  770. function SetDocumentCharacterSet(aCharset)
  771. {
  772.   dump("SetDocumentCharacterSet Callback!\n");
  773.   dump(aCharset + "\n");
  774.  
  775.   if (msgCompose) {
  776.     msgCompose.SetDocumentCharset(aCharset);
  777.     currentMailSendCharset = aCharset;
  778.     g_charsetTitle = null;
  779.     SetComposeWindowTitle(13);
  780.   }
  781.   else
  782.     dump("Compose has not been created!\n");
  783. }
  784.  
  785. function SetDefaultMailSendCharacterSet()
  786. {
  787.   // Set the current menu selection as the default
  788.   if (currentMailSendCharset != null) {
  789.     // try to get preferences service
  790.     var prefs = null;
  791.     try {
  792.       prefs = Components.classes['@mozilla.org/preferences;1'];
  793.       prefs = prefs.getService();
  794.       prefs = prefs.QueryInterface(Components.interfaces.nsIPref);
  795.     }
  796.     catch (ex) {
  797.       dump("failed to get prefs service!\n");
  798.       prefs = null;
  799.     }
  800.  
  801.       if (msgCompose) {
  802.       // write to the pref file
  803.       prefs.SetCharPref("mailnews.send_default_charset", currentMailSendCharset);
  804.       // update the global
  805.       g_send_default_charset = currentMailSendCharset;
  806.       dump("Set send_default_charset to" + currentMailSendCharset + "\n");
  807.     }
  808.       else
  809.           dump("Compose has not been created!\n");
  810.   }
  811. }
  812.  
  813. function InitCharsetMenuCheckMark()
  814. {
  815.   // dump("msgCompose.compFields is " + msgCompose.compFields.GetCharacterSet() + "\n");
  816.   // return if the charset is already set explitily
  817.   if (currentMailSendCharset != null) {
  818.     dump("already set to " + currentMailSendCharset + "\n");
  819.     return;
  820.   }
  821.  
  822.   var menuitem; 
  823.  
  824.   // try to get preferences service
  825.   var prefs = null;
  826.   try {
  827.     prefs = Components.classes['@mozilla.org/preferences;1'];
  828.     prefs = prefs.getService();
  829.     prefs = prefs.QueryInterface(Components.interfaces.nsIPref);
  830.   }
  831.   catch (ex) {
  832.     dump("failed to get prefs service!\n");
  833.     prefs = null;
  834.   }
  835.   var send_default_charset = prefs.getLocalizedUnicharPref("mailnews.send_default_charset");
  836. //  send_default_charset = send_default_charset.toUpperCase();
  837.   dump("send_default_charset is " + send_default_charset + "\n");
  838.  
  839.   var compFieldsCharset = msgCompose.compFields.GetCharacterSet();
  840. //  compFieldsCharset = compFieldsCharset.toUpperCase();
  841.   dump("msgCompose.compFields is " + compFieldsCharset + "\n");
  842.  
  843.   if (compFieldsCharset == "us-ascii")
  844.     compFieldsCharset = "ISO-8859-1";
  845.   menuitem = document.getElementById(compFieldsCharset);
  846.  
  847.   // charset may have been set implicitly in case of reply/forward
  848.   if (send_default_charset != compFieldsCharset) {
  849.     menuitem.setAttribute('checked', 'true');
  850.     return;
  851.   } 
  852.  
  853.   // use pref default
  854.   menuitem = document.getElementById(send_default_charset);
  855.   if (menuitem) 
  856.     menuitem.setAttribute('checked', 'true'); 
  857.  
  858.   // Set a document charset to a default mail send charset.
  859.   SetDocumentCharacterSet(send_default_charset);
  860. }
  861.  
  862. function GetCharsetUIString()
  863. {
  864.   var charset = msgCompose.compFields.GetCharacterSet();
  865.   if (g_send_default_charset == null) {
  866.     try {
  867.       prefs = Components.classes['@mozilla.org/preferences;1'];
  868.       prefs = prefs.getService();
  869.       prefs = prefs.QueryInterface(Components.interfaces.nsIPref);
  870.       g_send_default_charset = prefs.getLocalizedUnicharPref("mailnews.send_default_charset");
  871.     }
  872.     catch (ex) {
  873.       dump("failed to get prefs service!\n");
  874.       prefs = null;
  875.       g_send_default_charset = charset; // set to the current charset
  876.     }
  877.   }
  878.  
  879.   charset = charset.toUpperCase();
  880.   if (charset == "US-ASCII")
  881.     charset = "ISO-8859-1";
  882.  
  883.   if (charset != g_send_default_charset) {
  884.  
  885.     if (g_charsetTitle == null) {
  886.       try {
  887.         var ccm = Components.classes['@mozilla.org/charset-converter-manager;1'];
  888.         ccm = ccm.getService();
  889.         ccm = ccm.QueryInterface(Components.interfaces.nsICharsetConverterManager2);
  890.         // get a localized string
  891.         var charsetAtom = ccm.GetCharsetAtom(charset);
  892.         g_charsetTitle = ccm.GetCharsetTitle(charsetAtom);
  893.       }
  894.       catch (ex) {
  895.         dump("failed to get a charset title of " + charset + "!\n");
  896.         g_charsetTitle = charset; // just show the charset itself
  897.       }
  898.     }
  899.  
  900.     return " - " + g_charsetTitle;
  901.   }
  902.  
  903.   return "";
  904. }
  905.  
  906. function GenericSendMessage( msgType )
  907. {
  908.     dump("GenericSendMessage from XUL\n");
  909.  
  910.   dump("Identity = " + getCurrentIdentity() + "\n");
  911.     
  912.     if (msgCompose != null)
  913.     {
  914.         var msgCompFields = msgCompose.compFields;
  915.         if (msgCompFields)
  916.         {
  917.             Recipients2CompFields(msgCompFields);
  918.             var subject = document.getElementById("msgSubject").value;
  919.             msgCompFields.SetSubject(subject);
  920.             dump("attachments = " + GenerateAttachmentsString() + "\n");
  921.             try {
  922.                 msgCompFields.SetAttachments(GenerateAttachmentsString());
  923.             }
  924.             catch (ex) {
  925.                 dump("failed to SetAttachments\n");
  926.             }
  927.         
  928.             if (msgType == msgCompDeliverMode.Now || msgType == msgCompDeliverMode.Later)
  929.             {
  930.               //Do we need to check the spelling?
  931.         if (prefs.GetBoolPref("mail.SpellCheckBeforeSend"))
  932.             goDoCommand('cmd_spelling');
  933.               
  934.                 //Check if we have a subject, else ask user for confirmation
  935.                 if (subject == "")
  936.                 { 
  937.                     if (commonDialogsService)
  938.                     {
  939.                         var result = {value:0};
  940.                         if (commonDialogsService.Prompt(
  941.                             window,
  942.                             Bundle.GetStringFromName("subjectDlogTitle"),
  943.                             Bundle.GetStringFromName("subjectDlogMessage"),
  944.                             Bundle.GetStringFromName("defaultSubject"),
  945.                             result
  946.                             ))
  947.                         {
  948.                             msgCompFields.SetSubject(result.value);
  949.                             var subjectInputElem = document.getElementById("msgSubject");
  950.                             subjectInputElem.value = result.value;
  951.                         }
  952.                         else
  953.                           return;
  954.                     }
  955.                 }
  956.  
  957.                 // Before sending the message, check what to do with HTML message, eventually abort.
  958.         var convert = DetermineConvertibility();
  959.                 var action = DetermineHTMLAction(convert);
  960.                 if (action == msgCompSendFormat.AskUser)
  961.                 {
  962.                     var recommAction = convert == msgCompConvertible.No
  963.                                    ? msgCompSendFormat.AskUser
  964.                                    : msgCompSendFormat.PlainText;
  965.                     var result2 = {action:recommAction,
  966.                                   convertible:convert,
  967.                                   abort:false};
  968.                     window.openDialog("chrome://messenger/content/messengercompose/askSendFormat.xul",
  969.                                       "askSendFormatDialog", "chrome,modal,titlebar,centerscreen",
  970.                                       result2);
  971.                     if (result2.abort)
  972.                         return;
  973.                     action = result2.action;
  974.                 }
  975.                 switch (action)
  976.                 {
  977.                     case msgCompSendFormat.PlainText:
  978.                         msgCompFields.SetTheForcePlainText(true);
  979.                         msgCompFields.SetUseMultipartAlternativeFlag(false);
  980.                         break;
  981.                     case msgCompSendFormat.HTML:
  982.                         msgCompFields.SetTheForcePlainText(false);
  983.                         msgCompFields.SetUseMultipartAlternativeFlag(false);
  984.                         break;
  985.                     case msgCompSendFormat.Both:
  986.                         msgCompFields.SetTheForcePlainText(false);
  987.                         msgCompFields.SetUseMultipartAlternativeFlag(true);
  988.                         break;        
  989.                    default: dump("\###SendMessage Error: invalid action value\n"); return;
  990.                 }
  991.             }
  992.             try {
  993.               windowLocked = true;
  994.               CommandUpdate_MsgCompose();
  995.                 msgCompose.SendMsg(msgType, getCurrentIdentity(), null);
  996.                 contentChanged = false;
  997.                 msgCompose.bodyModified = false;
  998.             }
  999.             catch (ex) {
  1000.                 dump("failed to SendMsg\n");
  1001.               windowLocked = false;
  1002.               CommandUpdate_MsgCompose();
  1003.             }
  1004.         }
  1005.     }
  1006.     else
  1007.         dump("###SendMessage Error: composeAppCore is null!\n");
  1008. }
  1009.  
  1010. function SendMessage()
  1011. {
  1012.     dump("SendMessage from XUL\n");
  1013.   // 0 = nsMsgDeliverNow
  1014.   // RICHIE: We should really have a way of using constants and not
  1015.   // hardcoded numbers for the first argument
  1016.     GenericSendMessage(msgCompDeliverMode.Now);
  1017. }
  1018.  
  1019. function SendMessageLater()
  1020. {
  1021.     dump("SendMessageLater from XUL\n");
  1022.   // 1 = nsMsgQueueForLater
  1023.   // RICHIE: We should really have a way of using constants and not
  1024.   // hardcoded numbers for the first argument
  1025.     GenericSendMessage(msgCompDeliverMode.Later);
  1026. }
  1027.  
  1028. function Save()
  1029. {
  1030.     dump("Save from XUL\n");
  1031.     switch (defaultSaveOperation)
  1032.     {
  1033.       case "file"     : SaveAsFile(false);      break;
  1034.       case "template" : SaveAsTemplate(false);  break;
  1035.       default         : SaveAsDraft(false);     break;
  1036.     }
  1037. }
  1038.  
  1039. function SaveAsFile(saveAs)
  1040. {
  1041.     dump("SaveAsFile from XUL\n");
  1042.     editorShell.saveDocument(saveAs, false);
  1043.   defaultSaveOperation = "file";
  1044. }
  1045.  
  1046. function SaveAsDraft()
  1047. {
  1048.     dump("SaveAsDraft from XUL\n");
  1049.  
  1050.   // 4 = nsMsgSaveAsDraft
  1051.   // RICHIE: We should really have a way of using constants and not
  1052.   // hardcoded numbers for the first argument
  1053.   GenericSendMessage(msgCompDeliverMode.SaveAsDraft);
  1054.   defaultSaveOperation = "draft";
  1055. }
  1056.  
  1057. function SaveAsTemplate()
  1058. {
  1059.     dump("SaveAsTemplate from XUL\n");
  1060.  
  1061.   // 5 = nsMsgSaveAsTemplate
  1062.   // RICHIE: We should really have a way of using constants and not
  1063.   // hardcoded numbers for the first argument
  1064.   GenericSendMessage(msgCompDeliverMode.SaveAsTemplate);
  1065.   defaultSaveOperation = "template";
  1066. }
  1067.  
  1068.  
  1069. function MessageFcc(menuItem)
  1070. {
  1071.     // Get the id for the folder we're FCC into
  1072.   // This is the additional FCC in addition to the
  1073.   // default FCC
  1074.     destUri = menuItem.getAttribute('id');
  1075.     if (msgCompose)
  1076.     {
  1077.         var msgCompFields = msgCompose.compFields;
  1078.         if (msgCompFields)
  1079.         {
  1080.             if (msgCompFields.GetFcc2() == destUri)
  1081.             {
  1082.                 msgCompFields.SetFcc2("nocopy://");
  1083.                 dump("FCC2: none\n");
  1084.             }
  1085.             else
  1086.             {
  1087.                 msgCompFields.SetFcc2(destUri);
  1088.                 dump("FCC2: " + destUri + "\n");
  1089.             }
  1090.         }
  1091.     }    
  1092. }
  1093.  
  1094. function PriorityMenuSelect(target)
  1095. {
  1096.     dump("Set Message Priority to " + target.getAttribute('id') + "\n");
  1097.     if (msgCompose)
  1098.     {
  1099.         var msgCompFields = msgCompose.compFields;
  1100.         if (msgCompFields)
  1101.             msgCompFields.SetPriority(target.getAttribute('id'));
  1102.     }
  1103. }
  1104.  
  1105. function ReturnReceiptMenuSelect()
  1106. {
  1107.     if (msgCompose)
  1108.     {
  1109.         var msgCompFields = msgCompose.compFields;
  1110.         if (msgCompFields)
  1111.         {
  1112.             if (msgCompFields.GetReturnReceipt())
  1113.             {
  1114.                 dump("Set Return Receipt to FALSE\n");
  1115.                 msgCompFields.SetReturnReceipt(false);
  1116.             }
  1117.             else
  1118.             {
  1119.                 dump("Set Return Receipt to TRUE\n");
  1120.                 msgCompFields.SetReturnReceipt(true);
  1121.             }
  1122.         }
  1123.     }
  1124. }
  1125.  
  1126. function OutputFormatMenuSelect(target)
  1127. {
  1128.     dump("Set Message Format to " + target.getAttribute('id') + "\n");
  1129.     if (msgCompose)
  1130.     {
  1131.         var msgCompFields = msgCompose.compFields;
  1132.    
  1133.         if (msgCompFields)
  1134.         {
  1135.             switch (target.getAttribute('id'))
  1136.             {
  1137.                 case "1": sendFormat = msgCompSendFormat.AskUser;     break;
  1138.                 case "2": sendFormat = msgCompSendFormat.PlainText;   break;
  1139.                 case "3": sendFormat = msgCompSendFormat.HTML;        break;
  1140.             case "4": sendFormat = msgCompSendFormat.Both;        break;
  1141.             }
  1142.         }
  1143.     }
  1144. }
  1145.  
  1146. function SelectAddress() 
  1147. {
  1148.     var msgCompFields = msgCompose.compFields;
  1149.     
  1150.     Recipients2CompFields(msgCompFields);
  1151.     
  1152.     var toAddress = msgCompFields.GetTo();
  1153.     var ccAddress = msgCompFields.GetCc();
  1154.     var bccAddress = msgCompFields.GetBcc();
  1155.     
  1156.     dump("toAddress: " + toAddress + "\n");
  1157.     window.openDialog("chrome://messenger/content/addressbook/abSelectAddressesDialog.xul",
  1158.                       "",
  1159.                       "chrome,resizable,titlebar,modal",
  1160.                       {composeWindow:top.window,
  1161.                        msgCompFields:msgCompFields,
  1162.                        toAddress:toAddress,
  1163.                        ccAddress:ccAddress,
  1164.                        bccAddress:bccAddress});
  1165. }
  1166.  
  1167. function queryISupportsArray(supportsArray, iid) {
  1168.     var result = new Array;
  1169.     for (var i=0; i<supportsArray.Count(); i++) {
  1170.       // dump(i + "," + result[i] + "\n");
  1171.       result[i] = supportsArray.GetElementAt(i).QueryInterface(iid);
  1172.     }
  1173.     return result;
  1174. }
  1175.  
  1176. function GetIdentities()
  1177. {
  1178.  
  1179.     var idSupports = accountManager.allIdentities;
  1180.     var identities = queryISupportsArray(idSupports,
  1181.                                          Components.interfaces.nsIMsgIdentity);
  1182.  
  1183.     dump(identities + "\n");
  1184.     return identities;
  1185. }
  1186.  
  1187. function fillIdentityListPopup(popup)
  1188. {
  1189.     var identities = GetIdentities();
  1190.     
  1191.     for (var i=0; i<identities.length; i++)
  1192.     {
  1193.         var identity = identities[i];
  1194.  
  1195.         //dump(i + " = " + identity.identityName + "," +identity.key + "\n");
  1196.  
  1197.         //Get server prettyName for each identity
  1198.  
  1199.         var serverSupports = accountManager.GetServersForIdentity(identity);
  1200.  
  1201.         //dump(i + " = " + identity.identityName + "," +identity.key + "\n");
  1202.         
  1203.         if(serverSupports.GetElementAt(0))
  1204.             var    result = serverSupports.GetElementAt(0).QueryInterface(Components.interfaces.nsIMsgIncomingServer);
  1205.         //dump ("The account name is = "+result.prettyName+ "\n");
  1206.         var accountName = " - "+result.prettyName;
  1207.  
  1208.         var item=document.createElement('menuitem');
  1209.         item.setAttribute('value', identity.identityName);
  1210.         item.setAttribute('class', 'identity-popup-item');
  1211.         item.setAttribute('accountname', accountName);
  1212.         item.setAttribute('id', identity.key);
  1213.         popup.appendChild(item);
  1214.     }
  1215. }
  1216.  
  1217. function getCurrentIdentity()
  1218. {
  1219.     // fill in Identity combobox
  1220.     var identityList = document.getElementById("msgIdentity");
  1221.  
  1222.     var item = identityList.selectedItem;
  1223.     var identityKey = item.getAttribute('id');
  1224.  
  1225.     //dump("Looking for identity " + identityKey + "\n");
  1226.     var identity = accountManager.getIdentity(identityKey);
  1227.     
  1228.     return identity;
  1229. }
  1230.  
  1231. function getIdentityForKey(key)
  1232. {
  1233.     return accountManager.getIdentity(key);
  1234. }
  1235.  
  1236. function AdjustFocus()
  1237. {
  1238.     var element = document.getElementById("msgRecipient#" + awGetNumberOfRecipients());
  1239.     if (element.value == "")
  1240.     {
  1241.         dump("set focus on the recipient\n");
  1242.         awSetFocus(awGetNumberOfRecipients(), element);
  1243.     }
  1244.     else
  1245.     {
  1246.         element = document.getElementById("msgSubject");
  1247.         if (element.value == "")
  1248.         {
  1249.             dump("set focus on the subject\n");
  1250.             element.focus();
  1251.         }
  1252.         else
  1253.         {
  1254.             dump("set focus on the body\n");
  1255.             editorShell.contentWindow.focus();
  1256.         }
  1257.     }
  1258. }
  1259.  
  1260. function SetComposeWindowTitle(event) 
  1261. {
  1262.     /* dump("event = " + event + "\n"); */
  1263.  
  1264.     /* only set the title when they hit return (or tab?) if 
  1265.       mail.update_compose_title_as_you_type == false
  1266.      */
  1267.     if ((event != 13) && (update_compose_title_as_you_type == false)) {
  1268.         return;
  1269.     }
  1270.  
  1271.     var newTitle = document.getElementById('msgSubject').value;
  1272.  
  1273.     /* dump("newTitle = " + newTitle + "\n"); */
  1274.  
  1275.     if (newTitle == "" ) {
  1276.         newTitle = Bundle.GetStringFromName("defaultSubject");
  1277.     }
  1278.  
  1279.     newTitle += GetCharsetUIString();
  1280.  
  1281.     window.title = Bundle.GetStringFromName("windowTitlePrefix") + " " + newTitle;
  1282. }
  1283.  
  1284. // Check for changes to document and allow saving before closing
  1285. // This is hooked up to the OS's window close widget (e.g., "X" for Windows)
  1286. function ComposeCanClose()
  1287. {
  1288.     // Returns FALSE only if user cancels save action
  1289.     if (contentChanged || msgCompose.bodyModified)
  1290.     {
  1291.         if (commonDialogsService)
  1292.         {
  1293.             var result = {value:0};
  1294.             commonDialogsService.UniversalDialog(
  1295.                 window,
  1296.                 null,
  1297.                 Bundle.GetStringFromName("saveDlogTitle"),
  1298.                 Bundle.GetStringFromName("saveDlogMessage"),
  1299.                 null,
  1300.                 Bundle.GetStringFromName("saveDlogSaveBtn"),
  1301.                 Bundle.GetStringFromName("saveDlogCancelBtn"),
  1302.                 Bundle.GetStringFromName("saveDlogDontSaveBtn"),
  1303.                 null,
  1304.                 null,
  1305.                 null,
  1306.                 {value:0},
  1307.                 {value:0},
  1308.                 "chrome://global/skin/question-icon.gif",
  1309.                 {value:"false"},
  1310.                 3,
  1311.                 0,
  1312.                 0,
  1313.                 result
  1314.                 );
  1315.             if (result)
  1316.             {
  1317.                 switch (result.value)
  1318.                 {
  1319.                     case 0: //Save
  1320.                         if (LastToClose())
  1321.                             NotifyQuitApplication();
  1322.                         SaveAsDraft();
  1323.                         break;
  1324.                     case 1:    //Cancel
  1325.                         return false;
  1326.                     case 2:    //Don't Save
  1327.                         break;    
  1328.                 }    
  1329.             }
  1330.         }
  1331.                 
  1332.         msgCompose.bodyModified = false;
  1333.         contentChanged = false;
  1334.     }
  1335.  
  1336.     return true;
  1337. }
  1338.  
  1339. function CloseWindow()
  1340. {
  1341.     if (msgCompose)
  1342.         msgCompose.CloseWindow();
  1343. }
  1344.  
  1345. function AttachFile()
  1346. {
  1347.     dump("AttachFile()\n");
  1348.     currentAttachment = "";
  1349.     //Get file using nsIFilePicker and convert to URL
  1350.     try {
  1351.             var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  1352.             fp.init(window, Bundle.GetStringFromName("chooseFileToAttach"), nsIFilePicker.modeOpen);
  1353.             fp.appendFilters(nsIFilePicker.filterAll);
  1354.             if (fp.show() == nsIFilePicker.returnOK) {
  1355.             currentAttachment = fp.fileURL.spec;
  1356.             dump("nsIFilePicker - "+currentAttachment+"\n");
  1357.             }
  1358.     }     
  1359.     catch (ex) {
  1360.         dump("failed to get the local file to attach\n");
  1361.     }
  1362.     
  1363.     AddAttachment(currentAttachment);
  1364. }
  1365.  
  1366. function AddAttachment(attachment)
  1367. {
  1368.     if (attachment && (attachment != ""))
  1369.     {
  1370.         var bucketBody = document.getElementById("bucketBody");
  1371.         var item = document.createElement("treeitem");
  1372.         var row = document.createElement("treerow");
  1373.         var cell = document.createElement("treecell");
  1374.         
  1375.         var prettyName = attachment;
  1376.         if (msgCompose)
  1377.             prettyName = msgCompose.AttachmentPrettyName(attachment);
  1378.         cell.setAttribute("value", prettyName);                //use for display only
  1379.         cell.setAttribute("attachment", attachment);        //full url stored here
  1380.         cell.setAttribute("tooltip", "aTooltip");
  1381.         try {
  1382.             cell.setAttribute("tooltiptext", unescape(attachment));
  1383.         }
  1384.         catch(e) {cell.setAttribute("tooltiptext", attachment);}
  1385.         row.appendChild(cell);
  1386.         item.appendChild(row);
  1387.         bucketBody.appendChild(item);
  1388.     }    
  1389. }
  1390.  
  1391. function AttachPage()
  1392. {
  1393.     if (commonDialogsService)
  1394.     {
  1395.         var result = {value:0};
  1396.         if (commonDialogsService.Prompt(
  1397.             window,
  1398.             Bundle.GetStringFromName("attachPageDlogTitle"),
  1399.             Bundle.GetStringFromName("attachPageDlogMessage"),
  1400.             null,
  1401.             result))
  1402.         {
  1403.             AddAttachment(result.value);
  1404.         }
  1405.     }
  1406. }
  1407.  
  1408. function GenerateAttachmentsString()
  1409. {
  1410.     var attachments = "";
  1411.     var body = document.getElementById('bucketBody');
  1412.     var item, row, cell, text, colon;
  1413.  
  1414.     for (var index = 0; index < body.childNodes.length; index++)
  1415.     {
  1416.         item = body.childNodes[index];
  1417.         if (item.childNodes && item.childNodes.length)
  1418.         {
  1419.             row = item.childNodes[0];
  1420.             if (row.childNodes &&  row.childNodes.length)
  1421.             {
  1422.                 cell = row.childNodes[0];
  1423.                 if (cell)
  1424.                 {
  1425.                     text = cell.getAttribute("attachment");
  1426.                     if (text.length)
  1427.                     {
  1428.                       text = text.replace(/\,/g, "%2C");
  1429.                         if (attachments == "")
  1430.                             attachments = text;
  1431.                         else
  1432.                             attachments = attachments + "," + text;
  1433.                     }
  1434.                 }
  1435.             }
  1436.         }
  1437.     }
  1438.  
  1439.     return attachments;
  1440. }
  1441.  
  1442. function RemoveSelectedAttachment()
  1443. {
  1444.     var bucketTree = document.getElementById("attachmentBucket");
  1445.     if ( bucketTree )
  1446.     {
  1447.         var body = document.getElementById("bucketBody");
  1448.         
  1449.         if ( body && bucketTree.selectedItems && bucketTree.selectedItems.length )
  1450.         {
  1451.             for ( var item = bucketTree.selectedItems.length - 1; item >= 0; item-- )
  1452.                 body.removeChild(bucketTree.selectedItems[item]);
  1453.         }    
  1454.     }    
  1455.     
  1456. }
  1457.  
  1458. function AttachVCard()
  1459. {
  1460.     dump("AttachVCard()\n");
  1461. }
  1462.  
  1463. function DetermineHTMLAction(convertible)
  1464. {
  1465.     if (! msgCompose.composeHTML)
  1466.     {
  1467.         try {
  1468.             msgCompose.CheckAndPopulateRecipients(true, false);
  1469.         } catch(ex) {}
  1470.         return msgCompSendFormat.PlainText;
  1471.     }
  1472.  
  1473.     if (sendFormat == msgCompSendFormat.AskUser)
  1474.     {
  1475.         //Well, before we ask, see if we can figure out what to do for ourselves
  1476.         
  1477.         var noHtmlRecipients;
  1478.         var noHtmlnewsgroups;
  1479.  
  1480.         //Check the address book for the HTML property for each recipient
  1481.         try {
  1482.             noHtmlRecipients = msgCompose.CheckAndPopulateRecipients(true, true);
  1483.         } catch(ex)
  1484.         {
  1485.             var msgCompFields = msgCompose.compFields;
  1486.             noHtmlRecipients = msgCompFields.GetTo() + "," + msgCompFields.GetCc() + "," + msgCompFields.GetBcc();
  1487.         }
  1488.         dump("DetermineHTMLAction: noHtmlRecipients are " + noHtmlRecipients + "\n");
  1489.  
  1490.         //Check newsgroups now...
  1491.         try {
  1492.             noHtmlnewsgroups = msgCompose.GetNoHtmlNewsgroups(null);
  1493.         } catch(ex)
  1494.         {
  1495.            noHtmlnewsgroups = msgCompose.compFields.GetNewsgroups();
  1496.         }
  1497.         
  1498.         if (noHtmlRecipients != "" || noHtmlnewsgroups != "")
  1499.         {
  1500.             if (convertible == msgCompConvertible.Plain)
  1501.               return msgCompSendFormat.PlainText;
  1502.             
  1503.             if (noHtmlnewsgroups == "")
  1504.             {
  1505.                 //See if a preference has been set to tell us what to do. Note that we do not honor that
  1506.                 //preference for newsgroups. Only for e-mail addresses.
  1507.                 var action = prefs.GetIntPref("mail.default_html_action");
  1508.                 switch (action)
  1509.                 {
  1510.                     case msgCompSendFormat.PlainText    :
  1511.                     case msgCompSendFormat.HTML         :
  1512.                     case msgCompSendFormat.Both         :
  1513.                         return action;
  1514.                 }
  1515.             }
  1516.             return msgCompSendFormat.AskUser;
  1517.         }
  1518.         else
  1519.             return msgCompSendFormat.HTML;
  1520.     }
  1521.       else
  1522.       {
  1523.           try {
  1524.               msgCompose.CheckAndPopulateRecipients(true, false);
  1525.           } catch(ex) {}
  1526.       }
  1527.  
  1528.     return sendFormat;
  1529. }
  1530.  
  1531. function DetermineConvertibility()
  1532. {
  1533.     if (!msgCompose.composeHTML)
  1534.         return msgCompConvertible.Plain;
  1535.  
  1536.     try {
  1537.         return msgCompose.bodyConvertible();
  1538.     } catch(ex) {}
  1539.     return msgCompConvertible.No;
  1540. }
  1541.  
  1542. function LoadIdentity(startup)
  1543. {
  1544.     var identityElement = document.getElementById("msgIdentity");    
  1545.     var prevIdentity = currentIdentity;
  1546.     
  1547.     if (identityElement) {
  1548.         var item = identityElement.selectedItem;
  1549.         var idKey = item.getAttribute('id');
  1550.         currentIdentity = accountManager.getIdentity(idKey);
  1551.  
  1552.         if (!startup && prevIdentity && idKey != prevIdentity.key)
  1553.         {
  1554.           var prevReplyTo = prevIdentity.replyTo;
  1555.           var prevBcc = "";
  1556.           if (prevIdentity.bccSelf)
  1557.             prevBcc += prevIdentity.email;
  1558.           if (prevIdentity.bccOthers)
  1559.           {
  1560.             if (prevBcc != "")
  1561.               prevBcc += ","
  1562.             prevBcc += prevIdentity.bccList; 
  1563.           }
  1564.           
  1565.           var newReplyTo = currentIdentity.replyTo;
  1566.           var newBcc = "";
  1567.           if (currentIdentity.bccSelf)
  1568.             newBcc += currentIdentity.email;
  1569.           if (currentIdentity.bccOthers)
  1570.           {
  1571.             if (newBcc != "")
  1572.               newBcc += ","
  1573.             newBcc += currentIdentity.bccList; 
  1574.           }
  1575.  
  1576.           var needToCleanUp = false;
  1577.           var msgCompFields = msgCompose.compFields;
  1578.  
  1579.           if (newReplyTo != prevReplyTo)
  1580.           {
  1581.             needToCleanUp = true;
  1582.             if (prevReplyTo != "")
  1583.               awRemoveRecipients(msgCompFields, "addr_reply", prevReplyTo);
  1584.             if (newReplyTo != "")
  1585.               awAddRecipients(msgCompFields, "addr_reply", newReplyTo);
  1586.           }
  1587.           
  1588.           if (newBcc != prevBcc)
  1589.           {
  1590.             needToCleanUp = true;
  1591.             if (prevBcc != "")
  1592.               awRemoveRecipients(msgCompFields, "addr_bcc", prevBcc);
  1593.             if (newReplyTo != "")
  1594.               awAddRecipients(msgCompFields, "addr_bcc", newBcc);
  1595.           }          
  1596.           
  1597.           if (needToCleanUp)
  1598.             awCleanupRows();
  1599.  
  1600.           try {
  1601.             msgCompose.SetSignature(currentIdentity);
  1602.           } catch (ex) { dump("### Cannot set the signature: " + ex + "\n");}
  1603.         }
  1604.         
  1605.         //Setup autocomplete session, we can doit from here as it's use as a service
  1606.         var session = Components.classes["@mozilla.org/autocompleteSession;1?type=addrbook"].getService(Components.interfaces.nsIAbAutoCompleteSession);
  1607.         if (session)
  1608.         {
  1609.             var emailAddr = currentIdentity.email;
  1610.             var start = emailAddr.lastIndexOf("@");
  1611.             session.defaultDomain = emailAddr.slice(start + 1, emailAddr.length);
  1612.         }
  1613.     }   
  1614. }
  1615.  
  1616.  
  1617. function subjectKeyPress(event) 
  1618. {
  1619.   switch(event.keyCode) {
  1620.   case 9: 
  1621.     if (!event.shiftKey) {
  1622.       window._content.focus();
  1623.       event.preventDefault();
  1624.     }
  1625.     break;
  1626.   case 13:
  1627.     window._content.focus();
  1628.     break;
  1629.   }
  1630. }
  1631.  
  1632. function editorKeyPress(event)
  1633. {
  1634.   if (event.keyCode == 9) {
  1635.     if (event.shiftKey) {
  1636.       document.getElementById('msgSubject').focus();
  1637.       event.preventDefault();
  1638.     }
  1639.   }
  1640. }
  1641.  
  1642. function AttachmentBucketClicked(event)
  1643. {
  1644.   if (event.originalTarget.localName == 'treechildren')
  1645.     goDoCommand('cmd_attachFile');
  1646. }  
  1647.  
  1648. var attachmentBucketObserver = {
  1649.   onDrop: function (aEvent, aData, aDragSession)
  1650.     {
  1651.       aData = aData.length ? aData[0] : aData;
  1652.       if (aData.flavour != "application/x-moz-file") 
  1653.         return;
  1654.     
  1655.       var dataObj = aData.data.data.QueryInterface(Components.interfaces.nsIFile);
  1656.       if (!dataObj) 
  1657.         return;
  1658.         
  1659.       var fileURL = nsJSComponentManager.createInstance("@mozilla.org/network/standard-url;1", "nsIFileURL");
  1660.       fileURL.file = dataObj;
  1661.         AddAttachment(fileURL.spec);
  1662.     },
  1663.     
  1664.   onDragOver: function (aEvent, aFlavour, aDragSession)
  1665.     {
  1666.       if (aFlavour != "application/x-moz-file")
  1667.         return;
  1668.       var attachmentBucket = document.getElementById("attachmentBucket");
  1669.       attachmentBucket.setAttribute("dragover", "true");
  1670.     },
  1671.     
  1672.   onDragExit: function (aEvent, aDragSession)
  1673.     {
  1674.       var attachmentBucket = document.getElementById("attachmentBucket");
  1675.       attachmentBucket.removeAttribute("dragover");
  1676.     },
  1677.         
  1678.   getSupportedFlavours: function ()
  1679.     {
  1680.       var flavourList = { };
  1681.       flavourList["application/x-moz-file"] = { width: 2, iid: "nsIFile" };
  1682.       return flavourList;
  1683.     }  
  1684. };
  1685.