]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/javascript/EmailUI.js
Release 6.5.0
[Github/sugarcrm.git] / modules / Emails / javascript / EmailUI.js
1 /*********************************************************************************
2  * SugarCRM Community Edition is a customer relationship management program developed by
3  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
4  * 
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU Affero General Public License version 3 as published by the
7  * Free Software Foundation with the addition of the following permission added
8  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
11  * 
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
15  * details.
16  * 
17  * You should have received a copy of the GNU Affero General Public License along with
18  * this program; if not, see http://www.gnu.org/licenses or write to the Free
19  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20  * 02110-1301 USA.
21  * 
22  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
24  * 
25  * The interactive user interfaces in modified source and object code versions
26  * of this program must display Appropriate Legal Notices, as required under
27  * Section 5 of the GNU Affero General Public License version 3.
28  * 
29  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30  * these Appropriate Legal Notices must retain the display of the "Powered by
31  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32  * technical reasons, the Appropriate Legal Notices must display the words
33  * "Powered by SugarCRM".
34  ********************************************************************************/
35
36
37 (function() {
38         var sw = YAHOO.SUGAR,
39                 Event = YAHOO.util.Event,
40                 Connect = YAHOO.util.Connect,
41             Dom = YAHOO.util.Dom
42             SE = SUGAR.email2;
43
44 ///////////////////////////////////////////////////////////////////////////////
45 ////    EMAIL ACCOUNTS
46 SE.accounts = {
47     outboundDialog : null,
48     inboundAccountEditDialog : null,
49     inboundAccountsSettingsTable : null,
50     outboundAccountsSettingsTable : null,
51     testOutboundDialog : null,
52     errorStyle : 'input-error',
53     normalStyle : '',
54     newAddedOutboundId : '',
55
56     /**
57      * makes async call to retrieve an outbound instance for editting
58      */
59      //EXT111
60     editOutbound : function(obi) {
61
62             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
63
64     },
65     deleteOutbound : function(obi) {
66
67         if(obi.match(/^(add|line|sendmail)+/)) {
68             alert('Invalid Operation');
69         } else {
70                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
71             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
72         }
73     },
74     //EXT111
75     getReplyAddress : function() {
76         var primary = '';
77
78         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
79             var addy = SE.userPrefs.current_user.emailAddresses[i];
80
81             if(addy.primary_address == "1") {
82                 primary = addy.email_address;
83             }
84
85             if(addy.reply_to == "1") {
86                 return addy.email_address;
87             }
88         }
89
90         return primary;
91     },
92
93     /**
94      * Called on "Accounts" tab activation event
95      */
96     lazyLoad : function() {
97
98         this._setupInboundAccountTable();
99         this._setupOutboundAccountTable();
100
101     },
102
103     _setupInboundAccountTable: function()
104     {
105         //Setup the inbound mail settings
106         if(!this.inboundAccountsSettingsTable)
107         {
108                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
109                                         var clckEvent = oColumn.key;
110                                         var imgSrc = "";
111                                         var is_group = oRecord.getData("is_group");
112                                         if(!is_group)
113                                         {
114                                         if(oColumn.key == 'edit')
115                                         {
116                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
117                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
118                                         }
119                                         else if(oColumn.key == 'delete')
120                                         {
121                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
122                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
123                                         }
124                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
125                                         }
126                    };
127
128                    this.showBoolean = function(el, oRecord, oColumn, oData)
129                    {
130                        var is_group = oRecord.getData("is_group");
131                        var bChecked = oData;
132                        bChecked = (bChecked) ? " checked" : "";
133                        if(!is_group)
134                        {
135                        el.innerHTML = "<input type=\"radio\"" + bChecked +
136                            " name=\"col" + oColumn.getId() + "-radio\"" +
137                            " class=\"yui-dt-radio\">";
138                        }
139                    };
140
141
142                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
143                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
144
145                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
146                                     '<img border="0" src="index.php?entryPoint=getImage&amp;imageName=helpInline.png">' +
147                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
148
149
150                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
151                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
152                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
153                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
154                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
155                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
156                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
157                 this.ieDataSource = new YAHOO.util.DataSource(query);
158                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
159                         this.ieDataSource.responseSchema = {
160                                 resultsList: "account_list",
161                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
162                         };
163                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
164                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
165
166                     var elCheckbox = oArgs.target;
167                     var oColumn = this.getColumn(elCheckbox);
168                         if(oColumn.key == 'is_active')
169                         {
170                                 var oRecord = this.getRecord(elCheckbox);
171                                 oRecord.setData("is_active",elCheckbox.checked);
172                                 var t_id = oRecord.getData('id');
173                         var isGroupFolder = oRecord.getData('has_groupfolder');
174
175                         if(isGroupFolder)
176                             SUGAR.email2.folders.updateSubscriptions();
177                         else
178                         SUGAR.email2.folders.setFolderSelection();
179
180                         }
181                 });
182                         var lastDefaultSelectedId = "";
183                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
184
185                     var elRadio = oArgs.target;
186                     var oColumn = this.getColumn(elRadio);
187                         if(oColumn.key == 'is_default')
188                         {
189                                 var oRecord = this.getRecord(elRadio);
190                                 var t_id = oRecord.getData('id');
191                                 var t_isGroup = oRecord.getData('is_group');
192                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
193                                 {
194                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
195                                         lastDefaultSelectedId = t_id;
196                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
197                                 }
198                                 else if(t_isGroup)
199                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
200
201                         }
202                 });
203
204                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
205                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
206         }
207     },
208      _setupOutboundAccountTable: function()
209     {
210         if(!this.outboundAccountsSettingsTable)
211         {
212                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
213                                         var clckEvent = oColumn.key;
214                                         var imgSrc = "";
215                                         var isEditable = oRecord.getData("is_editable");
216                                         var type = oRecord.getData("type");
217                                         if(isEditable)
218                                         {
219                                         if(oColumn.key == 'edit')
220                                         {
221                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
222                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
223                                         }
224                                         else if(oColumn.key == 'delete' && type == 'user')
225                                         {
226                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
227                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
228                                         }
229                                         if(imgSrc != '')
230                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
231                                         }
232                 };
233
234                 //Custom formatter to display any error messages.
235                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
236
237                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
238                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
239
240                         var id = oRecord.getData('id');
241                                         var message = oRecord.getData("errors");
242                                         if(message != '')
243                                         {
244                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
245                                         //Add the id and message for all outbound accounts.
246                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
247                                         }
248                                         else
249                                         {
250                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
251                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
252                                         }
253                 };
254                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
255                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
256
257                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
258                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
259                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
260                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
261
262                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
263                 this.obDataSource = new YAHOO.util.DataSource(query);
264                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
265                         this.obDataSource.responseSchema = {
266
267                                 resultsList: "outbound_account_list",
268                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
269                         };
270
271                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
272
273
274                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
275                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
276                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
277         }
278     },
279     /**
280      * Displays a modal diaglogue to edit outbound account settings
281      */
282     showEditInboundAccountDialogue : function(clear) {
283
284         if(!this.inboundAccountEditDialog) {
285                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
286                 modal:true,
287                                 visible:true,
288                 fixedcenter:true,
289                 constraintoviewport: true,
290                 width   : "600px",
291                 shadow  : true
292             });
293                         EAD.showEvent.subscribe(function() {
294                 var el = this.element;
295                 var viewH = YAHOO.util.Dom.getViewportHeight();
296                 if (this.header && el && viewH - 50 < el.clientHeight) {
297                     var body = this.header.nextElementSibling;
298                                         body.style.overflow = "hidden";
299                     body.style.height = "100%";
300                 }
301             }, EAD);
302             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
303                         Dom.removeClass("editAccountDialogue", "yui-hidden");
304
305         } // end lazy load
306
307         if(clear == undefined || clear == true)
308         {
309                 SE.accounts.clearInboundAccountEditScreen();
310                 //Set default protocol to IMAP when creating new records
311                 document.forms['ieAccount'].elements['protocol'].value = "imap";
312                 SE.accounts.setPortDefault();
313         }
314
315         //Check if we should display username/password fields for outbound account if errors were detected.
316         this.checkOutBoundSelection();
317
318         this.inboundAccountEditDialog.render();
319         this.inboundAccountEditDialog.show();
320         SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
321     },
322
323     /**
324     *  Set all fields on the outbound edit form to either enabled/disabled
325     *  except for the username/password.
326     *
327     */
328     toggleOutboundAccountDisabledFields: function(disable)
329     {
330         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
331         for(var i=0;i<fields.length;i++)
332         {
333             document.getElementById(fields[i]).disabled = disable;
334         }
335         if(disable)
336             Dom.addClass("mail_smtpssl_row", "yui-hidden");
337         else
338             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
339
340     },
341     /**
342     * Refresh the inbound accounts table.
343     */
344     refreshInboundAccountTable : function()
345     {
346             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
347                 {
348                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
349                                 scope: this.inboundAccountsSettingsTable }
350                         );
351     },
352     /**
353     * Refresh the outbound accounts table.
354     */
355     refreshOuboundAccountTable : function()
356     {
357             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
358                 {
359                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
360                                 scope: this.outboundAccountsSettingsTable }
361                         );
362     },
363     /**
364      * Displays a modal diaglogue to add a SMTP server
365      */
366     showAddSmtp : function() {
367         // lazy load dialogue
368         if(!this.outboundDialog) {
369                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
370                 modal:true,
371                                 visible:true,
372                 fixedcenter:true,
373                 constraintoviewport: true,
374                 width   : "750px",
375                 shadow  : true
376             });
377             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
378             this.outboundDialog.hideEvent.subscribe(function(){
379                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
380                 var out = Dom.get("outbound_email");
381                 if (out && out.value == "SYSTEM_ADD")
382                 {
383                         out.value = out.options[0].value;
384                 }
385                 //Check if we should display username/password for system account.
386                 SE.accounts.checkOutBoundSelection();
387                 return true;
388             });
389
390             Dom.removeClass("outboundDialog", "yui-hidden");
391         } // end lazy load
392
393         // clear out form
394         var form = document.getElementById('outboundEmailForm');
395         for(i=0; i<form.elements.length; i++) {
396             if(form.elements[i].name == 'mail_smtpport') {
397                 form.elements[i].value = 25;
398             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
399                 form.elements[i].value = '';
400             } else if(form.elements[i].type == 'checkbox') {
401                 form.elements[i].checked = false;
402             }
403         }
404         //Render the SMTP buttons
405         if ( !SUGAR.smtpButtonGroup ) {
406             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
407             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
408             {
409                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
410                 document.getElementById('smtp_settings').style.display = '';
411                 form.mail_smtptype.value = e.newValue.get('value');
412             });
413             YAHOO.widget.Button.addHiddenFieldsToForm(form);
414         }
415         //Hide Username/Password
416         SUGAR.email2.accounts.smtp_authenticate_field_display();
417         //Unset readonly fields
418         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
419         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
420                 this.outboundDialog.render();
421         this.outboundDialog.show();
422     },
423
424     /**
425      * Accounts' Advanced Settings view toggle
426      */
427     toggleAdv : function() {
428         var adv = document.getElementById("ie_adv");
429         if(adv.style.display == 'none') {
430             adv.style.display = "";
431         } else {
432             adv.style.display = 'none';
433         }
434     },
435
436         smtp_authenticate_field_display : function() {
437                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
438                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
439                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
440         },
441
442         smtp_setDefaultSMTPPort : function() {
443                 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
444
445         if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
446             document.getElementById("mail_smtpport").value = '465';
447         }
448         if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
449             document.getElementById("mail_smtpport").value = '25';
450         }
451         },
452
453     /**
454      * Changes the display used in the outbound email SMTP dialog to match the
455      */
456     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
457     {
458         document.getElementById("smtpButtonGroupTD").style.display = '';
459         document.getElementById("chooseEmailProviderTD").style.display = '';
460         document.getElementById("mailsettings1").style.display = '';
461         document.getElementById("mailsettings2").style.display = '';
462         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
463         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
464         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
465         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
466
467         switch (smtptype) {
468         case "yahoomail":
469             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
470             document.getElementById("mail_smtpport").value = '465';
471             document.getElementById("mail_smtpauth_req").checked = true;
472             var ssl = document.getElementById("mail_smtpssl");
473             for(var j=0;j<ssl.options.length;j++) {
474                 if(ssl.options[j].text == 'SSL') {
475                     ssl.options[j].selected = true;
476                     break;
477                 }
478             }
479             document.getElementById("mailsettings1").style.display = 'none';
480             document.getElementById("mailsettings2").style.display = 'none';
481             document.getElementById("mail_smtppass_label").innerHTML =
482             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
483             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
484             break;
485         case "gmail":
486             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
487             document.getElementById("mail_smtpport").value = '587';
488             document.getElementById("mail_smtpauth_req").checked = true;
489             var ssl = document.getElementById("mail_smtpssl");
490             for(var j=0;j<ssl.options.length;j++) {
491                 if(ssl.options[j].text == 'TLS') {
492                     ssl.options[j].selected = true;
493                     break;
494                 }
495             }
496             document.getElementById("mailsettings1").style.display = 'none';
497             document.getElementById("mailsettings2").style.display = 'none';
498             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
499             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
500             break;
501         case "exchange":
502             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
503                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
504                 document.getElementById("mail_smtpserver").value = '';
505             }
506             document.getElementById("mail_smtpport").value = '25';
507             document.getElementById("mail_smtpauth_req").checked = true;
508             document.getElementById("mailsettings1").style.display = '';
509             document.getElementById("mailsettings2").style.display = '';
510             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
511             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
512             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
513             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
514             break;
515         }
516         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
517         {
518             document.getElementById("smtpButtonGroupTD").style.display = 'none';
519             document.getElementById("chooseEmailProviderTD").style.display = 'none';
520             document.getElementById("mailsettings2").style.display = 'none';
521         }
522
523         SUGAR.email2.accounts.smtp_authenticate_field_display();
524         SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
525     },
526
527     /**
528     * Fill the gmail default values for inbound accounts.
529     */
530     fillInboundGmailDefaults: function () {
531
532         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
533         document.forms['ieAccount'].elements['ssl'].checked = true;
534         document.forms['ieAccount'].elements['protocol'].value = "imap";
535         SUGAR.email2.accounts.setPortDefault();
536         SUGAR.util.setEmailPasswordDisplay('email_password', false);
537     },
538     /**
539      * Sets Port field to selected protocol and SSL settings defaults
540      */
541     setPortDefault : function() {
542         var prot = document.getElementById('protocol');
543         var ssl  = document.getElementById('ssl');
544         var port = document.getElementById('port');
545         var stdPorts= new Array("110", "143", "993", "995");
546         var stdBool    = new Boolean(false);
547         var mailboxdiv = document.getElementById("mailboxdiv");
548         var trashFolderdiv = document.getElementById("trashFolderdiv");
549         var sentFolderdiv = document.getElementById("sentFolderdiv");
550                 var monitoredFolder = document.getElementById("subscribeFolderButton");
551         if(port.value == '') {
552             stdBool.value = true;
553         } else {
554             for(i=0; i<stdPorts.length; i++) {
555                 if(stdPorts[i] == port.value) {
556                     stdBool.value = true;
557                 }
558             }
559         }
560
561         if(stdBool.value == true) {
562             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
563                 port.value = "143";
564             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
565                 port.value = '993';
566             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
567                 port.value = '110';
568             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
569                 port.value = '995';
570             }
571         }
572
573         if (prot.value == 'imap') {
574                 mailboxdiv.style.display = "";
575                 trashFolderdiv.style.display = "";
576                 sentFolderdiv.style.display = "";
577                 monitoredFolder.style.display = "";
578                 if (document.getElementById('mailbox').value == "") {
579                         document.getElementById('mailbox').value = "INBOX";
580                 }
581         } else {
582                 mailboxdiv.style.display = "none";
583                 trashFolderdiv.style.display = "none";
584                 sentFolderdiv.style.display = "none";
585                         monitoredFolder.style.display = "none";
586                 document.getElementById('mailbox').value = "";
587         } // else
588     },
589
590     /**
591      * Draws/removes red boxes around required fields.
592      */
593     ieAccountError : function(style) {
594         document.getElementById('server_url').className = style;
595         document.getElementById('email_user').className = style;
596         document.getElementById('email_password').className = style;
597         document.getElementById('protocol').className = style;
598         document.getElementById('port').className = style;
599     },
600
601     checkOutBoundSelection: function() {
602         var select = Dom.get('outbound_email');
603         if (!select || select.selectedIndex == -1) { return; }
604
605         var v = select.options[select.selectedIndex].value;
606
607         if(v == '')
608         {
609                 select.options[select.selectedIndex].selected = false;
610                 v = select.options[0].value;
611         }
612         else if (v == 'SYSTEM_ADD')
613                 SUGAR.email2.accounts.showAddSmtp();
614
615         var foundError = false;
616         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
617                 for(i in errorAccounts)
618                 {
619                     if(v == i)
620                     {
621                         foundError = true;
622                         break;
623                     }
624                 }
625
626                 //Should username/password fields for outbound account.
627                 if(foundError)
628                     this.toggleInboundOutboundFields(true);
629                 else
630                     this.toggleInboundOutboundFields(false);
631
632
633
634     },
635     toggleInboundOutboundFields : function (display)
636     {
637         if(display)
638         {
639             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
640                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
641         }
642         else
643         {
644             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
645                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
646         }
647     },
648     /**
649      * rebuilds the select options for mailer options
650      */
651     rebuildMailerOptions : function() {
652         var select = document.forms['ieAccount'].elements['outbound_email'];
653         SE.util.emptySelectOptions(select);
654
655         //Get the available sugar mailers
656         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
657
658         for(i=0;i<a_outbound.length;i++)
659         {
660                 var t_record = a_outbound[i];
661                 var key = t_record.getData('id');
662                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
663
664                 var opt = new Option(display, key);
665                 select.options.add(opt);
666                 if (key == SE.accounts.newAddedOutboundId) {
667                         select.options.selectedIndex = i;
668                 }
669         }
670
671         select.options.add(new Option('',''));
672         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
673         //Hide/Show username password fields if necessary.
674         SE.accounts.checkOutBoundSelection();
675     },
676     /**
677      * Empties all the fields in the accounts edit view
678      */
679     clearInboundAccountEditScreen:function() {
680
681         document.getElementById('ie_id').value = '';
682         document.getElementById('ie_name').value = '';
683         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
684         document.getElementById('ie_from_addr').value = this.getReplyAddress();
685         document.getElementById('reply_to_addr').value = '';
686         document.getElementById('server_url').value = '';
687         document.getElementById('email_user').value = '';
688         document.getElementById('email_password').value = '';
689         document.getElementById('port').value = '';
690         document.getElementById('inbound_mail_smtpuser').value = '';
691         document.getElementById('inbound_mail_smtppass').value = '';
692         document.ieAccount.protocol.options[0].selected = true;
693         // handle SSL
694         document.getElementById('ssl').checked = false;
695         SUGAR.util.setEmailPasswordDisplay('email_password', false);
696     },
697
698     /**
699      * Populates an account's fields in Settings->Accounts
700      */
701     fillIeAccount:function(jsonstr) {
702         var o = YAHOO.lang.JSON.parse(jsonstr);
703
704         document.getElementById('ie_id').value = o.id;
705         document.getElementById('ie_name').value = o.name;
706         if (o.stored_options != null) {
707                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
708                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
709                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
710                 if (o.stored_options.trashFolder != null) {
711                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
712                 }
713                 if (o.stored_options.sentFolder != null) {
714                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
715                 }
716         }
717         document.getElementById('server_url').value = o.server_url;
718         document.getElementById('email_user').value = o.email_user;
719         document.getElementById('port').value = o.port;
720         document.getElementById('group_id').value = o.group_id;
721         document.getElementById('mailbox').value = o.mailbox;
722
723
724         var i = 0;
725
726         // handle SSL
727         if(typeof(o.service[2]) != 'undefined') {
728             document.getElementById('ssl').checked = true;
729         }
730
731         // handle protocol
732         if(document.getElementById('protocol').value != o.protocol) {
733             var prot = document.getElementById('protocol');
734             for(i=0; i<prot.options.length; i++) {
735                 if(prot.options[i].value == o.service[3]) {
736                     prot.options[i].selected = true;
737                     this.setPortDefault();
738                 }
739             }
740         }
741  // handle SMTP selection
742         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
743             var opts = document.getElementById('outbound_email').options;
744             for(i=0; i<opts.length; i++) {
745                 if(opts[i].value == o.stored_options.outbound_email) {
746                     opts[i].selected = true;
747                 }
748             }
749         }
750     },
751
752     deleteIeAccount : function(IeAccountID,IeGroupID) {
753         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
754         {
755             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
756
757             AjaxObject.target = 'frameFlex';
758             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
759             SUGAR.email2.accounts.refreshInboundAccountTable();
760          }
761      },
762
763        // Null check for Outbound Settings.
764     checkOutboundSettings: function() {
765         var errorMessage = '';
766         var isError = false;
767         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
768             var mailName = document.getElementById('mail_name').value;
769             var smtpServer = document.getElementById('mail_smtpserver').value;
770             var smtpPort = document.getElementById('mail_smtpport').value;
771
772             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
773             if(trim(mailName) == '') {
774                 isError = true;
775                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
776             }
777             if(trim(smtpServer) == '') {
778                 isError = true;
779                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
780             }
781             if(trim(smtpPort) == '') {
782                 isError = true;
783                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
784             }
785             if(mailsmtpauthreq.checked) {
786                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
787                     isError = true;
788                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
789                 }
790             }
791         }
792         if(isError) {
793             SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
794             return false;
795         } else {
796             return true;
797         }
798     },
799
800     testOutboundSettings: function() {
801         var errorMessage = '';
802         var isError = false;
803         var fromAddress = document.getElementById("outboundtest_from_address").value;
804         if (trim(fromAddress) == "") {
805             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
806             SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
807             return false;
808
809         }
810         else if (!isValidEmail(fromAddress)) {
811             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
812             SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
813             return false;
814         }
815
816         //Hide the dialogue and show an in progress indicator.
817         SE.accounts.testOutboundDialog.hide();
818         SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
819
820         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
821         //nothing is sent in the request.
822         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
823         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
824
825         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
826         if(outboundType == 'system-override')
827             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
828
829         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
830         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
831
832     },
833
834     testOutboundSettingsDialog: function() {
835         //Ensure that all settings are correct before proceeding to send test email.
836         if(!SE.accounts.checkOutboundSettings())
837             return;
838
839         // lazy load dialogue
840         if(!SE.accounts.testOutboundDialog) {
841                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
842                 modal:true,
843                                 visible:true,
844                 fixedcenter:true,
845                 constraintoviewport: true,
846                 width   : 600,
847                 shadow  : true
848             });
849             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
850             Dom.removeClass("testOutboundDialog", "yui-hidden");
851         } // end lazy load
852         SE.accounts.testOutboundDialog.render();
853         SE.accounts.testOutboundDialog.show();
854     },
855
856     /**
857      * Saves Outbound email settings
858      */
859     saveOutboundSettings : function() {
860         if(SE.accounts.checkOutboundSettings()) {
861             //Enable the form fields for the post.
862             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
863             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
864             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
865         } else {
866             return false;
867         }
868     },
869
870     saveIeAccount : function() {
871
872         //Before saving check if there are any error messages associated with the outbound account.
873         var outboundID = document.getElementById('outbound_email').value;
874
875         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
876             'validateSMTPCreds':true}) )
877         {
878             document.getElementById('saveButton').disabled = true;
879
880             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
881
882             var formObject = document.getElementById('ieAccount');
883             YAHOO.util.Connect.setForm(formObject);
884
885             AjaxObject._reset();
886             AjaxObject.target = 'frameFlex';
887             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
888         }
889     },
890
891     testSettings : function() {
892         form = document.getElementById('ieAccount');
893
894         if(SE.accounts.checkIeCreds()) {
895             ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount", form.ie_id.value);
896         }
897     },
898
899     getFoldersListForInboundAccountForEmail2 : function() {
900         form = document.getElementById('ieAccount');
901         if(SE.accounts.checkIeCreds()) {
902                 var mailBoxValue = form.mailbox.value;
903                 if (form.searchField.value.length > 0) {
904                         mailBoxValue = "";
905                 } // if
906             getFoldersListForInboundAccount("InboundEmail", "ShowInboundFoldersList", "Popup", 400, 300, form.server_url.value, form.protocol.value, form.port.value, form.email_user.value, Rot13.write(form.email_password.value), mailBoxValue, form.ssl.checked, true, form.searchField.value );
907         } // if
908
909     },
910
911     checkIeCreds : function(validateRules) {
912         if(typeof(validateRules) == 'undefined')
913             validateRules = {};
914
915         var errors = new Array();
916         var out = new String();
917
918         var ie_name = Dom.get('ie_name').value;
919         var fromAddress = Dom.get('ie_from_addr').value;
920         var server_url = Dom.get('server_url').value;
921         var email_user = Dom.get('email_user').value;
922         var email_password = Dom.get('email_password').value;
923         var protocol = Dom.get('protocol').value;
924         var port = Dom.get('port').value;
925         var oe = Dom.get('outbound_email');
926
927         // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
928         // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
929         // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
930         var oe_value = (typeof(oe.options[oe.selectedIndex]) === 'undefined' || typeof(oe.options[oe.selectedIndex]) === 'unknown' || typeof(oe.options[oe.selectedIndex]) === null) ? "" : oe.options[oe.selectedIndex].value;
931
932         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
933         var outboundPass = Dom.get('inbound_mail_smtppass').value;
934
935         //If the username and password were provided then ignore the error messge
936
937         var outboundCredentialsFound = false;
938
939         if(outboundUserName != "" && outboundPass != "")
940             outboundCredentialsFound = true;
941
942         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
943
944         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
945              && validateSMTPCreds)
946         {
947             if(trim(outboundUserName) == "") {
948                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
949             }
950             if(trim(outboundPass) == "") {
951                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
952             }
953         }
954
955         if(trim(ie_name) == "") {
956             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
957         }
958
959         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
960         {
961             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
962                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
963             }
964         }
965
966
967         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
968              || trim(oe_value) == "SYSTEM_ADD") ) {
969             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
970         }
971         if(trim(server_url) == "") {
972             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
973         }
974         if(trim(email_user) == "") {
975             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
976         }
977         if(protocol == "") {
978             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
979         }
980         if (protocol == 'imap') {
981                 var mailbox = document.getElementById('mailbox').value;
982                 if (trim(mailbox) == "") {
983                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
984                 } // if
985                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
986                         var trashFolder = document.getElementById('trashFolder').value;
987                         if (trim(trashFolder) == "") {
988                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
989                         } // if
990                         } // if
991         }
992         if(port == "") {
993             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
994         }
995
996         if(errors.length > 0) {
997             out = app_strings.LBL_EMAIL_ERROR_DESC;
998             for(i=0; i<errors.length; i++) {
999                 if(out != "") {
1000                     out += "\n";
1001                 }
1002                 out += errors[i];
1003             }
1004
1005             alert(out);
1006             return false;
1007         } else {
1008
1009             return true;
1010         }
1011     },
1012
1013     getIeAccount : function(ieId) {
1014         if(ieId == '')
1015             return;
1016
1017         SUGAR.showMessageBox(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1018                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1019
1020         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1021     },
1022
1023     /**
1024      * Iterates through TreeView nodes to apply styles dependent nature of node
1025      */
1026     renderTree:function() {
1027         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1028         SE.tree.render();
1029     },
1030
1031     //Sets the style for any nodes that need it.
1032     setNodeStyle : function(node) {
1033         if (!node.data.origText) {
1034             node.data.origText = node.data.text;
1035         }
1036         //Set unread
1037         if (typeof(node.data.unseen) != 'undefined') {
1038                 if (node.data.unseen > 0) {
1039                                 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1040                 // Add bold style to label, kinda hacky
1041                 node.labelStyle += " ygtvlabelbold";
1042                         }
1043                         else {
1044                                 node.setUpLabel(node.data.origText);
1045                         }
1046         } else {
1047                 node.setUpLabel(node.data.origText);
1048         }
1049         SE.accounts.setupDDTarget(node);
1050     },
1051
1052     setupDDTarget : function(node) {
1053         if (node.ddTarget) {
1054                 node.ddTarget.removeFromGroup();
1055                 delete node.ddTarget;
1056         }
1057         var id = node.getElId();
1058         var num = id.substring(4);
1059         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1060                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1061                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1062
1063                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1064         }
1065         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1066                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1067         }
1068     },
1069
1070     /**
1071      * Async call to rebuild the folder list.  After a folder delete or account delete
1072      */
1073     rebuildFolderList : function() {
1074         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1075         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1076     },
1077
1078     /**
1079      * Returns the number of remote accounts the user has active.
1080      */
1081     getAccountCount : function() {
1082         var tree = SE.tree;
1083         var count = 0;
1084         for(i=0; i<tree._nodes.length; i++) {
1085             var node = tree._nodes[i];
1086
1087             if(typeof(node) != 'undefined' && node.data.ieId) {
1088                 count++;
1089             }
1090         }
1091         return count;
1092     }
1093 };
1094 ////    END ACCOUNTS
1095 ///////////////////////////////////////////////////////////////////////////////
1096
1097
1098
1099
1100 ///////////////////////////////////////////////////////////////////////////////
1101 ////    CONTEXT MENU CALLS
1102 SE.contextMenus = {
1103
1104     assignToDialogue : null,
1105     /**
1106      * Archives from context menu
1107      * @param Array uids
1108      * @param string ieId
1109      * @param string folder
1110      */
1111     _archiveToSugar : function(uids, ieId, folder) {
1112         var ser = '';
1113
1114         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1115             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1116             ser += uids[i];
1117         }
1118         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1119     },
1120
1121     /**
1122      * Archives from context menu
1123      */
1124     archiveToSugar : function(menuItem) {
1125         SE.contextMenus.emailListContextMenu.hide();
1126
1127         var rows = SE.grid.getSelectedRows();
1128         var uids = [];
1129         /* iterate through available rows JIC a row is deleted - use first available */
1130         for(var i=0; i<rows.length; i++) {
1131             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1132         }
1133         var data = SE.grid.getRecord(rows[0]).getData();
1134         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1135     },
1136
1137     /**
1138      * Popup the printable version and start system's print function.
1139      */
1140     viewPrintable : function(menuItem) {
1141         var rows = SE.grid.getSelectedRows();
1142         var data = SE.grid.getRecord(rows[0]).getData();
1143         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1144     },
1145
1146     /**
1147      * Marks email flagged on mail server
1148      */
1149     markRead : function(type, contextMenuId) {
1150         SE.contextMenus.markEmail('read');
1151     },
1152
1153     /**
1154      * Assign this emails to people based on assignment rules
1155      */
1156     assignEmailsTo : function(type, contextMenuId) {
1157         if(!SE.contextMenus.assignToDialogue)
1158         {
1159                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1160                 modal:true,
1161                                 visible:false,
1162                 fixedcenter:true,
1163                 constraintoviewport: true,
1164                 width   : "600px",
1165                 shadow  : true
1166             });
1167             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1168             enableQS(true);
1169         }
1170
1171         Dom.removeClass("assignToDiv", "yui-hidden");
1172         SE.contextMenus.assignToDialogue.render();
1173         SE.contextMenus.assignToDialogue.show();
1174     },
1175
1176     /**
1177      * Marks email flagged on mail server
1178      */
1179     markFlagged : function(contextMenuId) {
1180         SE.contextMenus.markEmail('flagged');
1181     },
1182
1183     /**
1184      * Marks email unflagged on mail server
1185      */
1186     markUnflagged : function(contextMenuId) {
1187         SE.contextMenus.markEmail('unflagged');
1188     },
1189
1190     /**
1191      * Marks email unread on mail server
1192      */
1193     markUnread : function() {
1194         SE.contextMenus.markEmail('unread');
1195     },
1196
1197     /**
1198      * Deletes an email from context menu
1199      */
1200     markDeleted : function() {
1201         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1202                 document.getElementById('_blank').innerHTML = "";
1203                 SE.contextMenus.markEmail('deleted');
1204         }
1205     },
1206
1207     /**
1208      * generic call API to apply a flag to emails on the server and on sugar
1209      * @param string type "read" | "unread" | "flagged" | "deleted"
1210      */
1211     markEmail : function(type) {
1212         SE.contextMenus.emailListContextMenu.hide();
1213
1214         //var dm = SE.grid.getStore();
1215         //var uids = SE.grid.getSelectedRowIds();
1216         //var indexes = SE.grid.getSelectedRowIndexes();
1217         var rows = SE.grid.getSelectedRows();
1218         if (rows.length == 0)
1219                 rows = [SE.contextMenus.currentRow];
1220         var ser = [ ];
1221
1222         for(var i=0; i<rows.length; i++) {
1223             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1224         }
1225
1226         ser = YAHOO.lang.JSON.stringify(ser);
1227
1228         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1229         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1230
1231
1232         var count = 0;
1233
1234
1235         if(type == 'read' || type == 'deleted') {
1236             // mark read
1237             for(var j=0; j<rows.length; j++) {
1238                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1239                     count = count + 1;
1240                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1241                 }
1242             }
1243            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1244             if(ieId){
1245             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1246             var unseenCount = node.data.unseen;
1247             if (isNaN(unseenCount)) {
1248                 unseenCount = 0;
1249             }
1250             var finalCount = parseInt(unseenCount) - count;
1251             node.data.unseen = finalCount;
1252
1253             SE.accounts.renderTree();
1254             }
1255         } else if(type == 'unread') {
1256             // mark unread
1257             for(var j=0; j<rows.length; j++) {
1258                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1259                     count = count + 1;
1260                 }
1261             }
1262
1263             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1264             var unseenCount = node.data.unseen;
1265             if (isNaN(unseenCount)) {
1266                 unseenCount = 0;
1267             }
1268             var finalCount = parseInt(unseenCount) + count;
1269             node.data.unseen = finalCount;
1270             SE.accounts.renderTree();
1271         }
1272
1273         if (type == 'unread') {
1274                 for(var i=0; i<rows.length; i++) {
1275                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1276                 } // for
1277         }
1278
1279                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1280         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1281     },
1282
1283     /**
1284      * refreshes the ListView to show changes to cache
1285      */
1286     markEmailCleanup : function() {
1287         SE.accounts.renderTree();
1288         SUGAR.hideMessageBox();
1289         SE.listView.refreshGrid();
1290     },
1291
1292         showAssignmentDialog : function() {
1293                 if (SE.contextMenus.assignmentDialog == null) {
1294                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1295                 } else {
1296                         SE.contextMenus.assignmentDialog.show();
1297                 } // else
1298         },
1299
1300         /**
1301      * shows the import dialog with only relate visible.
1302      */
1303     relateTo : function() {
1304         SE.contextMenus.emailListContextMenu.hide();
1305
1306         var rows = SE.grid.getSelectedRows();
1307         var data = SE.grid.getRecord(rows[0]).getData();
1308         var ieId = data.ieId;
1309         var folder = data.mbox;
1310         var uids = [];
1311         /* iterate through available rows JIC a row is deleted - use first available */
1312         for(var i=0; i<rows.length; i++) {
1313             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1314         }
1315         var ser = YAHOO.lang.JSON.stringify(uids);
1316
1317         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1318     },
1319
1320         /**
1321      * shows the import dialog with only relate visible.
1322      */
1323     showDetailView : function() {
1324         SE.contextMenus.emailListContextMenu.hide();
1325         var rows = SE.grid.getSelectedRows();
1326         if (rows.length > 1) {
1327                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1328                 return;
1329         }
1330         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1331         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1332         /* iterate through available rows JIC a row is deleted - use first available */
1333         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1334         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1335     },
1336
1337     /**
1338      *
1339      */
1340     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1341         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1342         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1343     },
1344
1345     /**
1346      * Opens multiple messages from ListView context click
1347      */
1348     openMultiple : function() {
1349         SE.contextMenus.emailListContextMenu.hide();
1350
1351         var rows = SE.grid.getSelectedRows();
1352         var uids = SE.listView.getUidsFromSelection();
1353
1354         if(uids.length > 0) {
1355             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1356             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1357             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1358         }
1359     },
1360
1361     /**
1362      * Replies/forwards email
1363      */
1364     replyForwardEmailContext : function() {
1365         SE.contextMenus.emailListContextMenu.hide();
1366
1367         var indexes = SE.grid.getSelectedRows();
1368         //var dm = SE.grid.getDataModel();
1369         var type = this.id;
1370
1371         for(var i=0; i<indexes.length; i++) {
1372             var row = SE.grid.getRecord(indexes[i]).getData();
1373             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1374         }
1375     },
1376
1377     //show menu functions
1378     showEmailsListMenu : function(grid, row) {
1379
1380        var data = row.getData();
1381        var draft = (data.type == "draft");
1382        var menu = SE.contextMenus.emailListContextMenu;
1383        var folderNode;
1384
1385        if (SE.tree)
1386        {
1387                if (data.mbox == 'sugar::Emails')
1388                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1389                else
1390                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1391
1392                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1393                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1394                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1395                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1396                else
1397                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1398        }
1399        else
1400            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1401
1402        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1403        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1404        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1405        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1406        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1407
1408
1409        if (data.mbox == "sugar::Emails")
1410        {
1411            //Allow users to reassign imported emails
1412            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1413            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1414            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1415            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1416        }
1417        else
1418        {
1419            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1420            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1421        }
1422     },
1423
1424     showFolderMenu : function(grid, rowIndex, event) {
1425        event.stopEvent();
1426        var coords = event.getXY();
1427        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1428     }
1429 };
1430
1431 SE.contextMenus.dv = {
1432     archiveToSugar : function(contextMenuId) {
1433
1434         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1435     },
1436
1437     replyForwardEmailContext : function(all) {
1438         SE.contextMenus.detailViewContextMenu.hide();
1439     }
1440
1441 };
1442
1443
1444
1445
1446
1447 ////    END SE.contextMenus
1448 ///////////////////////////////////////////////////////////////////////////////
1449
1450
1451
1452 ///////////////////////////////////////////////////////////////////////////////
1453 ////    DETAIL VIEW
1454 SE.detailView = {
1455     consumeMetaDetail : function(ret) {
1456         // handling if the Email drafts
1457         if(ret.type == 'draft') {
1458             SE.composeLayout.c0_composeDraft();
1459             return;
1460         }
1461
1462
1463         // cache contents browser-side
1464         SE._setDetailCache(ret);
1465
1466         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1467         // 2 below must be in global context
1468         meta = ret.meta;
1469         meta['panelId'] = SE.util.getPanelId();
1470
1471         email = ret.meta.email;
1472         var out = displayTemplate.exec({
1473             'app_strings' : app_strings,
1474             'theme' : theme,
1475             'idx' : targetDiv.id,
1476             'meta' : meta,
1477             'email' : meta.email,
1478             'linkBeans' : linkBeans
1479         });
1480         var tabLabel = meta.email.name;
1481         if (tabLabel != null && tabLabel.length > 25) {
1482                 tabLabel = tabLabel.substring(0, 25) + "...";
1483         } // if
1484         targetDiv.set("label", tabLabel);
1485         targetDiv.set("content", out);
1486
1487         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1488         if (SUGAR.email2.util.isIe()) {
1489                 displayEmailFrameDiv.style.height = "390px";
1490         } else {
1491                 displayEmailFrameDiv.style.height = "410px";
1492         }
1493
1494         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1495         displayFrame.contentWindow.document.write(email.description);
1496         displayFrame.contentWindow.document.close();
1497
1498         // hide archive links
1499         if(ret.meta.is_sugarEmail) {
1500                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1501             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1502         } else {
1503             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1504                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1505         } // else
1506
1507     },
1508
1509     consumeMetaPreview : function(ret) {
1510         // cache contents browser-side
1511         SE._setDetailCache(ret);
1512
1513
1514
1515         var currrow = SE.grid.getLastSelectedRecord();
1516         currrow = SE.grid.getRecord(currrow);
1517         if (!currrow) {
1518             document.getElementById('_blank').innerHTML = '';
1519             return;
1520         }
1521         // handling if the Email drafts
1522         if(ret.type == 'draft'){
1523             if (currrow.getData().uid == ret.uid) {
1524                 SE.composeLayout.c0_composeDraft();
1525             }
1526             return;
1527         }
1528
1529         if (currrow.getData().uid != ret.meta.uid) {
1530            return;
1531         }
1532
1533         // remove loading sprite
1534         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
1535         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1536         meta = ret.meta;
1537         meta['panelId'] = SE.util.getPanelId();
1538         email = ret.meta.email;
1539
1540         document.getElementById('_blank').innerHTML = displayTemplate.exec({
1541             'app_strings' : app_strings,
1542             'theme' : theme,
1543             'idx' : 'Preview',
1544             'meta' : meta,
1545             'email' :meta.email,
1546             'linkBeans' : linkBeans
1547         });
1548        // document.getElementById('_blank').innerHTML = meta.email;
1549        /* displayTemplate.append('_blank', {
1550             'app_strings' : app_strings,
1551             'theme' : theme,
1552             'idx' : 'Preview',
1553             'meta' : meta,
1554             'email' :meta.email,
1555             'linkBeans' : linkBeans
1556         });*/
1557
1558         var displayFrame = document.getElementById('displayEmailFramePreview');
1559         displayFrame.contentWindow.document.write(email.description);
1560         displayFrame.contentWindow.document.close();
1561
1562         SE.listViewLayout.resizePreview();
1563
1564         // hide archive links
1565         if(ret.meta.is_sugarEmail) {
1566             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
1567             document.getElementById("btnEmailViewPreview").style.display = "none";
1568             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
1569         } else {
1570           //hide view relationship link
1571                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
1572         }
1573     },
1574
1575     /**
1576      * wraps emailDelete() for single messages, comes from preview or tab
1577      */
1578     emailDeleteSingle : function(ieId, uid, mbox) {
1579         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1580             // find active panel and close if the user double clicked the email to view.
1581             var activeTabId = SE.util.getPanelId();
1582             if(activeTabId != 'Preview')
1583                 SE.innerLayout.get("activeTab").close();
1584
1585             document.getElementById('_blank').innerHTML = "";
1586                 var ser = [ ];
1587                         ser.push(uid);
1588                 uid = YAHOO.lang.JSON.stringify(ser);
1589             this.emailDelete(ieId, uid, mbox);
1590         }
1591     },
1592
1593     /**
1594      * Sends async call to delete a given message
1595      * @param
1596      */
1597     emailDelete : function(ieId, uid, mbox) {
1598        SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
1599        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
1600            uid + "&ieId=" + ieId + "&folder=" + mbox);
1601     },
1602
1603     /**
1604      * retrieves one email to display in the preview pane.
1605      */
1606     getEmailPreview : function() {
1607         var row = SUGAR.email2.listView.currentRow;
1608         var data = row.getData();
1609             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
1610                var setRead = (data['seen'] == 0) ? true : false;
1611                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
1612                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
1613             }
1614     },
1615
1616     /**
1617      * Imports one email into Sugar
1618      */
1619     importEmail : function(ieId, uid, mbox) {
1620         SE.util.clearHiddenFieldValues('emailUIForm');
1621
1622         SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
1623
1624         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
1625         AjaxObject.target = '';
1626         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
1627     },
1628
1629     /**
1630      * Populates the frameFlex div with the contents of an email
1631      */
1632     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
1633         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
1634
1635         var mboxStr = new String(mbox);
1636         var compKey = mbox + uid;
1637
1638         if(setRead == true) {
1639                 SE.listView.boldUnreadRows()
1640                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
1641         }
1642
1643         if(destination == SE.innerLayout) {
1644                 /*
1645              * loading email into a tab, peer with ListView
1646              * targetDiv must remain in the global namespace as it is used by AjaxObject
1647              */
1648                 //Check if we already have a tab of the email open
1649                 var tabs = SE.innerLayout.get("tabs");
1650                 for (var t in tabs) {
1651                         if (tabs[t].id && tabs[t].id == uid) {
1652                                 SE.innerLayout.set("activeTab", tabs[t]);
1653                                 return;
1654                         }
1655                 }
1656
1657                 targetDiv = new YAHOO.SUGAR.ClosableTab({
1658                                 label: loadingSprite,
1659                                         scroll : true,
1660                                         content : "",
1661                                         active : true
1662                 }, SE.innerLayout);
1663                 targetDiv.id = uid;
1664                 SE.innerLayout.addTab(targetDiv);
1665
1666             // use cache if available
1667             if(SE.cache[compKey]) {
1668                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
1669             } else {
1670                 // open email as peer-tab to listView
1671                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
1672                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
1673             }
1674         } else {
1675             // loading email into preview pane
1676             document.getElementById('_blank').innerHTML = loadingSprite;
1677
1678             // use cache if available
1679             if(SE.cache[compKey]) {
1680                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
1681             } else {
1682                 AjaxObject.forceAbort = true;
1683                 // open in preview window
1684                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
1685                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
1686             }
1687         }
1688     },
1689
1690     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
1691     {
1692         if(mboxStr.substring(0,7) == 'sugar::') {
1693             // display an email from Sugar
1694             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
1695         } else {
1696             // display an email from an email server
1697             document.getElementById('emailUIAction').value = 'getSingleMessage';
1698         }
1699         document.getElementById('mbox').value = mbox;
1700         document.getElementById('ieId').value = ieId;
1701         document.getElementById('uid').value = uid;
1702
1703         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
1704
1705         AjaxObject.forceAbort = true;
1706         AjaxObject.target = '_blank';
1707         AjaxObject.startRequest(callback, null);
1708     },
1709
1710     /**
1711      * Retrieves multiple emails for DetailView
1712      */
1713     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
1714         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
1715         SE.util.clearHiddenFieldValues('emailUIForm');
1716
1717         var mboxStr = new String(mbox);
1718
1719         uids = SE.util.cleanUids(uids);
1720
1721         if(mboxStr.substring(0,7) == 'sugar::') {
1722             // display an email from Sugar
1723             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
1724             document.getElementById('uid').value = uids;
1725         } else {
1726             // display an email from an email server
1727             document.getElementById('emailUIAction').value = 'getMultipleMessages';
1728             document.getElementById('mbox').value = mbox;
1729             document.getElementById('ieId').value = ieId;
1730             document.getElementById('uid').value = uids;
1731         }
1732
1733         var formObject = document.getElementById('emailUIForm');
1734         YAHOO.util.Connect.setForm(formObject);
1735
1736         AjaxObject.target = 'frameFlex';
1737         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
1738
1739         if(setRead == true) {
1740             var c = uids.split(",");
1741             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
1742         }
1743     },
1744
1745     /**
1746      * Makes async call to get QuickCreate form
1747      * Renders a modal edit view for a given module
1748      */
1749     quickCreate : function(module, ieId, uid, mailbox) {
1750         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
1751
1752         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
1753             get += "&sugarEmail=true";
1754         }
1755
1756         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
1757     },
1758
1759     /**
1760      * Makes async call to save a quick create
1761      * @param bool
1762      */
1763     saveQuickCreate : function(action) {
1764         var qcd = SE.detailView.quickCreateDialog;
1765         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
1766                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
1767                 var theCallback = callbackQuickCreateSave;
1768                 var accountType = '&sugarEmail=true';
1769                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
1770                    accountType = '&ieId=' + qcd.ieId;
1771                 }
1772
1773             if (action == 'reply') {
1774                    theCallback = callbackQuickCreateSaveAndReply;
1775                 } else if (action == true) {
1776                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
1777                 }
1778                 formObject.action.value = 'EmailUIAjax';
1779                 YAHOO.util.Connect.setForm(formObject);
1780                 SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
1781                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
1782                                        accountType + '&mbox=' + qcd.mbox);
1783         }
1784     },
1785
1786     /**
1787      * Code to show/hide long list of email address in DetailView
1788      */
1789     showCroppedEmailList : function(el) {
1790         el.style.display = 'none';
1791         el.previousSibling.style.display = 'inline'
1792     },
1793     showFullEmailList : function(el) {
1794         el.style.display = 'none';
1795         el.nextSibling.style.display = 'inline';
1796     },
1797
1798     /**
1799      * Shows the QuickCreate overlay
1800      * @param string ieId
1801      * @param string uid
1802      * @param string mailbox
1803      */
1804     showQuickCreate : function(ieId, uid, mailbox) {
1805         var panelId = SE.util.getPanelId();
1806         var context = document.getElementById("quickCreateSpan" + panelId);
1807
1808         if (!SE.detailView.cqMenus)
1809                 SE.detailView.cqMenus = {};
1810
1811         if (SE.detailView.cqMenus[context])
1812                 SE.detailView.cqMenus[context].destroy();
1813
1814             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
1815                 lazyload:true,
1816                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
1817         });
1818
1819             for (var i=0; i < this.qcmodules.length; i++) {
1820             var module = this.qcmodules[i];
1821             menu.addItem({
1822                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
1823                 modulename: module,
1824                 value: module,
1825                 onclick: { fn: function() {
1826                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
1827                         }
1828                 }
1829             });
1830         }
1831
1832                 menu.render(document.body);
1833                 menu.show();
1834     },
1835
1836     /**
1837      * Displays the "View" submenu in the detailView
1838      * @param string ieId
1839      * @param string uid
1840      * @param string mailbox
1841      */
1842     showViewMenu : function(ieId, uid, mailbox) {
1843         var panelId = SE.util.getPanelId();
1844         var context = "btnEmailView" + panelId;
1845         if (!SE.detailView.viewMenus)
1846                 SE.detailView.viewMenus = {};
1847
1848         if (SE.detailView.viewMenus[context])
1849                 SE.detailView.viewMenus[context].destroy();
1850
1851             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
1852                 lazyload:true,
1853                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
1854                 clicktohide: true
1855         });
1856                 menu.addItems(
1857                                 (ieId == 'null' || ieId == null) ?
1858                         //No ieId - Sugar Email
1859                         [{
1860                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
1861                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
1862             }]
1863                         :
1864                         //IeID exists, on a remote server
1865                         [{
1866                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
1867                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
1868             },{
1869                 text: app_strings.LBL_EMAIL_VIEW_RAW,
1870                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
1871             }]
1872         );
1873                 menu.render(document.body);
1874                 menu.show();
1875
1876
1877         /*
1878         //#23108 jchi@07/17/2008
1879         menu.render('quickCreateSpan'+ panelId);*/
1880         //this.viewMenu = menu;
1881         //this.viewMenu.show(context);
1882     },
1883     /**
1884      * Makes async call to get an email's headers
1885      */
1886     viewHeaders : function(ieId, uid, mailbox) {
1887         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
1888         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
1889     },
1890
1891     /**
1892      * Makes async call to get a printable version
1893      */
1894     viewPrintable : function(ieId, uid, mailbox) {
1895         if(mailbox == 'sugar::Emails') {
1896             // display an email from Sugar
1897             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
1898         } else {
1899             // display an email from an email server
1900             var emailUIAction = '&emailUIAction=getSingleMessage';
1901         }
1902
1903         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
1904         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
1905     },
1906
1907     /**
1908      * Makes async call to get an email's raw source
1909      */
1910     viewRaw : function(ieId, uid, mailbox) {
1911         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
1912         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
1913     },
1914
1915     /**
1916      * Display all email addresses in detailview.
1917      */
1918     displayAllAddrs : function(el) {
1919         el.style.display = 'none';
1920         Dom.getNextSibling(el).style.display = 'inline';
1921     }
1922 };
1923 ////    END SE.detailView
1924 ///////////////////////////////////////////////////////////////////////////////
1925
1926
1927
1928 ///////////////////////////////////////////////////////////////////////////////
1929 ////    SE.folders
1930 SE.folders = {
1931     contextMenuFocus : new Object(),
1932
1933     /**
1934      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
1935      * SugarFolder ID - folder strings
1936      */
1937     _createFolderId : function(node) {
1938         var ret = '';
1939
1940         if(!node.data.id)
1941             return ret;
1942
1943         if(node.data.ieId) {
1944             /* we have a local Sugar folder */
1945             if(node.data.ieId == 'folder') {
1946                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
1947             } else if(node.data.ieId.match(SE.reGUID)) {
1948                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
1949             }
1950         } else {
1951             ret = node.data.id;
1952         }
1953
1954         return ret;
1955     },
1956
1957     addChildNode : function(parentNode, childNode) {
1958         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
1959         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
1960         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
1961
1962         if(childNode.nodes) {
1963             if(childNode.nodes.length > 0) {
1964                 for(j=0; j<childNode.nodes.length; j++) {
1965                     var newChildNode = childNode.nodes[j];
1966                     this.addChildNode(node, newChildNode);
1967                 }
1968             }
1969         }
1970     },
1971
1972     /**
1973      * Builds and returns a new TreeView Node
1974      * @param string name
1975      * @param string id
1976      * @param int is_group
1977      * @return object
1978      */
1979     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
1980         var node = new YAHOO.widget.TextNode(name, parentNode, true);
1981
1982         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
1983         node.expanded = expanded;
1984         node.data = new Object;
1985         node.data['id'] = id;
1986         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
1987         node.data['label'] = name;
1988         node.data['ieId'] = 'folder';
1989         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
1990         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
1991         node.data['unseen'] = unseen;
1992         return node;
1993     },
1994
1995     /**
1996      * ensures that a new folder has a valid name
1997      */
1998     checkFolderName : function(name) {
1999         if(name == "")
2000             return false;
2001
2002         this.folderAdd(name);
2003     },
2004
2005     /**
2006      * Pings email servers for new email - forces refresh of folder pane
2007      */
2008     checkEmailAccounts : function() {
2009         this.checkEmailAccountsSilent(true);
2010     },
2011
2012     checkEmailAccountsSilent : function(showOverlay) {
2013         if(typeof(SE.folders.checkingMail)) {
2014             clearTimeout(SE.folders.checkingMail);
2015         }
2016
2017         // don't stomp an on-going request
2018         if(AjaxObject.currentRequestObject.conn == null) {
2019             if(showOverlay) {
2020                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW,
2021                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2022             }
2023             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2024         } else {
2025             // wait 5 secs before trying again.
2026             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2027         }
2028     },
2029
2030     /**
2031      * Starts check of all email Accounts using a loading bar for large POP accounts
2032      */
2033     startEmailAccountCheck : function() {
2034         // don't do two checks at the same time
2035        if(!AjaxObject.requestInProgress()) {
2036             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2037             SE.accounts.ieIds = SE.folders.getIeIds();
2038             if (SE.accounts.ieIds.length > 0) {
2039                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2040                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2041             } else {
2042                SUGAR.hideMessageBox();
2043             }
2044         } else {
2045             // wait 5 secs before trying again.
2046             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2047         }
2048     },
2049
2050     /**
2051      * Checks a single Account check based on passed ieId
2052      */
2053      startEmailCheckOneAccount : function(ieId, synch) {
2054             if (synch) {
2055                 synch = true;
2056             } else {
2057                 synch = false;
2058             }
2059             var mbox = "";
2060             var node = SE.clickedFolderNode;
2061             if (node && !synch) {
2062                 mbox = node.data.mbox;
2063             } // if
2064             SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2065             SE.accounts.ieIds = [ieId];
2066             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2067                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2068       },
2069
2070
2071     /**
2072      * Empties trash for subscribed accounts
2073      */
2074     emptyTrash : function() {
2075         SE.contextMenus.frameFoldersContextMenu.hide();
2076         SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2077         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2078     },
2079
2080     /**
2081      * Clears Cache files of the inboundemail account
2082      */
2083     clearCacheFiles : function(ieId) {
2084         SE.contextMenus.frameFoldersContextMenu.hide();
2085         SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2086         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2087     },
2088
2089
2090     /**
2091      * Returns an array of all the active accounts in the folder view
2092      */
2093     getIeIds : function() {
2094          var ieIds = [];
2095          var root = SE.tree.getRoot();
2096          for(i=0; i < root.children.length; i++) {
2097            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2098                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2099                ieIds.push(root.children[i].children[0].data.ieId);
2100            }
2101          }
2102          return ieIds;
2103      },
2104
2105     /**
2106      * loads folder lists in Settings->Folders
2107      */
2108     lazyLoadSettings : function() {
2109         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2110         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2111     },
2112
2113     /**
2114      * After the add new folder is done via folders tab on seetings, this function should get called
2115      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2116      */
2117     loadSettingFolder : function() {
2118         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2119         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2120     },
2121
2122     /**
2123      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2124      */
2125     removeSugarFolders : function() {
2126         var tree = SE.tree;
2127         var root = tree.getRoot();
2128         var folder = SE.util.findChildNode(root, "ieId", "folder");
2129         while(folder) {
2130             tree.removeNode(folder);
2131             folder = SE.util.findChildNode(root, "ieId", "folder");
2132         }
2133         if (!root.childrenRendered) {
2134                 root.childrenRendered = true;
2135         }
2136     },
2137
2138     rebuildFolders : function(silent) {
2139       if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2140        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2141     },
2142
2143
2144
2145     /**
2146      * Updates TreeView with Sugar Folders
2147      */
2148     setSugarFolders : function(delay) {
2149         this.removeSugarFolders();
2150                 //AjaxObject.forceAbort = true;
2151                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2152     },
2153
2154     /**
2155      * Takes async data object and creates the sugar folders in TreeView
2156      */
2157     setSugarFoldersEnd : function(o) {
2158         var root = SE.tree.getRoot();
2159         addChildNodes(root, {nodes: o});
2160         SE.accounts.renderTree();
2161         //If nothing is loaded in the grid, load "My Inbox"
2162         if (SE.grid.params.ieId == "undefined") {
2163                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2164         }
2165     },
2166
2167     startCheckTimer : function() {
2168         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2169             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2170
2171             if(typeof(SE.folders.checkTimer) != 'undefined') {
2172                 clearTimeout(SE.folders.checkTimer);
2173             }
2174
2175             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2176             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2177             {
2178                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2179                 SE.folders.checkEmailAccountsSilent(false);
2180             }
2181         }
2182     },
2183
2184     /**
2185      * makes an async call to save user preference and refresh folder view
2186      * @param object SELECT list object
2187      */
2188     setFolderSelection : function() {
2189         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2190
2191         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2192         var a_active_accnts = "";
2193         for(i=0;i<a_rs.length;i++)
2194         {
2195                 var t_record = a_rs[i];
2196                 var is_active = t_record.getData('is_active');
2197                 if(is_active)
2198                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2199         }
2200
2201         if(a_active_accnts == "")
2202                 a_active_accnts = "&ieIdShow[]=";
2203
2204         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2205
2206         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2207     },
2208
2209     /**
2210      * makes async call to save user preference for a given node's open state
2211      * @param object node YUI TextNode object
2212      */
2213     setOpenState : function(node) {
2214         SE.util.clearHiddenFieldValues('emailUIForm');
2215         var nodePath = node.data.id;
2216         var nodeParent = node.parent;
2217
2218         while(nodeParent != null) {
2219             // root node has no ID param
2220             if(nodeParent.data != null) {
2221                 nodePath = nodeParent.data.id + "::" + nodePath;
2222             }
2223
2224             var nodeParent = nodeParent.parent;
2225         }
2226
2227         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2228         document.getElementById('focusFolder').value = nodePath;
2229
2230         if(node.expanded == true) {
2231             document.getElementById('focusFolderOpen').value = 'open';
2232         } else {
2233             document.getElementById('focusFolderOpen').value = 'closed';
2234         }
2235
2236         var formObject = document.getElementById('emailUIForm');
2237         YAHOO.util.Connect.setForm(formObject);
2238
2239         AjaxObject.startRequest(null, null);
2240     },
2241
2242     getNodeFromMboxPath : function(path) {
2243         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2244         var a = YAHOO.lang.JSON.parse(path);
2245
2246         var node = tree.getRoot();
2247
2248         var i = 0;
2249         while(i < a.length) {
2250             node = this.getChildNodeFromLabel(node, a[i]);
2251             i++;
2252         }
2253
2254         return node;
2255     },
2256
2257     getChildNodeFromLabel : function(node, nodeLabel) {
2258         for(i=0; i<node.children.length; i++) {
2259             if(node.children[i].data.id == nodeLabel) {
2260                 return node.children[i];
2261             }
2262         }
2263     },
2264
2265     /**
2266      * returns the node that presumably under the user's right-click
2267      */
2268     getNodeFromContextMenuFocus : function() {
2269         //// get the target(parent) node
2270         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2271         var index = -1;
2272         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2273
2274         // filter local folders
2275         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2276             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2277                 if(target.id == '') {
2278                     target = target.parentNode;
2279                 } else {
2280                     break;
2281                 }
2282             }
2283         }
2284
2285         var targetNode = document.getElementById(target.id);
2286         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2287
2288         try {
2289             var matches = re.exec(targetNode.id);
2290         } catch(ex) {
2291             return document.getElementById(ygtvlabelel1);
2292         }
2293
2294         if(matches) {
2295             index = matches[1];
2296         } else {
2297             // usually parent node
2298             matches = re.exec(targetNode.parentNode.id);
2299
2300             if(matches) {
2301                 index = matches[1];
2302             }
2303         }
2304
2305         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2306         parentNode.expand();
2307
2308         return parentNode;
2309     },
2310
2311     /**
2312      * Decrements the Unread Email count in folder text
2313      * @param string ieId ID to look for
2314      * @param string mailbox name
2315      * @param count how many to decrement
2316      */
2317     decrementUnreadCount : function(ieId, mbox, count) {
2318
2319         if(mbox == null)
2320             return;
2321
2322         if(mbox.indexOf("sugar::") === 0) {
2323             var node = this.getNodeFromId(ieId);
2324         } else {
2325             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2326         }
2327         if(node) {
2328             var unseen = node.data.unseen;
2329             if(unseen > 0) {
2330                 var check = unseen - count;
2331                 var finalCount = (check >= 0) ? check : 0;
2332                 node.data.unseen = finalCount;
2333             }
2334             SE.accounts.renderTree();
2335         }
2336     },
2337
2338     /**
2339      * gets the TreeView node with a given ID/ieId
2340      * @param string id ID to look for
2341      * @return object Node
2342      */
2343     getNodeFromId : function(id) {
2344         SE.folders.focusNode = null;
2345         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2346             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2347                 SE.folders.focusNode = this;
2348                 return false;
2349             }
2350         }, null, [id]);
2351         return SE.folders.focusNode;
2352     },
2353
2354     /**
2355      * Uses ieId and mailbox to try to find a node in the tree
2356      */
2357     getNodeFromIeIdAndMailbox : function(id, mbox) {
2358                 SE.folders.focusNode = null;
2359         if (mbox == "sugar::Emails") {
2360                 mbox = id;
2361                 id = "folder";
2362         } // if
2363         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2364                 if (varsarray instanceof Array) {
2365             if (this.data.ieId && this.data.ieId == varsarray[0]
2366                     && this.data.mbox == varsarray[1]) {
2367                 SE.folders.focusNode = this;
2368                 return false;
2369             } }
2370                 else {
2371                         if (this.data.ieId && this.data.ieId == varsarray) {
2372                                 SE.folders.focusNode = this;
2373                     return false;
2374                         }
2375                 }
2376         }, null, [id, mbox]);
2377         return SE.folders.focusNode;
2378     },
2379
2380     unhighliteAll : function() {
2381         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2382     },
2383
2384     /**
2385      * Displays a short form
2386      */
2387     folderAdd : function() {
2388         SE.contextMenus.frameFoldersContextMenu.hide();
2389
2390         var node = SE.clickedFolderNode;
2391
2392         if(node != null && node.data) {
2393             SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2394                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2395                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2396         } else {
2397             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2398         }
2399     },
2400
2401     folderAddRegisterEnter : function() {
2402         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2403                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2404                                                                                                                         this.buttons[1].handler);
2405
2406                 this.enterKeyListener.enable();
2407     },
2408
2409     folderRemoveRegisterEnter : function() {
2410         this.enterKeyListener.disable();
2411     },
2412
2413     folderAddXmlCall : function(name) {
2414         if (trim(name) == "") {
2415                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2416                 return false;
2417         }
2418         name = escape(name);
2419         var post = '';
2420         var type = 'sugar';
2421
2422         var parentNode = SE.clickedFolderNode;
2423
2424         this.contextMenuFocus = parentNode;
2425
2426         if(parentNode.data.ieId) {
2427             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2428                 type = 'imap';
2429             }
2430         }
2431         if(type == 'imap') {
2432                 // make an IMAP folder
2433             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2434             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2435         } else if(type == 'sugar') {
2436             // make a Sugar folder
2437             if(SE.folders.isUniqueFolderName(name)) {
2438                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2439                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2440             } else {
2441                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2442                 SE.folders.folderAdd();
2443                 return;
2444             }
2445         } else {
2446             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2447         }
2448
2449         // hide add-folder diaglogue
2450         SE.e2overlay.hide();
2451     },
2452
2453     /**
2454      * Removes either an IMAP folder or a Sugar Folder
2455      */
2456     folderDelete : function() {
2457         SE.contextMenus.frameFoldersContextMenu.hide();
2458
2459         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2460             var post = '';
2461             var parentNode = SE.clickedFolderNode;
2462
2463             if(parentNode != null && parentNode.data) {
2464                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2465                     SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2466                     return;
2467                 }
2468
2469                 AjaxObject.target = 'frameFlex';
2470
2471                 if(parentNode.data.ieId != 'folder') {
2472                     // delete an IMAP folder
2473                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2474                 } else {
2475                     // delete a sugar folder
2476                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2477                 }
2478                 SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2479                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2480             } else {
2481                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2482             }
2483         }
2484     },
2485
2486     /**
2487      * Rename folder form
2488      */
2489      //EXT111
2490     folderRename : function() {
2491         SE.contextMenus.frameFoldersContextMenu.hide();
2492         var node = SE.clickedFolderNode;
2493
2494         if(node != null) {
2495             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2496                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2497                 return;
2498             }
2499
2500                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2501                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2502                     'prompt',
2503                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2504         } else {
2505             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2506         }
2507     },
2508
2509     /**
2510      * fills an Object with key-value pairs of available folders
2511      */
2512     getAvailableFoldersObject : function() {
2513         var ret = new Object();
2514         var tree = SE.tree.root;
2515
2516         if(tree.children) {
2517             for(var i=0; i<tree.children.length; i++) {
2518                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
2519             }
2520         } else {
2521             ret['none'] = app_strings.LBL_NONE;
2522         }
2523
2524         return ret;
2525     },
2526
2527     /**
2528      * Fills in key-value pairs for dependent dropdowns
2529      * @param object ret Associative array
2530      * @param object node TreeView node in focus
2531      * @param string currentPath Built up path thus far
2532      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
2533      */
2534     getFolderFromChild : function(ret, node, currentPath, spacer) {
2535         if(node.data != null && node.depth > 0) {
2536             /* handle visual separtors differentiating b/t mailserver and local */
2537             if(node.data.ieId && node.data.ieId == 'folder') {
2538                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
2539             }
2540
2541             if(!ret.spacer0) {
2542                 ret['spacer0'] = spacer;
2543             } else if(ret.spacer0 != spacer) {
2544                 ret['spacer1'] = spacer
2545             }
2546
2547             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
2548             var depthMarker = currentPath;
2549             var retIndex = SE.folders._createFolderId(node);
2550             ret[retIndex] = depthMarker + theLabel;
2551         }
2552
2553         if(node.children != null) {
2554             if(theLabel) {
2555                 currentPath += theLabel + "/";
2556             }
2557
2558             for(var i=0; i<node.children.length; i++) {
2559                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
2560             }
2561         }
2562
2563         return ret;
2564     },
2565
2566     /**
2567      * Wrapper to refresh folders tree
2568      */
2569     getFolders : function() {
2570         SE.accounts.rebuildFolderList();
2571     },
2572
2573     /**
2574      * handles events around folder-rename input field changes
2575      * @param object YUI event object
2576      */
2577     handleEnter : function(e) {
2578         switch(e.browserEvent.type) {
2579             case 'click':
2580                 e.preventDefault(); // click in text field
2581             break;
2582
2583             case 'blur':
2584                 SE.folders.submitFolderRename(e);
2585             break;
2586
2587             case 'keypress':
2588                 var kc = e.browserEvent.keyCode;
2589                 switch(kc) {
2590                     case 13: // enter
2591                         e.preventDefault();
2592                         SE.folders.submitFolderRename(e);
2593                     break;
2594
2595                     case 27: // esc
2596                         e.preventDefault(e);
2597                         SE.folders.cancelFolderRename(e);
2598                     break;
2599                 }
2600             break;
2601         }
2602     },
2603     /**
2604     * Called when a node is clicked on in the folder tree
2605     * @param node, The node clicked on
2606     * @param e, The click event
2607     */
2608     handleClick : function(o) {
2609         var node = o.node;
2610         //If the click was on a sugar folder
2611         if (node.data.ieId == "folder") {
2612             SE.listView.populateListFrameSugarFolder(node, node.id, false);
2613         }
2614         else {
2615             SE.listView.populateListFrame(node, node.data.ieId, false);
2616         }
2617        //eval(node.data.click);
2618        //debugger;
2619     },
2620
2621     /**
2622     * Called when a node is right-clicked on in the folder tree
2623     */
2624     handleRightClick : function(e) {
2625         YAHOO.util.Event.preventDefault(e);
2626                 //Get the Tree Node
2627                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
2628                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
2629
2630                 //If the click was on a sugar folder
2631         SE.clickedFolderNode = node;
2632         var inbound = (node.data.ieId && node.data.ieId != 'folder');
2633                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
2634                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
2635                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
2636                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
2637                 menu.getItem(3).cfg.setProperty("disabled", false);
2638                 menu.getItem(4).cfg.setProperty("disabled", false);
2639                 menu.getItem(5).cfg.setProperty("disabled", false);
2640                 menu.getItem(6).cfg.setProperty("disabled", true);
2641                 //Group folder
2642                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
2643                         menu.getItem(0).cfg.setProperty("disabled", true);
2644                         menu.getItem(1).cfg.setProperty("disabled", true);
2645                         menu.getItem(2).cfg.setProperty("disabled", true);
2646                         menu.getItem(3).cfg.setProperty("disabled", true);
2647                         menu.getItem(4).cfg.setProperty("disabled", true);
2648                 }
2649         if (node.data.protocol != null) {
2650                 menu.getItem(6).cfg.setProperty("disabled", false);
2651         }
2652                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
2653                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
2654                         //Sent or Draft folders
2655                         menu.getItem(3).cfg.setProperty("disabled", true);
2656                         menu.getItem(4).cfg.setProperty("disabled", true);
2657                         menu.getItem(5).cfg.setProperty("disabled", true);
2658                 }
2659
2660                 //For group with auto inbound, disable everything.
2661                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
2662                 {
2663                     menu.getItem(0).cfg.setProperty("disabled", true);
2664                 menu.getItem(1).cfg.setProperty("disabled", true);
2665                 menu.getItem(2).cfg.setProperty("disabled", true);
2666                 menu.getItem(3).cfg.setProperty("disabled", true);
2667                 menu.getItem(4).cfg.setProperty("disabled", true);
2668                 menu.getItem(5).cfg.setProperty("disabled", true);
2669                 menu.getItem(6).cfg.setProperty("disabled", true);
2670                 }
2671
2672                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
2673                 menu.show();
2674     },
2675
2676     /**
2677     * Called when a row is dropped on a node
2678     */
2679     handleDrop : function(rows, targetFolder) {
2680         var rowData = rows[0].getData();
2681         if (rowData.mbox != targetFolder.data.mbox) {
2682             var srcIeId = rowData.ieId;
2683             var srcFolder = rowData.mbox;
2684             var destIeId = targetFolder.data.ieId;
2685             var destFolder = targetFolder.data.mbox;
2686             var uids = [];
2687             for(var i=0; i<rows.length; i++) {
2688                 uids[i] = rows[i].getData().uid;
2689             }
2690             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
2691         }
2692     },
2693
2694     /**
2695     * Called when something is dragged over a Folder Node
2696     */
2697     dragOver : function(dragObject) {
2698        return true;
2699     },
2700
2701     /**
2702      * Determines if a folder name is unique to the folder tree
2703      * @param string name
2704      */
2705     isUniqueFolderName : function(name) {
2706         uniqueFolder = true;
2707         var root = SE.tree.getRoot();
2708         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
2709             if (this.attributes && this.attributes.ieId == "folder") {
2710                 if (this.attributes.text == name) {
2711                     uniqueFolder = false;
2712                     return false;
2713                 }
2714             }
2715         }, null, [name]);
2716         return uniqueFolder;
2717     },
2718
2719     /**
2720      * Makes async call to rename folder in focus
2721      * @param object e Event Object
2722      */
2723     submitFolderRename : function(newName) {
2724         if (trim(newName) == "") {
2725                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2726                 return false;
2727         }
2728                 newName = escape(newName);
2729         var node = SE.clickedFolderNode;
2730         var origName = node.data.text
2731         //Ignore no change
2732         if (newName == origName) {
2733             return true;
2734         }
2735         if(SE.folders.isUniqueFolderName(newName)) {
2736             SUGAR.showMessageBox(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
2737             if (node.data.ieId == "folder") {
2738                 //Sugar Folder
2739                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
2740             }
2741             else {
2742                 //IMAP folder or POP mailbox
2743                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
2744                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
2745                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
2746             }
2747             return true;
2748         } else {
2749             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2750             return false;
2751         }
2752     },
2753
2754     moveFolder : function(folderId, parentFolderId) {
2755         if (folderId != parentFolderId)
2756         {
2757                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
2758                     + folderId + "&newParentId=" + parentFolderId);
2759         }
2760     },
2761
2762     /**
2763      * makes async call to do a full synchronization of all accounts
2764      */
2765     synchronizeAccounts : function() {
2766         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
2767             SUGAR.showMessageBoxModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
2768             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
2769         }
2770     },
2771
2772     /**
2773      * Updates user's folder subscriptsion (Sugar only)
2774      * @param object SELECT DOM object in focus
2775      * @param string type of Folder selection
2776      */
2777     updateSubscriptions : function() {
2778         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2779
2780         var active = "";
2781
2782         select = document.getElementById('userFolders');
2783
2784         for(i=0; i<select.options.length; i++) {
2785             var opt = select.options[i];
2786              if(opt.selected && opt.value != "") {
2787                  if(active != "") {
2788                      active += "::";
2789                  }
2790                  active += opt.value;
2791              }
2792         }
2793
2794         //Add the group folder ids.
2795         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
2796         for(i=0; i<group_folders.length; i++)
2797         {
2798             active += ("::" + group_folders[i]);
2799         }
2800
2801         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
2802     },
2803     /**
2804      * Updates user's group folder subscriptsion (Sugar only)
2805      * @param ieID The group folder to add to the tree view
2806      */
2807     retrieveGroupFolderSubscriptions : function() {
2808
2809         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2810         var activeGroupFolders = "";
2811         var activeGroupIds = [];
2812         for(i=0;i<a_rs.length;i++)
2813         {
2814                 var t_record = a_rs[i];
2815                 var is_active = t_record.getData('is_active');
2816                 var isGroupFolder = t_record.getData('has_groupfolder');
2817                 var ieID = t_record.getData('id');
2818                 if( isGroupFolder )
2819                 {
2820                     if(is_active)
2821                       activeGroupIds.push(ieID);
2822                 }
2823         }
2824
2825         return activeGroupIds;
2826     }
2827
2828 };
2829
2830 SE.folders.checkEmail2 = function() {
2831     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
2832 }
2833 ////    END FOLDERS OBJECT
2834 ///////////////////////////////////////////////////////////////////////////////
2835
2836
2837 ///////////////////////////////////////////////////////////////////////////////
2838 ////    SE.keys
2839 /**
2840  * Keypress Event capture and processing
2841  */
2842 SE.keys = {
2843     overall : function(e) {
2844         switch(e.charCode) {
2845             case 119: // "w"
2846                 if(e.ctrlKey || e.altKey) {
2847                     var focusRegion = SE.innerLayout.regions.center;
2848                     if(focusRegion.activePanel.closable == true) {
2849                         focusRegion.remove(focusRegion.activePanel);
2850                     }
2851                 }
2852             break;
2853         }
2854     }
2855 };
2856 ////    END SE.keys
2857 ///////////////////////////////////////////////////////////////////////////////
2858
2859
2860 ///////////////////////////////////////////////////////////////////////////////
2861 ////    SE.listView
2862 /**
2863  * ListView object methods and attributes
2864  */
2865 SE.listView = {
2866     currentRowId : -1,
2867
2868     /**
2869      * Fills the ListView pane with detected messages.
2870      */
2871     populateListFrame : function(node, ieId, forceRefresh) {
2872         SE.innerLayout.selectTab(0);
2873                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
2874
2875         Dom.get('_blank').innerHTML = "";
2876         SE.grid.params['emailUIAction'] = 'getMessageList';
2877         SE.grid.params['mbox'] = node.data.mbox;
2878         SE.grid.params['ieId'] = ieId;
2879         forcePreview = true; // loads the preview pane with first item in grid
2880         SE.listView.refreshGrid();
2881     },
2882
2883     /**
2884      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
2885      */
2886     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
2887         SE.innerLayout.selectTab(0);
2888         Dom.get('_blank').innerHTML = "";
2889         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
2890         SE.grid.params['ieId'] = node.data.id;
2891         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
2892         SE.listView.refreshGrid();
2893     },
2894
2895     /**Mac
2896      * Sets sort order as user preference
2897      * @param
2898      */
2899     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
2900         ieId = ieIdPassed;
2901         ieName = ieNamePassed;
2902         focusFolder = focusFolderPassed;
2903
2904         SE.util.clearHiddenFieldValues('emailUIForm');
2905         var previousSort = document.getElementById('sortBy').value;
2906
2907         document.getElementById('sortBy').value = sortBy;
2908         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
2909         document.getElementById('focusFolder').value = focusFolder;
2910         document.getElementById('ieId').value = ieId;
2911
2912         if(sortBy == previousSort) {
2913             document.getElementById('reverse').value = '1';
2914         }
2915
2916         var formObject = document.getElementById('emailUIForm');
2917         YAHOO.util.Connect.setForm(formObject);
2918
2919         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
2920     },
2921
2922
2923     /**
2924      * Enables click/arrow select of grid items which then populate the preview pane.
2925      */
2926     selectFirstRow : function() {
2927         SE.grid.selModel.selectFirstRow();
2928     },
2929
2930     selectLastRow : function() {
2931         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
2932     },
2933
2934     setEmailListStyles : function() {
2935         SE.listView.boldUnreadRows();
2936         return;
2937         var ds = SE.grid.getStore();
2938         if (SE.grid.getSelections().length == 0) {
2939             document.getElementById('_blank').innerHTML = '';
2940         }
2941
2942         var acctMbox = '';
2943         if(typeof(ds.baseParams.mbox) != 'undefined') {
2944             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
2945             var cm = SE.grid.getColumnModel();
2946             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
2947                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
2948                 //SE.grid.render();
2949             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
2950                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
2951                 //SE.grid.render();
2952             }
2953         }
2954         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
2955         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
2956
2957         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
2958             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
2959             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
2960             if (node) node.data.unseen = unread;
2961         }
2962         SE.accounts.renderTree();
2963
2964
2965         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
2966         if(forcePreview && ds.totalCount > 0) {
2967             SE.detailView.getEmailPreview();
2968             forcePreview = false;
2969         }
2970     },
2971
2972     /**
2973      * Removes a row if found via its UID
2974      */
2975     removeRowByUid : function(uid) {
2976         uid = new String(uid);
2977         uids = uid.split(',');
2978         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
2979
2980         for(j=0; j<uids.length; j++) {
2981             var theUid = uids[j];
2982             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
2983                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
2984                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
2985                 }
2986             } // for
2987         }
2988     },
2989
2990     displaySelectedEmails : function(rows) {
2991         var dm = SE.grid.getDataModel();
2992         var uids = '';
2993
2994         for(i=0; i<rows.length; i++) {
2995             var rowIndex = rows[i].rowIndex;
2996             var metadata = dm.data[rowIndex];
2997
2998             if(uids != "") {
2999                 uids += ",";
3000             }
3001             uids += metadata[5];
3002
3003             // unbold unseen email
3004             this.unboldRow(rowIndex);
3005         }
3006
3007         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3008     },
3009
3010     /**
3011      * exception handler for data load failures
3012      */
3013     loadException : function(dataModel, ex, response) {
3014         //debugger;
3015     },
3016
3017     /**
3018      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3019      * @param string sourceIeId Email's source I-E id
3020      * @param string sourceFolder Email's current folder
3021      * @param destinationIeId Destination I-E id
3022      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3023      *
3024      * @param array emailUids Array of email's UIDs
3025      */
3026     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3027         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3028             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3029         } else {
3030             SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3031             // remove rows from visibility
3032             for(row in selectedRows) {
3033                 //SE.grid.getStore().remove(row);
3034             }
3035
3036             var baseUrl =    '&sourceIeId=' + sourceIeId +
3037                             '&sourceFolder=' + sourceFolder +
3038                             '&destinationIeId=' + destinationIeId +
3039                             '&destinationFolder=' + destinationFolder;
3040             var uids = '';
3041
3042             for(i=0; i<emailUids.length; i++) {
3043                 if(uids != '') {
3044                     uids += app_strings.LBL_EMAIL_DELIMITER;
3045                 }
3046                 uids += emailUids[i];
3047             }
3048             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3049                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3050             } else {
3051                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3052             }
3053         }
3054     },
3055
3056     /**
3057      * Unbolds text in the grid view to denote read status
3058      */
3059     markRead : function(index, record) {
3060         // unbold unseen email
3061         var row = SE.grid.getRecord(record);
3062         row.getData().seen = 1;
3063         SE.grid.getTrEl(record).style.fontWeight = "normal";
3064     },
3065
3066     /**
3067      * grid row output, bolding unread emails
3068      */
3069     boldUnreadRows : function() {
3070         // bold unread emails
3071         var trEl = SE.grid.getFirstTrEl();
3072         while(trEl != null) {
3073                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3074                         trEl.style.fontWeight = "bold";
3075                 else
3076                         trEl.style.fontWeight = "";
3077                 trEl = SE.grid.getNextTrEl(trEl);
3078         }
3079     },
3080
3081     /**
3082      * Show preview for an email if 1 and only 1 is selected
3083      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3084      */
3085     handleRowSelect : function(e) {
3086         if(e.selectedRows.length == 1) {
3087             SE.detailView.getEmailPreview();
3088         }
3089     },
3090
3091     handleDrop : function(e, dd, targetId, e2) {
3092         switch(targetId) {
3093             case 'htmleditordiv':
3094                 var rows = SE.grid.getSelectedRows();
3095                 if(rows.length > 0) {
3096                     SE.listView.displaySelectedEmails(rows);
3097                 }
3098             break;
3099
3100             default:
3101                 var targetElId = new String(targetId);
3102                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3103                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3104                 var dm = SE.grid.getDataModel();
3105                 var emailUids = new Array();
3106                 var destinationIeId = targetNode.data.ieId;
3107                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3108
3109
3110                 var rows = SE.grid.getSelectedRows();
3111                 // iterate through dragged rows
3112                 for(i=0; i<rows.length; i++) {
3113                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3114                     var rowIndex = rows[i].rowIndex;
3115                     var dataModelRow = dm.data[rowIndex];
3116                     var sourceIeId = dataModelRow[7];
3117                     var sourceFolder = dataModelRow[6];
3118                     emailUids[i] = dataModelRow[5];
3119                 }
3120
3121                 // event wrapped call - need FQ
3122                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3123                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3124             break;
3125         }
3126     },
3127
3128     /**
3129      * Hack-around to get double-click and single clicks to work on the grid
3130      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3131      */
3132     handleClick : function(o) {
3133         SUGAR.email2.grid.clearTextSelection();
3134
3135         var el = SUGAR.email2.grid.getSelectedRows();
3136
3137         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3138         if ( el.length == 1)
3139         {
3140            var rowId = el[0];
3141            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3142            SUGAR.email2.listView.currentRowIndex = rowId;
3143            clearTimeout(SUGAR.email2.detailView.previewTimer);
3144            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3145         }
3146     },
3147
3148     /**
3149      * Custom handler for double-click/enter
3150      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3151      */
3152     getEmail : function(e) {
3153         var rows = SE.grid.getSelectedRows();
3154         var row = SE.grid.getRecord(rows[0]).getData();
3155
3156         clearTimeout(SE.detailView.previewTimer);
3157         document.getElementById("_blank").innerHTML = "";
3158
3159         if(row.type != "draft") {
3160             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3161         } else {
3162             // circumventing yui-ext tab generation, let callback handler build new view
3163             SE.util.clearHiddenFieldValues('emailUIForm');
3164             //function(uid, mbox, ieId, setRead, destination) {
3165             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3166             document.getElementById('uid').value = row.uid; // uid;
3167             document.getElementById('mbox').value = row.mbox; // mbox;
3168             document.getElementById('ieId').value = row.ieId; // ieId;
3169
3170             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3171             AjaxObject.target = '_blank';
3172             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3173         }
3174     },
3175
3176     /**
3177      * Retrieves a row if found via its UID
3178      * @param string
3179      * @return int
3180      */
3181     getRowIndexByUid : function(uid) {
3182         uid = new String(uid);
3183         uids = uid.split(',');
3184
3185         for(j=0; j<uids.length; j++) {
3186             var theUid = uids[j];
3187
3188             for(i=0; i<SE.grid.getStore().data.length; i++) {
3189                 if(SE.grid.getStore().data[i].id == theUid) {
3190                     return i;
3191                 }
3192             }
3193         }
3194     },
3195
3196     /**
3197      * Returns the UID's of the seleted rows
3198      *
3199      */
3200      getUidsFromSelection : function() {
3201          var rows = SE.grid.getSelectedRows();
3202          var uids = [];
3203          /* iterate through available rows JIC a row is deleted - use first available */
3204          for(var i=0; i<rows.length; i++) {
3205                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3206          }
3207          return uids;
3208      },
3209
3210     refreshGrid : function() {
3211         SE.grid.getDataSource().sendRequest(
3212             encodeParamsToUrl(SE.grid.params),
3213                 SE.grid.onDataReturnInitializeTable,
3214                 SE.grid
3215         );
3216     }
3217
3218 };
3219 ////    END SE.listView
3220 ///////////////////////////////////////////////////////////////////////////////
3221
3222 ///////////////////////////////////////////////////////////////////////////////
3223 ////    SEARCH
3224 SE.search = {
3225     /**
3226      * sends search criteria
3227      * @param reference element search field
3228      */
3229     search : function(el) {
3230         var searchCriteria = new String(el.value);
3231
3232         if(searchCriteria == '') {
3233             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3234             return false;
3235         }
3236
3237         var safeCriteria = escape(searchCriteria);
3238
3239         var accountListSearch = document.getElementById('accountListSearch');
3240
3241         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3242         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3243         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3244         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3245         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3246
3247     },
3248
3249     /**
3250      * sends advanced search criteria
3251      */
3252     searchAdvanced : function() {
3253         var formObject = document.getElementById('advancedSearchForm');
3254         var search = false;
3255
3256         //Set assigned user id to blank if name is not present.
3257         if (formObject.elements['assigned_user_name'].value == "")
3258             formObject.elements['assigned_user_id'].value = "";
3259
3260         for(i=0; i<formObject.elements.length; i++) {
3261             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3262                 search = true;
3263             }
3264             if(formObject.elements[i].type == 'text') {
3265                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3266             }
3267             if(formObject.elements[i].type == 'hidden') {
3268                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3269             }
3270              if(formObject.elements[i].type == 'select-one') {
3271                 var el = formObject.elements[i];
3272                 var v = el.options[el.selectedIndex].value;
3273
3274                 if(v != "")
3275                     SE.grid.params[el.name] = v;
3276                 else
3277                 {
3278                     //Clear previous search results if necessary
3279                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3280                         delete SE.grid.params[el.name]
3281                 }
3282              }
3283         }
3284
3285         if (search)
3286         {
3287             if(! this.validateSearchFormInput() )
3288                 return;
3289
3290                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3291                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3292                 var accountListSearch = document.getElementById('accountListSearch');
3293                 SE.listView.refreshGrid();
3294         } else {
3295             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3296         }
3297     },
3298
3299     /**
3300     *  Validates the search form inputs to ensure all parameters are valid
3301     *  @return bool
3302     */
3303     validateSearchFormInput: function()
3304     {
3305         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3306         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3307         var dateCheck = check_form('advancedSearchForm');
3308
3309         //If the parent type is selected ensure the user selected a parent_id.
3310         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3311             return true;
3312         else
3313             return false;
3314     },
3315     /**
3316     *   Toggles the advanced options, either hidding or showing the selection.
3317     */
3318     toggleAdvancedOptions: function()
3319     {
3320         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3321
3322         for(var i=0;i<el.length;i++)
3323         {
3324             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3325                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3326             else
3327                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3328         }
3329     },
3330     /**
3331      * clears adv search form fields
3332      */
3333     searchClearAdvanced : function() {
3334         var form = document.getElementById('advancedSearchForm');
3335
3336         for(i=0; i<form.elements.length; i++) {
3337             if(form.elements[i].type != 'button') {
3338                 form.elements[i].value = '';
3339             }
3340         }
3341     }
3342 };
3343 ////    END SE.search
3344 //////////////////////////////////////////////////////////////////////////////
3345
3346
3347 //////////////////////////////////////////////////////////////////////////////
3348 ////    SE.settings
3349 SE.settings = {
3350     /******************************************************************************
3351      * USER SIGNATURES calls stolen from Users module
3352      *****************************************************************************/
3353     createSignature : function(record, the_user_id) {
3354         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3355         if(record != "") {
3356             URL += "&record="+record;
3357         }
3358         if(the_user_id != "") {
3359             URL += "&the_user_id="+the_user_id;
3360         }
3361         var windowName = 'email_signature';
3362         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3363
3364         var win = window.open(URL, windowName, windowFeatures);
3365         if(win && win.focus) {
3366             // put the focus on the popup if the browser supports the focus() method
3367             win.focus();
3368         }
3369     },
3370
3371     deleteSignature : function() {
3372         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3373             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3374                 var singature_id = document.getElementById('signature_id').value;
3375                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3376         } // if
3377     },
3378
3379     saveOptionsGeneral :  function(displayMessage) {
3380         var formObject = document.getElementById('formEmailSettingsGeneral');
3381         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3382                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3383                 return false;
3384         } // if
3385         YAHOO.util.Connect.setForm(formObject);
3386         SE.composeLayout.emailTemplates = null;
3387
3388         AjaxObject.target = 'frameFlex';
3389         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3390
3391         if(displayMessage)
3392             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3393
3394         SE.settings.settingsDialog.hide();
3395     },
3396
3397     /**
3398      * Shows settings container screen
3399      */
3400     showSettings : function() {
3401         if(!SE.settings.settingsDialog) {
3402                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3403                 modal:true,
3404                 visible:false,
3405                 fixedcenter:true,
3406                 draggable: false,
3407                 width:"800px",
3408                                 constraintoviewport: true
3409             });
3410                         dlg.showEvent.subscribe( function (){
3411                                 var el = this.element;
3412                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3413                 if (this.header && el && viewH - 50 < el.clientHeight) {
3414                     var body = this.header.nextElementSibling;
3415                                         body.style.overflow = "auto";
3416                     body.style.height = (viewH - 50) + "px";
3417                 }
3418             }, dlg);
3419                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3420                 dlg.setBody('<div id="settingsTabDiv"/>');
3421                 dlg.beforeRenderEvent.subscribe(function() {
3422                         var dd = new YAHOO.util.DDProxy(dlg.element);
3423                         dd.setHandleElId(dlg.header);
3424                         dd.on('endDragEvent', function() {
3425                                 dlg.show();
3426                         });
3427                 }, dlg, true);
3428                 dlg.render();
3429
3430                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3431                         var tabContent = Dom.get("tab_general");
3432                 tp.addTab(new YAHOO.widget.Tab({
3433                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3434                                 scroll : true,
3435                                 content :  tabContent.innerHTML,
3436                                 id : "generalSettings",
3437                                 active : true
3438                         }));
3439                 tabContent.parentNode.removeChild(tabContent);
3440                 tabContent = Dom.get("tab_accounts");
3441                 var accountTab = new YAHOO.widget.Tab({
3442                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3443                                 scroll : true,
3444                                 content : tabContent.innerHTML,
3445                                 id : "accountSettings"
3446                         });
3447                 tp.addTab(accountTab);
3448                 tabContent.parentNode.removeChild(tabContent);
3449
3450                         tp.appendTo(dlg.body);
3451         }
3452
3453         SE.settings.settingsDialog.show();
3454         SE.folders.lazyLoadSettings();
3455         SE.accounts.lazyLoad();
3456     },
3457
3458
3459     lazyLoadRules : function() {
3460         if(false) {
3461             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3462         }
3463
3464     }
3465 };
3466 ////    END SE.settings
3467 ///////////////////////////////////////////////////////////////////////////////
3468 })();
3469
3470 /******************************************************************************
3471  * UTILITIES
3472  *****************************************************************************/
3473 function removeHiddenNodes(nodes, grid) {
3474     var el;
3475         for(var i = nodes.length - 1; i > -1; i--) {
3476         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3477         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3478                 nodes.splice(i,1);
3479        }
3480     }
3481 }
3482
3483 function strpad(val) {
3484     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3485 };
3486
3487 function refreshTodos() {
3488     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3489     AjaxObject.target = 'todo';
3490     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3491 };
3492
3493 /******************************************************************************
3494  * MUST STAY IN GLOBAL NAMESPACE
3495  *****************************************************************************/
3496 function refresh_signature_list(signature_id, signature_name) {
3497     var field=document.getElementById('signature_id');
3498     var bfound=0;
3499     for (var i=0; i < field.options.length; i++) {
3500             if (field.options[i].value == signature_id) {
3501                 if (field.options[i].selected==false) {
3502                     field.options[i].selected=true;
3503                 }
3504                 bfound=1;
3505             }
3506     }
3507     //add item to selection list.
3508     if (bfound == 0) {
3509         var newElement=document.createElement('option');
3510         newElement.text=signature_name;
3511         newElement.value=signature_id;
3512         field.options.add(newElement);
3513         newElement.selected=true;
3514     }
3515
3516     //enable the edit button.
3517     var field1=document.getElementById('edit_sig');
3518     field1.style.visibility="inherit";
3519     var deleteButt = document.getElementById('delete_sig');
3520     deleteButt.style.visibility="inherit";
3521 };
3522
3523 function setDefaultSigId(id) {
3524     var checkbox = document.getElementById("signature_default");
3525     var default_sig = document.getElementById("signatureDefault");
3526
3527     if(checkbox.checked) {
3528         default_sig.value = id;
3529     } else {
3530         default_sig.value = "";
3531     }
3532 };
3533
3534 function setSigEditButtonVisibility() {
3535     var field = document.getElementById('signature_id');
3536     var editButt = document.getElementById('edit_sig');
3537     var deleteButt = document.getElementById('delete_sig');
3538     if(field.value != '') {
3539         editButt.style.visibility = "inherit";
3540         deleteButt.style.visibility = "inherit";
3541     } else {
3542         editButt.style.visibility = "hidden";
3543         deleteButt.style.visibility = "hidden";
3544     }
3545 }
3546
3547 //this function is used by emailUI.js and grid.js to create an encoded url from param values
3548 //basically same as SUGAR.util.paramsToUrl plus the encoding
3549 function encodeParamsToUrl(params) {
3550     var parts = [];
3551     for (var i in params)
3552     {
3553         if (params.hasOwnProperty(i))
3554         {
3555             parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(params[i]));
3556         }
3557     }
3558     return parts.join("&");
3559 }