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