]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.3.0
[Github/sugarcrm.git] / include / javascript / sugar_grp_emails.js
1
2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
3
4 /**
5  * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6  * dragged element is inserted before the dragged-over element.
7  *
8  * @extends YAHOO.util.DDProxy
9  * @constructor
10  * @param {String} id the id of the linked element
11  * @param {String} sGroup the group of related DragDrop objects
12  */
13 function ygDDList(id, sGroup) {
14
15         if (id) {
16                 this.init(id, sGroup);
17                 this.initFrame();
18                 //this.logger = new ygLogger("ygDDList");
19         }
20
21         var s = this.getDragEl().style;
22         s.borderColor = "transparent";
23         s.backgroundColor = "#f6f5e5";
24         s.opacity = 0.76;
25         s.filter = "alpha(opacity=76)";
26 }
27
28 ygDDList.prototype = new YAHOO.util.DDProxy();
29
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
32
33 ygDDList.prototype.startDrag = function(x, y) {
34         //this.logger.debug(this.id + " startDrag");
35
36         var dragEl = this.getDragEl();
37         var clickEl = this.getEl();
38
39         dragEl.innerHTML = clickEl.innerHTML;
40         dragElObjects = dragEl.getElementsByTagName('object');
41
42         
43         dragEl.className = clickEl.className;
44         dragEl.style.color = clickEl.style.color;
45         dragEl.style.border = "1px solid #aaa";
46
47         // save the style of the object 
48         clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
49         
50         this.borderDiv = document.createElement('div'); // create a div to display border
51         this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52         this.borderDiv.style.border = '2px dashed #cccccc';
53         
54         for(i in clickEl.childNodes) { // hide contents of the target elements contents
55                 if(typeof clickEl.childNodes[i].style != 'undefined') {
56                         this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57                         clickEl.childNodes[i].style.display = 'none';
58                 }
59
60         }
61         clickEl.appendChild(this.borderDiv);
62 };
63
64 ygDDList.prototype.endDrag = function(e) {
65         // disable moving the linked element
66         var clickEl = this.getEl();
67
68         clickEl.removeChild(this.borderDiv); // remove border div
69         
70         for(i in clickEl.childNodes) { // show target elements contents
71                 if(typeof clickEl.childNodes[i].style != 'undefined') {
72                         clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
73                 }
74         }
75         
76         if(this.clickHeight) 
77             clickEl.style.height = this.clickHeight;
78         else 
79                 clickEl.style.height = '';
80         
81         if(this.clickBorder) 
82             clickEl.style.border = this.clickBorder;
83         else 
84                 clickEl.style.border = '';
85                 
86         dragEl = this.getDragEl();
87         dragEl.innerHTML = '';
88
89         this.afterEndDrag(e);
90 };
91
92 ygDDList.prototype.afterEndDrag = function(e) {
93
94 }
95
96 ygDDList.prototype.onDrag = function(e, id) {
97     
98 };
99
100 ygDDList.prototype.onDragOver = function(e, id) {
101         // this.logger.debug(this.id.toString() + " onDragOver " + id);
102         var el;
103         
104     if ("string" == typeof id) {
105         el = YAHOO.util.DDM.getElement(id);
106     } else { 
107         el = YAHOO.util.DDM.getBestMatch(id).getEl();
108     }
109     
110         dragEl = this.getDragEl();
111         elRegion = YAHOO.util.Dom.getRegion(el);
112             
113 //    this.logger.debug('id: ' + el.id);
114 //    this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 //    this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116         var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 //    this.logger.debug('mid: ' + mid);
118         
119 //    this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " <  " + mid);
120 //    this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
121         
122         if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123                 var el2 = this.getEl();
124                 var p = el.parentNode;
125                 p.insertBefore(el2, el);
126         }
127         if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128                 var el2 = this.getEl();
129                 var p = el.parentNode;
130                 p.insertBefore(el2, el.nextSibling);
131         }
132 };
133
134 ygDDList.prototype.onDragEnter = function(e, id) {
135         // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136         // this.getDragEl().style.border = "1px solid #449629";
137 };
138
139 ygDDList.prototype.onDragOut = function(e, id) {
140     // I need to know when we are over nothing
141         // this.getDragEl().style.border = "1px solid #964428";
142 }
143
144 /////////////////////////////////////////////////////////////////////////////
145
146 function ygDDListBoundary(id, sGroup) {
147         if (id) {
148                 this.init(id, sGroup);
149                 //this.logger = new ygLogger("ygDDListBoundary");
150                 this.isBoundary = true;
151         }
152 }
153
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
156                                 
157 /*********************************************************************************
158  * SugarCRM Community Edition is a customer relationship management program developed by
159  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
160  *
161  * This program is free software; you can redistribute it and/or modify it under
162  * the terms of the GNU Affero General Public License version 3 as published by the
163  * Free Software Foundation with the addition of the following permission added
164  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
167  *
168  * This program is distributed in the hope that it will be useful, but WITHOUT
169  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
171  * details.
172  *
173  * You should have received a copy of the GNU Affero General Public License along with
174  * this program; if not, see http://www.gnu.org/licenses or write to the Free
175  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
176  * 02110-1301 USA.
177  *
178  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
180  *
181  * The interactive user interfaces in modified source and object code versions
182  * of this program must display Appropriate Legal Notices, as required under
183  * Section 5 of the GNU Affero General Public License version 3.
184  *
185  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186  * these Appropriate Legal Notices must retain the display of the "Powered by
187  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188  * technical reasons, the Appropriate Legal Notices must display the words
189  * "Powered by SugarCRM".
190  ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span>&nbsp;</span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace('&#039;',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){if(/save|full|cancel|change/.test(elm.value.toLowerCase())){savePressed=true;}}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(this.verifyElementValue==null||typeof(this.verifyElementValue)=='undefined'){return false;}
199 this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
200 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
201 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed)
202 this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
203 return;this.addInProgress=true;if(!address)
204 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag=document.createElement("input");var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
205 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
206 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
207 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
208 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
209 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
210 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
211 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
212 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
213 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
214 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
215 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
216 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};if(YAHOO.env.ua.ie>0){var emailcontainer=Dom.getAncestorByTagName(insertInto,'span');YAHOO.util.Event.addListener(newContent,"change",function(ev,el){SUGAR.util.callOnChangeListers(el);},emailcontainer);}
217 this.EmailAddressValidation(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},EmailAddressValidation:function(ev,fn,r,stR){YAHOO.util.Event.onContentReady(fn,function(){addToValidate(ev,fn,'email',r,stR);});},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
218 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
219 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
220 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
221 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
222 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
223 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
224 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
225 if(YAHOO.env.ua.ie){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
226 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
227 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView.indexOf('DCQuickCreate')>0){DCMenu.save(theForm.id);}else if(this.emailView.indexOf('QuickCreate')>=0){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value+'_subpanel_save_button');}}}};emailAddressWidgetLoaded=true;})();
228 // End of File include/SugarEmailAddress/SugarEmailAddress.js
229                                 
230 /*********************************************************************************
231  * SugarCRM Community Edition is a customer relationship management program developed by
232  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
233  *
234  * This program is free software; you can redistribute it and/or modify it under
235  * the terms of the GNU Affero General Public License version 3 as published by the
236  * Free Software Foundation with the addition of the following permission added
237  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
238  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
239  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
240  *
241  * This program is distributed in the hope that it will be useful, but WITHOUT
242  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
243  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
244  * details.
245  *
246  * You should have received a copy of the GNU Affero General Public License along with
247  * this program; if not, see http://www.gnu.org/licenses or write to the Free
248  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
249  * 02110-1301 USA.
250  *
251  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
252  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
253  *
254  * The interactive user interfaces in modified source and object code versions
255  * of this program must display Appropriate Legal Notices, as required under
256  * Section 5 of the GNU Affero General Public License version 3.
257  *
258  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
259  * these Appropriate Legal Notices must retain the display of the "Powered by
260  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
261  * technical reasons, the Appropriate Legal Notices must display the words
262  * "Powered by SugarCRM".
263  ********************************************************************************/
264 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
265 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
266 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
267 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
268 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
269 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
270 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
271 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){var clone_id=this.form+'_'+this.field+'_collection_0';YAHOO.util.Event.onContentReady(clone_id,function(c){c.create_clone();enableQS();c.changePrimary(true);for(key in c.secondaries_values){if(isInteger(key)){c.add(c.secondaries_values[key]);}}
272 c.js_more();initEditView(document.forms[c.form]);},this);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
273 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
274 var count=this.fields_count;var Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
275 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
276 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&&currentNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
277 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(typeof(input_els[x].id)=='undefined'||input_els[x].id==''){input_els[x].id=currentNode.id;}
278 if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);var new_id=currentNode.id.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
279 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
280 currentNode.name=new_name;currentNode.id=new_id;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_id.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_id;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_id;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_id;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
281 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
282 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
283 arrow.value='show';}
284 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects!='undefined'&&typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
285 break;}}
286 if(!has_primary){return false;}
287 return true;}
288 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match(fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
289 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
290 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
291 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects!='undefined'&&typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
292 if(noAdd){enableQS(false);}
293 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field_element_name+"_collection_"+i);var id_field=document.getElementById("id_"+this.field_element_name+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].name==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
294 divCount++;}}
295 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
296 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
297 return false;}};SUGAR.collection.safe_clone=function(e,recursive)
298 {if(e.nodeName=="#text")
299 {return document.createTextNode(e.data);}
300 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
301 {var properties=['class','style','name','type','valign','border','width','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}else{var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}
302 for(var i in properties)
303 {if(e[properties[i]])
304 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
305 newNode[properties[i]]=e[properties[i]];}}
306 if(recursive)
307 {for(var i in e.childNodes)
308 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
309 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
310 return newNode;}}
311 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
312                                 
313 /*********************************************************************************
314  * SugarCRM Community Edition is a customer relationship management program developed by
315  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
316  *
317  * This program is free software; you can redistribute it and/or modify it under
318  * the terms of the GNU Affero General Public License version 3 as published by the
319  * Free Software Foundation with the addition of the following permission added
320  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
321  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
322  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
323  *
324  * This program is distributed in the hope that it will be useful, but WITHOUT
325  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
326  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
327  * details.
328  *
329  * You should have received a copy of the GNU Affero General Public License along with
330  * this program; if not, see http://www.gnu.org/licenses or write to the Free
331  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
332  * 02110-1301 USA.
333  *
334  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
335  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
336  *
337  * The interactive user interfaces in modified source and object code versions
338  * of this program must display Appropriate Legal Notices, as required under
339  * Section 5 of the GNU Affero General Public License version 3.
340  *
341  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
342  * these Appropriate Legal Notices must retain the display of the "Powered by
343  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
344  * technical reasons, the Appropriate Legal Notices must display the words
345  * "Powered by SugarCRM".
346  ********************************************************************************/
347 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
348 return s;},init:function(){if(Rot13.map!=null)
349 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
350 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
351 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
352 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
353 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
354 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
355 return words;}
356 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName,ie_id)
357 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
358 if(typeof(ie_id)=='undefined'||ie_id=='')
359 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id.value:'';URL='index.php?'
360 +'module='+module_name
361 +'&to_pdf=1'
362 +'&action='+action
363 +'&target='+pageTarget
364 +'&target1='+pageTarget
365 +'&server_url='+mail_server
366 +'&email_user='+words[0]
367 +'&protocol='+protocol
368 +'&port='+port
369 +'&email_password='+words[1]
370 +'&mailbox='+words[2]
371 +'&ssl='+ssl
372 +'&ie_id='+ie_id
373 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
374 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
375 this.body.style.width=w}}
376 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
377 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
378 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
379 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
380 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
381 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
382 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
383 if(errors.length>0){out=SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_DESC');for(i=0;i<errors.length;i++){if(out!=""){out+="\n";}
384 out+=errors[i];}
385 alert(out);return false;}else{return true;}}
386 function getFoldersListForInboundAccount(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,searchFieldValue,formName){if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';URL='index.php?'
387 +'module='+module_name
388 +'&to_pdf=1'
389 +'&action='+action
390 +'&target='+pageTarget
391 +'&target1='+pageTarget
392 +'&server_url='+mail_server
393 +'&email_user='+words[0]
394 +'&protocol='+protocol
395 +'&port='+port
396 +'&email_password='+words[1]
397 +'&mailbox='+words[2]
398 +'&ssl='+ssl
399 +'&personal='+isPersonal
400 +'&searchField='+searchFieldValue;var SI=SUGAR.inboundEmail;if(!SI.listDlg){SI.listDlg=new YAHOO.widget.SimpleDialog("selectFoldersDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.listDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
401 this.body.style.width=w}}
402 SI.listDlg.setHeader(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.listDlg.setBody('');SI.listDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.listDlg._updateContent,failure:SI.listDlg.hide,scope:SI.listDlg});SI.listDlg.show();}
403 function setPortDefault(){var prot=document.getElementById('protocol');var ssl=document.getElementById('ssl');var port=document.getElementById('port');var stdPorts=new Array("110","143","993","995");var stdBool=new Boolean(false);if(port.value==''){stdBool.value=true;}else{for(i=0;i<stdPorts.length;i++){if(stdPorts[i]==port.value){stdBool.value=true;}}}
404 if(stdBool.value==true){if(prot.value=='imap'&&ssl.checked==false){port.value="143";}else if(prot.value=='imap'&&ssl.checked==true){port.value='993';}else if(prot.value=='pop3'&&ssl.checked==false){port.value='110';}else if(prot.value=='pop3'&&ssl.checked==true){port.value='995';}}}
405 function toggle_monitored_folder(field){var field1=document.getElementById('protocol');var mailbox=document.getElementById('mailbox');var label_inbox=document.getElementById('label_inbox');var subscribeFolderButton=document.getElementById('subscribeFolderButton');var trashFolderRow=document.getElementById('trashFolderRow');var trashFolderRow1=document.getElementById('trashFolderRow1');var sentFolderRow=document.getElementById('sentFolderRow');if(field1.value=='imap'){mailbox.disabled=false;try{mailbox.style.display='';trashFolderRow.style.display='';sentFolderRow.style.display='';trashFolderRow1.style.display='';subscribeFolderButton.style.display='';}catch(e){};label_inbox.style.display='';}
406 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}
407 // End of File modules/InboundEmail/InboundEmail.js
408                                 
409 /*********************************************************************************
410  * SugarCRM Community Edition is a customer relationship management program developed by
411  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
412  * 
413  * This program is free software; you can redistribute it and/or modify it under
414  * the terms of the GNU Affero General Public License version 3 as published by the
415  * Free Software Foundation with the addition of the following permission added
416  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
417  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
418  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
419  * 
420  * This program is distributed in the hope that it will be useful, but WITHOUT
421  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
422  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
423  * details.
424  * 
425  * You should have received a copy of the GNU Affero General Public License along with
426  * this program; if not, see http://www.gnu.org/licenses or write to the Free
427  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
428  * 02110-1301 USA.
429  * 
430  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
431  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
432  * 
433  * The interactive user interfaces in modified source and object code versions
434  * of this program must display Appropriate Legal Notices, as required under
435  * Section 5 of the GNU Affero General Public License version 3.
436  * 
437  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
438  * these Appropriate Legal Notices must retain the display of the "Powered by
439  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
440  * technical reasons, the Appropriate Legal Notices must display the words
441  * "Powered by SugarCRM".
442  ********************************************************************************/
443
444 SUGAR.email2 = {
445     cache : new Object(),
446     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
447     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
448     templates : {},
449     tinyInstances : {
450         currentHtmleditor : ''
451     },
452
453     /**
454      * preserves hits from email server
455      */ 
456     _setDetailCache : function(ret) {
457         if(ret.meta) {
458             var compKey = ret.meta.mbox + ret.meta.uid;
459
460             if(!SUGAR.email2.cache[compKey]) {
461                 SUGAR.email2.cache[compKey] = ret;
462             }
463         }
464     },
465
466     autoSetLayout : function() {
467         var c = document.getElementById('container');
468         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
469         //Ensure a minimum height.
470         tHeight = Math.max(tHeight, 550);
471         c.style.height = tHeight + "px";
472         SUGAR.email2.complexLayout.set('height', tHeight);
473         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
474         SUGAR.email2.complexLayout.render();
475         SUGAR.email2.listViewLayout.resizePreview();        
476     }
477 };
478
479
480 /**
481  * Shows overlay progress message
482  */
483
484 //overlayModal
485 SUGAR.showMessageBoxModal = function(title, body) {
486     SUGAR.showMessageBox(title, body);
487 }
488
489 //overlay
490 SUGAR.showMessageBox = function(reqtitle, body, type, additconfig) {
491     var config = { };
492     if (typeof(additconfig) == "object") {
493         var config = additconfig;
494     }
495     config.type = type;
496     config.title = reqtitle;
497     config.msg = body;
498     YAHOO.SUGAR.MessageBox.show(config);
499 }
500
501 //hideOverlay
502 SUGAR.hideMessageBox = function() {
503         YAHOO.SUGAR.MessageBox.hide();
504 };
505 // End of File modules/Emails/javascript/EmailUIShared.js
506                                 
507 /*********************************************************************************
508  * SugarCRM Community Edition is a customer relationship management program developed by
509  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
510  * 
511  * This program is free software; you can redistribute it and/or modify it under
512  * the terms of the GNU Affero General Public License version 3 as published by the
513  * Free Software Foundation with the addition of the following permission added
514  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
515  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
516  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
517  * 
518  * This program is distributed in the hope that it will be useful, but WITHOUT
519  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
520  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
521  * details.
522  * 
523  * You should have received a copy of the GNU Affero General Public License along with
524  * this program; if not, see http://www.gnu.org/licenses or write to the Free
525  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
526  * 02110-1301 USA.
527  * 
528  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
529  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
530  * 
531  * The interactive user interfaces in modified source and object code versions
532  * of this program must display Appropriate Legal Notices, as required under
533  * Section 5 of the GNU Affero General Public License version 3.
534  * 
535  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
536  * these Appropriate Legal Notices must retain the display of the "Powered by
537  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
538  * technical reasons, the Appropriate Legal Notices must display the words
539  * "Powered by SugarCRM".
540  ********************************************************************************/
541
542
543 (function() {
544         var sw = YAHOO.SUGAR,
545                 Event = YAHOO.util.Event,
546                 Connect = YAHOO.util.Connect,
547             Dom = YAHOO.util.Dom
548             SE = SUGAR.email2;
549
550 ///////////////////////////////////////////////////////////////////////////////
551 ////    EMAIL ACCOUNTS
552 SE.accounts = {
553     outboundDialog : null,
554     inboundAccountEditDialog : null,
555     inboundAccountsSettingsTable : null,
556     outboundAccountsSettingsTable : null,
557     testOutboundDialog : null,
558     errorStyle : 'input-error',
559     normalStyle : '',
560     newAddedOutboundId : '',
561
562     /**
563      * makes async call to retrieve an outbound instance for editting
564      */
565      //EXT111
566     editOutbound : function(obi) {
567
568             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
569
570     },
571     deleteOutbound : function(obi) {
572
573         if(obi.match(/^(add|line|sendmail)+/)) {
574             alert('Invalid Operation');
575         } else {
576                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
577             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
578         }
579     },
580     //EXT111
581     getReplyAddress : function() {
582         var primary = '';
583
584         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
585             var addy = SE.userPrefs.current_user.emailAddresses[i];
586
587             if(addy.primary_address == "1") {
588                 primary = addy.email_address;
589             }
590
591             if(addy.reply_to == "1") {
592                 return addy.email_address;
593             }
594         }
595
596         return primary;
597     },
598
599     /**
600      * Called on "Accounts" tab activation event
601      */
602     lazyLoad : function() {
603
604         this._setupInboundAccountTable();
605         this._setupOutboundAccountTable();
606
607     },
608
609     _setupInboundAccountTable: function()
610     {
611         //Setup the inbound mail settings
612         if(!this.inboundAccountsSettingsTable)
613         {
614                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
615                                         var clckEvent = oColumn.key;
616                                         var imgSrc = "";
617                                         var is_group = oRecord.getData("is_group");
618                                         if(!is_group)
619                                         {
620                                         if(oColumn.key == 'edit')
621                                         {
622                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
623                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
624                                         }
625                                         else if(oColumn.key == 'delete')
626                                         {
627                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
628                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
629                                         }
630                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
631                                         }
632                    };
633
634                    this.showBoolean = function(el, oRecord, oColumn, oData)
635                    {
636                        var is_group = oRecord.getData("is_group");
637                        var bChecked = oData;
638                        bChecked = (bChecked) ? " checked" : "";
639                        if(!is_group)
640                        {
641                        el.innerHTML = "<input type=\"radio\"" + bChecked +
642                            " name=\"col" + oColumn.getId() + "-radio\"" +
643                            " class=\"yui-dt-radio\">";
644                        }
645                    };
646
647
648                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
649                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
650
651                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
652                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
653                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
654
655
656                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
657                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
658                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
659                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
660                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
661                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
662                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
663                 this.ieDataSource = new YAHOO.util.DataSource(query);
664                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
665                         this.ieDataSource.responseSchema = {
666                                 resultsList: "account_list",
667                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
668                         };
669                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
670                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
671
672                     var elCheckbox = oArgs.target;
673                     var oColumn = this.getColumn(elCheckbox);
674                         if(oColumn.key == 'is_active')
675                         {
676                                 var oRecord = this.getRecord(elCheckbox);
677                                 oRecord.setData("is_active",elCheckbox.checked);
678                                 var t_id = oRecord.getData('id');
679                         var isGroupFolder = oRecord.getData('has_groupfolder');
680
681                         if(isGroupFolder)
682                             SUGAR.email2.folders.updateSubscriptions();
683                         else
684                         SUGAR.email2.folders.setFolderSelection();
685
686                         }
687                 });
688                         var lastDefaultSelectedId = "";
689                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
690
691                     var elRadio = oArgs.target;
692                     var oColumn = this.getColumn(elRadio);
693                         if(oColumn.key == 'is_default')
694                         {
695                                 var oRecord = this.getRecord(elRadio);
696                                 var t_id = oRecord.getData('id');
697                                 var t_isGroup = oRecord.getData('is_group');
698                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
699                                 {
700                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
701                                         lastDefaultSelectedId = t_id;
702                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
703                                 }
704                                 else if(t_isGroup)
705                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
706
707                         }
708                 });
709
710                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
711                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
712         }
713     },
714      _setupOutboundAccountTable: function()
715     {
716         if(!this.outboundAccountsSettingsTable)
717         {
718                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
719                                         var clckEvent = oColumn.key;
720                                         var imgSrc = "";
721                                         var isEditable = oRecord.getData("is_editable");
722                                         var type = oRecord.getData("type");
723                                         if(isEditable)
724                                         {
725                                         if(oColumn.key == 'edit')
726                                         {
727                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
728                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
729                                         }
730                                         else if(oColumn.key == 'delete' && type == 'user')
731                                         {
732                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
733                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
734                                         }
735                                         if(imgSrc != '')
736                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
737                                         }
738                 };
739
740                 //Custom formatter to display any error messages.
741                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
742
743                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
744                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
745
746                         var id = oRecord.getData('id');
747                                         var message = oRecord.getData("errors");
748                                         if(message != '')
749                                         {
750                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
751                                         //Add the id and message for all outbound accounts.
752                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
753                                         }
754                                         else
755                                         {
756                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
757                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
758                                         }
759                 };
760                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
761                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
762
763                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
764                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
765                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
766                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
767
768                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
769                 this.obDataSource = new YAHOO.util.DataSource(query);
770                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
771                         this.obDataSource.responseSchema = {
772
773                                 resultsList: "outbound_account_list",
774                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
775                         };
776
777                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
778
779
780                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
781                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
782                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
783         }
784     },
785     /**
786      * Displays a modal diaglogue to edit outbound account settings
787      */
788     showEditInboundAccountDialogue : function(clear) {
789
790         if(!this.inboundAccountEditDialog) {
791                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
792                 modal:true,
793                                 visible:true,
794                 fixedcenter:true,
795                 constraintoviewport: true,
796                 width   : "600px",
797                 shadow  : true
798             });
799                         EAD.showEvent.subscribe(function() {
800                 var el = this.element;
801                 var viewH = YAHOO.util.Dom.getViewportHeight();
802                 if (this.header && el && viewH - 50 < el.clientHeight) {
803                     var body = this.header.nextElementSibling;
804                                         body.style.overflow = "hidden";
805                     body.style.height = "100%";
806                 }
807             }, EAD);
808             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
809                         Dom.removeClass("editAccountDialogue", "yui-hidden");
810
811         } // end lazy load
812
813         if(clear == undefined || clear == true)
814         {
815                 SE.accounts.clearInboundAccountEditScreen();
816                 //Set default protocol to IMAP when creating new records
817                 document.forms['ieAccount'].elements['protocol'].value = "imap";
818                 SE.accounts.setPortDefault();
819         }
820
821         //Check if we should display username/password fields for outbound account if errors were detected.
822         this.checkOutBoundSelection();
823
824         this.inboundAccountEditDialog.render();
825         this.inboundAccountEditDialog.show();
826         SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
827     },
828
829     /**
830     *  Set all fields on the outbound edit form to either enabled/disabled
831     *  except for the username/password.
832     *
833     */
834     toggleOutboundAccountDisabledFields: function(disable)
835     {
836         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
837         for(var i=0;i<fields.length;i++)
838         {
839             document.getElementById(fields[i]).disabled = disable;
840         }
841         if(disable)
842             Dom.addClass("mail_smtpssl_row", "yui-hidden");
843         else
844             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
845
846     },
847     /**
848     * Refresh the inbound accounts table.
849     */
850     refreshInboundAccountTable : function()
851     {
852             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
853                 {
854                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
855                                 scope: this.inboundAccountsSettingsTable }
856                         );
857     },
858     /**
859     * Refresh the outbound accounts table.
860     */
861     refreshOuboundAccountTable : function()
862     {
863             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
864                 {
865                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
866                                 scope: this.outboundAccountsSettingsTable }
867                         );
868     },
869     /**
870      * Displays a modal diaglogue to add a SMTP server
871      */
872     showAddSmtp : function() {
873         // lazy load dialogue
874         if(!this.outboundDialog) {
875                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
876                 modal:true,
877                                 visible:true,
878                 fixedcenter:true,
879                 constraintoviewport: true,
880                 width   : "750px",
881                 shadow  : true
882             });
883             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
884             this.outboundDialog.hideEvent.subscribe(function(){
885                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
886                 var out = Dom.get("outbound_email");
887                 if (out && out.value == "SYSTEM_ADD")
888                 {
889                         out.value = out.options[0].value;
890                 }
891                 //Check if we should display username/password for system account.
892                 SE.accounts.checkOutBoundSelection();
893                 return true;
894             });
895
896             Dom.removeClass("outboundDialog", "yui-hidden");
897         } // end lazy load
898
899         // clear out form
900         var form = document.getElementById('outboundEmailForm');
901         for(i=0; i<form.elements.length; i++) {
902             if(form.elements[i].name == 'mail_smtpport') {
903                 form.elements[i].value = 25;
904             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
905                 form.elements[i].value = '';
906             } else if(form.elements[i].type == 'checkbox') {
907                 form.elements[i].checked = false;
908             }
909         }
910         //Render the SMTP buttons
911         if ( !SUGAR.smtpButtonGroup ) {
912             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
913             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
914             {
915                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
916                 document.getElementById('smtp_settings').style.display = '';
917                 form.mail_smtptype.value = e.newValue.get('value');
918             });
919             YAHOO.widget.Button.addHiddenFieldsToForm(form);
920         }
921         //Hide Username/Password
922         SUGAR.email2.accounts.smtp_authenticate_field_display();
923         //Unset readonly fields
924         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
925         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
926                 this.outboundDialog.render();
927         this.outboundDialog.show();
928     },
929
930     /**
931      * Accounts' Advanced Settings view toggle
932      */
933     toggleAdv : function() {
934         var adv = document.getElementById("ie_adv");
935         if(adv.style.display == 'none') {
936             adv.style.display = "";
937         } else {
938             adv.style.display = 'none';
939         }
940     },
941
942         smtp_authenticate_field_display : function() {
943                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
944                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
945                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
946         },
947         
948         smtp_setDefaultSMTPPort : function() {
949                 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
950     
951         if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
952             document.getElementById("mail_smtpport").value = '465';
953         }
954         if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
955             document.getElementById("mail_smtpport").value = '25';
956         }
957         },
958
959     /**
960      * Changes the display used in the outbound email SMTP dialog to match the
961      */
962     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
963     {
964         document.getElementById("smtpButtonGroupTD").style.display = '';
965         document.getElementById("chooseEmailProviderTD").style.display = '';
966         document.getElementById("mailsettings1").style.display = '';
967         document.getElementById("mailsettings2").style.display = '';
968         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
969         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
970         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
971         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
972
973         switch (smtptype) {
974         case "yahoomail":
975             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
976             document.getElementById("mail_smtpport").value = '465';
977             document.getElementById("mail_smtpauth_req").checked = true;
978             var ssl = document.getElementById("mail_smtpssl");
979             for(var j=0;j<ssl.options.length;j++) {
980                 if(ssl.options[j].text == 'SSL') {
981                     ssl.options[j].selected = true;
982                     break;
983                 }
984             }
985             document.getElementById("mailsettings1").style.display = 'none';
986             document.getElementById("mailsettings2").style.display = 'none';
987             document.getElementById("mail_smtppass_label").innerHTML =
988             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
989             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
990             break;
991         case "gmail":
992             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
993             document.getElementById("mail_smtpport").value = '587';
994             document.getElementById("mail_smtpauth_req").checked = true;
995             var ssl = document.getElementById("mail_smtpssl");
996             for(var j=0;j<ssl.options.length;j++) {
997                 if(ssl.options[j].text == 'TLS') {
998                     ssl.options[j].selected = true;
999                     break;
1000                 }
1001             }
1002             document.getElementById("mailsettings1").style.display = 'none';
1003             document.getElementById("mailsettings2").style.display = 'none';
1004             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
1005             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1006             break;
1007         case "exchange":
1008             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1009                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1010                 document.getElementById("mail_smtpserver").value = '';
1011             }
1012             document.getElementById("mail_smtpport").value = '25';
1013             document.getElementById("mail_smtpauth_req").checked = true;
1014             document.getElementById("mailsettings1").style.display = '';
1015             document.getElementById("mailsettings2").style.display = '';
1016             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1017             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1018             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1019             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1020             break;
1021         }
1022         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1023         {
1024             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1025             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1026             document.getElementById("mailsettings2").style.display = 'none';
1027         }
1028
1029         SUGAR.email2.accounts.smtp_authenticate_field_display();
1030         SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1031     },
1032
1033     /**
1034     * Fill the gmail default values for inbound accounts.
1035     */
1036     fillInboundGmailDefaults: function () {
1037
1038         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1039         document.forms['ieAccount'].elements['ssl'].checked = true;
1040         document.forms['ieAccount'].elements['protocol'].value = "imap";
1041         SUGAR.email2.accounts.setPortDefault();
1042         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1043     },
1044     /**
1045      * Sets Port field to selected protocol and SSL settings defaults
1046      */
1047     setPortDefault : function() {
1048         var prot = document.getElementById('protocol');
1049         var ssl  = document.getElementById('ssl');
1050         var port = document.getElementById('port');
1051         var stdPorts= new Array("110", "143", "993", "995");
1052         var stdBool    = new Boolean(false);
1053         var mailboxdiv = document.getElementById("mailboxdiv");
1054         var trashFolderdiv = document.getElementById("trashFolderdiv");
1055         var sentFolderdiv = document.getElementById("sentFolderdiv");
1056                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1057         if(port.value == '') {
1058             stdBool.value = true;
1059         } else {
1060             for(i=0; i<stdPorts.length; i++) {
1061                 if(stdPorts[i] == port.value) {
1062                     stdBool.value = true;
1063                 }
1064             }
1065         }
1066
1067         if(stdBool.value == true) {
1068             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1069                 port.value = "143";
1070             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1071                 port.value = '993';
1072             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1073                 port.value = '110';
1074             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1075                 port.value = '995';
1076             }
1077         }
1078
1079         if (prot.value == 'imap') {
1080                 mailboxdiv.style.display = "";
1081                 trashFolderdiv.style.display = "";
1082                 sentFolderdiv.style.display = "";
1083                 monitoredFolder.style.display = "";
1084                 if (document.getElementById('mailbox').value == "") {
1085                         document.getElementById('mailbox').value = "INBOX";
1086                 }
1087         } else {
1088                 mailboxdiv.style.display = "none";
1089                 trashFolderdiv.style.display = "none";
1090                 sentFolderdiv.style.display = "none";
1091                         monitoredFolder.style.display = "none";
1092                 document.getElementById('mailbox').value = "";
1093         } // else
1094     },
1095
1096     /**
1097      * Draws/removes red boxes around required fields.
1098      */
1099     ieAccountError : function(style) {
1100         document.getElementById('server_url').className = style;
1101         document.getElementById('email_user').className = style;
1102         document.getElementById('email_password').className = style;
1103         document.getElementById('protocol').className = style;
1104         document.getElementById('port').className = style;
1105     },
1106
1107     checkOutBoundSelection: function() {
1108         var select = Dom.get('outbound_email');
1109         if (!select || select.selectedIndex == -1) { return; }
1110
1111         var v = select.options[select.selectedIndex].value;
1112
1113         if(v == '')
1114         {
1115                 select.options[select.selectedIndex].selected = false;
1116                 v = select.options[0].value;
1117         }
1118         else if (v == 'SYSTEM_ADD')
1119                 SUGAR.email2.accounts.showAddSmtp();
1120
1121         var foundError = false;
1122         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1123                 for(i in errorAccounts)
1124                 {
1125                     if(v == i)
1126                     {
1127                         foundError = true;
1128                         break;
1129                     }
1130                 }
1131
1132                 //Should username/password fields for outbound account.
1133                 if(foundError)
1134                     this.toggleInboundOutboundFields(true);
1135                 else
1136                     this.toggleInboundOutboundFields(false);
1137
1138
1139
1140     },
1141     toggleInboundOutboundFields : function (display)
1142     {
1143         if(display)
1144         {
1145             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1146                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1147         }
1148         else
1149         {
1150             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1151                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1152         }
1153     },
1154     /**
1155      * rebuilds the select options for mailer options
1156      */
1157     rebuildMailerOptions : function() {
1158         var select = document.forms['ieAccount'].elements['outbound_email'];
1159         SE.util.emptySelectOptions(select);
1160
1161         //Get the available sugar mailers
1162         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1163
1164         for(i=0;i<a_outbound.length;i++)
1165         {
1166                 var t_record = a_outbound[i];
1167                 var key = t_record.getData('id');
1168                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1169
1170                 var opt = new Option(display, key);
1171                 select.options.add(opt);
1172                 if (key == SE.accounts.newAddedOutboundId) {
1173                         select.options.selectedIndex = i;
1174                 }
1175         }
1176
1177         select.options.add(new Option('',''));
1178         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1179         //Hide/Show username password fields if necessary.
1180         SE.accounts.checkOutBoundSelection();
1181     },
1182     /**
1183      * Empties all the fields in the accounts edit view
1184      */
1185     clearInboundAccountEditScreen:function() {
1186
1187         document.getElementById('ie_id').value = '';
1188         document.getElementById('ie_name').value = '';
1189         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1190         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1191         document.getElementById('reply_to_addr').value = '';
1192         document.getElementById('server_url').value = '';
1193         document.getElementById('email_user').value = '';
1194         document.getElementById('email_password').value = '';
1195         document.getElementById('port').value = '';
1196         document.getElementById('inbound_mail_smtpuser').value = '';
1197         document.getElementById('inbound_mail_smtppass').value = '';
1198         document.ieAccount.protocol.options[0].selected = true;
1199         // handle SSL
1200         document.getElementById('ssl').checked = false;
1201         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1202     },
1203
1204     /**
1205      * Populates an account's fields in Settings->Accounts
1206      */
1207     fillIeAccount:function(jsonstr) {
1208         var o = YAHOO.lang.JSON.parse(jsonstr);
1209
1210         document.getElementById('ie_id').value = o.id;
1211         document.getElementById('ie_name').value = o.name;
1212         if (o.stored_options != null) {
1213                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1214                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1215                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1216                 if (o.stored_options.trashFolder != null) {
1217                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1218                 }
1219                 if (o.stored_options.sentFolder != null) {
1220                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1221                 }
1222         }
1223         document.getElementById('server_url').value = o.server_url;
1224         document.getElementById('email_user').value = o.email_user;
1225         document.getElementById('port').value = o.port;
1226         document.getElementById('group_id').value = o.group_id;
1227         document.getElementById('mailbox').value = o.mailbox;
1228
1229
1230         var i = 0;
1231
1232         // handle SSL
1233         if(typeof(o.service[2]) != 'undefined') {
1234             document.getElementById('ssl').checked = true;
1235         }
1236
1237         // handle protocol
1238         if(document.getElementById('protocol').value != o.protocol) {
1239             var prot = document.getElementById('protocol');
1240             for(i=0; i<prot.options.length; i++) {
1241                 if(prot.options[i].value == o.service[3]) {
1242                     prot.options[i].selected = true;
1243                     this.setPortDefault();
1244                 }
1245             }
1246         }
1247  // handle SMTP selection
1248         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1249             var opts = document.getElementById('outbound_email').options;
1250             for(i=0; i<opts.length; i++) {
1251                 if(opts[i].value == o.stored_options.outbound_email) {
1252                     opts[i].selected = true;
1253                 }
1254             }
1255         }
1256     },
1257
1258     deleteIeAccount : function(IeAccountID,IeGroupID) {
1259         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1260         {
1261             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1262
1263             AjaxObject.target = 'frameFlex';
1264             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1265             SUGAR.email2.accounts.refreshInboundAccountTable();
1266          }
1267      },
1268
1269        // Null check for Outbound Settings.
1270     checkOutboundSettings: function() {
1271         var errorMessage = '';
1272         var isError = false;
1273         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1274             var mailName = document.getElementById('mail_name').value;
1275             var smtpServer = document.getElementById('mail_smtpserver').value;
1276             var smtpPort = document.getElementById('mail_smtpport').value;
1277
1278             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1279             if(trim(mailName) == '') {
1280                 isError = true;
1281                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1282             }
1283             if(trim(smtpServer) == '') {
1284                 isError = true;
1285                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1286             }
1287             if(trim(smtpPort) == '') {
1288                 isError = true;
1289                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1290             }
1291             if(mailsmtpauthreq.checked) {
1292                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1293                     isError = true;
1294                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1295                 }
1296             }
1297         }
1298         if(isError) {
1299             SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1300             return false;
1301         } else {
1302             return true;
1303         }
1304     },
1305
1306     testOutboundSettings: function() {
1307         var errorMessage = '';
1308         var isError = false;
1309         var fromAddress = document.getElementById("outboundtest_from_address").value;
1310         if (trim(fromAddress) == "") {
1311             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1312             SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1313             return false;
1314
1315         }
1316         else if (!isValidEmail(fromAddress)) {
1317             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1318             SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1319             return false;
1320         }
1321
1322         //Hide the dialogue and show an in progress indicator.
1323         SE.accounts.testOutboundDialog.hide();
1324         SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1325
1326         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1327         //nothing is sent in the request.
1328         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1329         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1330
1331         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1332         if(outboundType == 'system-override')
1333             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1334
1335         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1336         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1337
1338     },
1339
1340     testOutboundSettingsDialog: function() {
1341         //Ensure that all settings are correct before proceeding to send test email.
1342         if(!SE.accounts.checkOutboundSettings())
1343             return;
1344
1345         // lazy load dialogue
1346         if(!SE.accounts.testOutboundDialog) {
1347                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1348                 modal:true,
1349                                 visible:true,
1350                 fixedcenter:true,
1351                 constraintoviewport: true,
1352                 width   : 600,
1353                 shadow  : true
1354             });
1355             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1356             Dom.removeClass("testOutboundDialog", "yui-hidden");
1357         } // end lazy load
1358         SE.accounts.testOutboundDialog.render();
1359         SE.accounts.testOutboundDialog.show();
1360     },
1361
1362     /**
1363      * Saves Outbound email settings
1364      */
1365     saveOutboundSettings : function() {
1366         if(SE.accounts.checkOutboundSettings()) {
1367             //Enable the form fields for the post.
1368             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1369             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1370             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1371         } else {
1372             return false;
1373         }
1374     },
1375
1376     saveIeAccount : function() {
1377
1378         //Before saving check if there are any error messages associated with the outbound account.
1379         var outboundID = document.getElementById('outbound_email').value;
1380
1381         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1382             'validateSMTPCreds':true}) )
1383         {
1384             document.getElementById('saveButton').disabled = true;
1385
1386             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1387
1388             var formObject = document.getElementById('ieAccount');
1389             YAHOO.util.Connect.setForm(formObject);
1390
1391             AjaxObject._reset();
1392             AjaxObject.target = 'frameFlex';
1393             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1394         }
1395     },
1396
1397     testSettings : function() {
1398         form = document.getElementById('ieAccount');
1399
1400         if(SE.accounts.checkIeCreds()) {
1401             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);
1402         }
1403     },
1404
1405     getFoldersListForInboundAccountForEmail2 : function() {
1406         form = document.getElementById('ieAccount');
1407         if(SE.accounts.checkIeCreds()) {
1408                 var mailBoxValue = form.mailbox.value;
1409                 if (form.searchField.value.length > 0) {
1410                         mailBoxValue = "";
1411                 } // if
1412             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 );
1413         } // if
1414
1415     },
1416
1417     checkIeCreds : function(validateRules) {
1418         if(typeof(validateRules) == 'undefined')
1419             validateRules = {};
1420
1421         var errors = new Array();
1422         var out = new String();
1423
1424         var ie_name = Dom.get('ie_name').value;
1425         var fromAddress = Dom.get('ie_from_addr').value;
1426         var server_url = Dom.get('server_url').value;
1427         var email_user = Dom.get('email_user').value;
1428         var email_password = Dom.get('email_password').value;
1429         var protocol = Dom.get('protocol').value;
1430         var port = Dom.get('port').value;
1431         var oe = Dom.get('outbound_email');
1432
1433         // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1434         // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1435         // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1436         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;
1437
1438         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1439         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1440
1441         //If the username and password were provided then ignore the error messge
1442
1443         var outboundCredentialsFound = false;
1444
1445         if(outboundUserName != "" && outboundPass != "")
1446             outboundCredentialsFound = true;
1447
1448         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1449
1450         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1451              && validateSMTPCreds)
1452         {
1453             if(trim(outboundUserName) == "") {
1454                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1455             }
1456             if(trim(outboundPass) == "") {
1457                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1458             }
1459         }
1460
1461         if(trim(ie_name) == "") {
1462             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1463         }
1464
1465         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1466         {
1467             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1468                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1469             }
1470         }
1471
1472
1473         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1474              || trim(oe_value) == "SYSTEM_ADD") ) {
1475             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1476         }
1477         if(trim(server_url) == "") {
1478             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1479         }
1480         if(trim(email_user) == "") {
1481             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1482         }
1483         if(protocol == "") {
1484             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1485         }
1486         if (protocol == 'imap') {
1487                 var mailbox = document.getElementById('mailbox').value;
1488                 if (trim(mailbox) == "") {
1489                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1490                 } // if
1491                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1492                         var trashFolder = document.getElementById('trashFolder').value;
1493                         if (trim(trashFolder) == "") {
1494                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1495                         } // if
1496                         } // if
1497         }
1498         if(port == "") {
1499             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1500         }
1501
1502         if(errors.length > 0) {
1503             out = app_strings.LBL_EMAIL_ERROR_DESC;
1504             for(i=0; i<errors.length; i++) {
1505                 if(out != "") {
1506                     out += "\n";
1507                 }
1508                 out += errors[i];
1509             }
1510
1511             alert(out);
1512             return false;
1513         } else {
1514
1515             return true;
1516         }
1517     },
1518
1519     getIeAccount : function(ieId) {
1520         if(ieId == '')
1521             return;
1522
1523         SUGAR.showMessageBox(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1524                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1525
1526         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1527     },
1528
1529     /**
1530      * Iterates through TreeView nodes to apply styles dependent nature of node
1531      */
1532     renderTree:function() {
1533         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1534         SE.tree.render();
1535     },
1536
1537     //Sets the style for any nodes that need it.
1538     setNodeStyle : function(node) {
1539         if (!node.data.origText) {
1540             node.data.origText = node.data.text;
1541         }
1542         //Set unread
1543         if (typeof(node.data.unseen) != 'undefined') {
1544                 if (node.data.unseen > 0) {
1545                                 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1546                 // Add bold style to label, kinda hacky
1547                 node.labelStyle += " ygtvlabelbold";
1548                         }
1549                         else {
1550                                 node.setUpLabel(node.data.origText);
1551                         }
1552         } else {
1553                 node.setUpLabel(node.data.origText);
1554         }
1555         SE.accounts.setupDDTarget(node);
1556     },
1557
1558     setupDDTarget : function(node) {
1559         if (node.ddTarget) {
1560                 node.ddTarget.removeFromGroup();
1561                 delete node.ddTarget;
1562         }
1563         var id = node.getElId();
1564         var num = id.substring(4);
1565         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1566                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1567                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1568
1569                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1570         }
1571         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1572                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1573         }
1574     },
1575
1576     /**
1577      * Async call to rebuild the folder list.  After a folder delete or account delete
1578      */
1579     rebuildFolderList : function() {
1580         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1581         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1582     },
1583
1584     /**
1585      * Returns the number of remote accounts the user has active.
1586      */
1587     getAccountCount : function() {
1588         var tree = SE.tree;
1589         var count = 0;
1590         for(i=0; i<tree._nodes.length; i++) {
1591             var node = tree._nodes[i];
1592
1593             if(typeof(node) != 'undefined' && node.data.ieId) {
1594                 count++;
1595             }
1596         }
1597         return count;
1598     }
1599 };
1600 ////    END ACCOUNTS
1601 ///////////////////////////////////////////////////////////////////////////////
1602
1603
1604
1605
1606 ///////////////////////////////////////////////////////////////////////////////
1607 ////    CONTEXT MENU CALLS
1608 SE.contextMenus = {
1609
1610     assignToDialogue : null,
1611     /**
1612      * Archives from context menu
1613      * @param Array uids
1614      * @param string ieId
1615      * @param string folder
1616      */
1617     _archiveToSugar : function(uids, ieId, folder) {
1618         var ser = '';
1619
1620         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1621             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1622             ser += uids[i];
1623         }
1624         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1625     },
1626
1627     /**
1628      * Archives from context menu
1629      */
1630     archiveToSugar : function(menuItem) {
1631         SE.contextMenus.emailListContextMenu.hide();
1632
1633         var rows = SE.grid.getSelectedRows();
1634         var uids = [];
1635         /* iterate through available rows JIC a row is deleted - use first available */
1636         for(var i=0; i<rows.length; i++) {
1637             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1638         }
1639         var data = SE.grid.getRecord(rows[0]).getData();
1640         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1641     },
1642
1643     /**
1644      * Popup the printable version and start system's print function.
1645      */
1646     viewPrintable : function(menuItem) {
1647         var rows = SE.grid.getSelectedRows();
1648         var data = SE.grid.getRecord(rows[0]).getData();
1649         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1650     },
1651
1652     /**
1653      * Marks email flagged on mail server
1654      */
1655     markRead : function(type, contextMenuId) {
1656         SE.contextMenus.markEmail('read');
1657     },
1658
1659     /**
1660      * Assign this emails to people based on assignment rules
1661      */
1662     assignEmailsTo : function(type, contextMenuId) {
1663         if(!SE.contextMenus.assignToDialogue)
1664         {
1665                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1666                 modal:true,
1667                                 visible:false,
1668                 fixedcenter:true,
1669                 constraintoviewport: true,
1670                 width   : "600px",
1671                 shadow  : true
1672             });
1673             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1674             enableQS(true);
1675         }
1676
1677         Dom.removeClass("assignToDiv", "yui-hidden");
1678         SE.contextMenus.assignToDialogue.render();
1679         SE.contextMenus.assignToDialogue.show();
1680     },
1681
1682     /**
1683      * Marks email flagged on mail server
1684      */
1685     markFlagged : function(contextMenuId) {
1686         SE.contextMenus.markEmail('flagged');
1687     },
1688
1689     /**
1690      * Marks email unflagged on mail server
1691      */
1692     markUnflagged : function(contextMenuId) {
1693         SE.contextMenus.markEmail('unflagged');
1694     },
1695
1696     /**
1697      * Marks email unread on mail server
1698      */
1699     markUnread : function() {
1700         SE.contextMenus.markEmail('unread');
1701     },
1702
1703     /**
1704      * Deletes an email from context menu
1705      */
1706     markDeleted : function() {
1707         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1708                 document.getElementById('_blank').innerHTML = "";
1709                 SE.contextMenus.markEmail('deleted');
1710         }
1711     },
1712
1713     /**
1714      * generic call API to apply a flag to emails on the server and on sugar
1715      * @param string type "read" | "unread" | "flagged" | "deleted"
1716      */
1717     markEmail : function(type) {
1718         SE.contextMenus.emailListContextMenu.hide();
1719
1720         //var dm = SE.grid.getStore();
1721         //var uids = SE.grid.getSelectedRowIds();
1722         //var indexes = SE.grid.getSelectedRowIndexes();
1723         var rows = SE.grid.getSelectedRows();
1724         if (rows.length == 0)
1725                 rows = [SE.contextMenus.currentRow];
1726         var ser = [ ];
1727
1728         for(var i=0; i<rows.length; i++) {
1729             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1730         }
1731
1732         ser = YAHOO.lang.JSON.stringify(ser);
1733
1734         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1735         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1736
1737
1738         var count = 0;
1739
1740
1741         if(type == 'read' || type == 'deleted') {
1742             // mark read
1743             for(var j=0; j<rows.length; j++) {
1744                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1745                     count = count + 1;
1746                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1747                 }
1748             }
1749            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1750             if(ieId){
1751             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1752             var unseenCount = node.data.unseen;
1753             if (isNaN(unseenCount)) {
1754                 unseenCount = 0;
1755             }
1756             var finalCount = parseInt(unseenCount) - count;
1757             node.data.unseen = finalCount;
1758
1759             SE.accounts.renderTree();
1760             }
1761         } else if(type == 'unread') {
1762             // mark unread
1763             for(var j=0; j<rows.length; j++) {
1764                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1765                     count = count + 1;
1766                 }
1767             }
1768
1769             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1770             var unseenCount = node.data.unseen;
1771             if (isNaN(unseenCount)) {
1772                 unseenCount = 0;
1773             }
1774             var finalCount = parseInt(unseenCount) + count;
1775             node.data.unseen = finalCount;
1776             SE.accounts.renderTree();
1777         }
1778
1779         if (type == 'unread') {
1780                 for(var i=0; i<rows.length; i++) {
1781                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1782                 } // for
1783         }
1784
1785                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1786         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1787     },
1788
1789     /**
1790      * refreshes the ListView to show changes to cache
1791      */
1792     markEmailCleanup : function() {
1793         SE.accounts.renderTree();
1794         SUGAR.hideMessageBox();
1795         SE.listView.refreshGrid();
1796     },
1797
1798         showAssignmentDialog : function() {
1799                 if (SE.contextMenus.assignmentDialog == null) {
1800                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1801                 } else {
1802                         SE.contextMenus.assignmentDialog.show();
1803                 } // else
1804         },
1805
1806         /**
1807      * shows the import dialog with only relate visible.
1808      */
1809     relateTo : function() {
1810         SE.contextMenus.emailListContextMenu.hide();
1811
1812         var rows = SE.grid.getSelectedRows();
1813         var data = SE.grid.getRecord(rows[0]).getData();
1814         var ieId = data.ieId;
1815         var folder = data.mbox;
1816         var uids = [];
1817         /* iterate through available rows JIC a row is deleted - use first available */
1818         for(var i=0; i<rows.length; i++) {
1819             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1820         }
1821         var ser = YAHOO.lang.JSON.stringify(uids);
1822         
1823         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1824     },
1825
1826         /**
1827      * shows the import dialog with only relate visible.
1828      */
1829     showDetailView : function() {
1830         SE.contextMenus.emailListContextMenu.hide();
1831         var rows = SE.grid.getSelectedRows();
1832         if (rows.length > 1) {
1833                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1834                 return;
1835         }
1836         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1837         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1838         /* iterate through available rows JIC a row is deleted - use first available */
1839         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1840         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1841     },
1842
1843     /**
1844      *
1845      */
1846     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1847         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1848         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1849     },
1850
1851     /**
1852      * Opens multiple messages from ListView context click
1853      */
1854     openMultiple : function() {
1855         SE.contextMenus.emailListContextMenu.hide();
1856
1857         var rows = SE.grid.getSelectedRows();
1858         var uids = SE.listView.getUidsFromSelection();
1859
1860         if(uids.length > 0) {
1861             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1862             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1863             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1864         }
1865     },
1866
1867     /**
1868      * Replies/forwards email
1869      */
1870     replyForwardEmailContext : function() {
1871         SE.contextMenus.emailListContextMenu.hide();
1872
1873         var indexes = SE.grid.getSelectedRows();
1874         //var dm = SE.grid.getDataModel();
1875         var type = this.id;
1876
1877         for(var i=0; i<indexes.length; i++) {
1878             var row = SE.grid.getRecord(indexes[i]).getData();
1879             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1880         }
1881     },
1882
1883     //show menu functions
1884     showEmailsListMenu : function(grid, row) {
1885
1886        var data = row.getData();
1887        var draft = (data.type == "draft");
1888        var menu = SE.contextMenus.emailListContextMenu;
1889        var folderNode;
1890
1891        if (SE.tree)
1892        {
1893                if (data.mbox == 'sugar::Emails')
1894                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1895                else
1896                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1897
1898                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1899                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1900                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1901                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1902                else
1903                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1904        }
1905        else
1906            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1907
1908        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1909        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1910        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1911        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1912        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1913
1914
1915        if (data.mbox == "sugar::Emails")
1916        {
1917            //Allow users to reassign imported emails
1918            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1919            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1920            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1921            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1922        }
1923        else
1924        {
1925            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1926            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1927        }
1928     },
1929
1930     showFolderMenu : function(grid, rowIndex, event) {
1931        event.stopEvent();
1932        var coords = event.getXY();
1933        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1934     }
1935 };
1936
1937 SE.contextMenus.dv = {
1938     archiveToSugar : function(contextMenuId) {
1939
1940         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1941     },
1942
1943     replyForwardEmailContext : function(all) {
1944         SE.contextMenus.detailViewContextMenu.hide();
1945     }
1946
1947 };
1948
1949
1950
1951
1952
1953 ////    END SE.contextMenus
1954 ///////////////////////////////////////////////////////////////////////////////
1955
1956
1957
1958 ///////////////////////////////////////////////////////////////////////////////
1959 ////    DETAIL VIEW
1960 SE.detailView = {
1961     consumeMetaDetail : function(ret) {
1962         // handling if the Email drafts
1963         if(ret.type == 'draft') {
1964             SE.composeLayout.c0_composeDraft();
1965             return;
1966         }
1967
1968
1969         // cache contents browser-side
1970         SE._setDetailCache(ret);
1971
1972         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1973         // 2 below must be in global context
1974         meta = ret.meta;
1975         meta['panelId'] = SE.util.getPanelId();
1976
1977         email = ret.meta.email;
1978         var out = displayTemplate.exec({
1979             'app_strings' : app_strings,
1980             'theme' : theme,
1981             'idx' : targetDiv.id,
1982             'meta' : meta,
1983             'email' : meta.email,
1984             'linkBeans' : linkBeans
1985         });
1986         var tabLabel = meta.email.name;
1987         if (tabLabel != null && tabLabel.length > 25) {
1988                 tabLabel = tabLabel.substring(0, 25) + "...";
1989         } // if
1990         targetDiv.set("label", tabLabel);
1991         targetDiv.set("content", out);
1992
1993         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1994         if (SUGAR.email2.util.isIe()) {
1995                 displayEmailFrameDiv.style.height = "390px";
1996         } else {
1997                 displayEmailFrameDiv.style.height = "410px";
1998         }
1999
2000         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
2001         displayFrame.contentWindow.document.write(email.description);
2002         displayFrame.contentWindow.document.close();
2003
2004         // hide archive links
2005         if(ret.meta.is_sugarEmail) {
2006                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
2007             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2008         } else {
2009             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2010                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2011         } // else
2012
2013     },
2014
2015     consumeMetaPreview : function(ret) {
2016         // cache contents browser-side
2017         SE._setDetailCache(ret);
2018
2019
2020
2021         var currrow = SE.grid.getLastSelectedRecord();
2022         currrow = SE.grid.getRecord(currrow);
2023         if (!currrow) {
2024             document.getElementById('_blank').innerHTML = '';
2025             return;
2026         }
2027         // handling if the Email drafts
2028         if(ret.type == 'draft'){
2029             if (currrow.getData().uid == ret.uid) {
2030                 SE.composeLayout.c0_composeDraft();
2031             }
2032             return;
2033         }
2034
2035         if (currrow.getData().uid != ret.meta.uid) {
2036            return;
2037         }
2038
2039         // remove loading sprite
2040         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2041         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2042         meta = ret.meta;
2043         meta['panelId'] = SE.util.getPanelId();
2044         email = ret.meta.email;
2045
2046         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2047             'app_strings' : app_strings,
2048             'theme' : theme,
2049             'idx' : 'Preview',
2050             'meta' : meta,
2051             'email' :meta.email,
2052             'linkBeans' : linkBeans
2053         });
2054        // document.getElementById('_blank').innerHTML = meta.email;
2055        /* displayTemplate.append('_blank', {
2056             'app_strings' : app_strings,
2057             'theme' : theme,
2058             'idx' : 'Preview',
2059             'meta' : meta,
2060             'email' :meta.email,
2061             'linkBeans' : linkBeans
2062         });*/
2063
2064         var displayFrame = document.getElementById('displayEmailFramePreview');
2065         displayFrame.contentWindow.document.write(email.description);
2066         displayFrame.contentWindow.document.close();
2067
2068         SE.listViewLayout.resizePreview();
2069
2070         // hide archive links
2071         if(ret.meta.is_sugarEmail) {
2072             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2073             document.getElementById("btnEmailViewPreview").style.display = "none";
2074             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2075         } else {
2076           //hide view relationship link
2077                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2078         }
2079     },
2080
2081     /**
2082      * wraps emailDelete() for single messages, comes from preview or tab
2083      */
2084     emailDeleteSingle : function(ieId, uid, mbox) {
2085         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2086             // find active panel and close if the user double clicked the email to view.
2087             var activeTabId = SE.util.getPanelId();
2088             if(activeTabId != 'Preview')
2089                 SE.innerLayout.get("activeTab").close();
2090
2091             document.getElementById('_blank').innerHTML = "";
2092                 var ser = [ ];
2093                         ser.push(uid);
2094                 uid = YAHOO.lang.JSON.stringify(ser);
2095             this.emailDelete(ieId, uid, mbox);
2096         }
2097     },
2098
2099     /**
2100      * Sends async call to delete a given message
2101      * @param
2102      */
2103     emailDelete : function(ieId, uid, mbox) {
2104        SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2105        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2106            uid + "&ieId=" + ieId + "&folder=" + mbox);
2107     },
2108
2109     /**
2110      * retrieves one email to display in the preview pane.
2111      */
2112     getEmailPreview : function() {
2113         var row = SUGAR.email2.listView.currentRow;
2114         var data = row.getData();
2115             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2116                var setRead = (data['seen'] == 0) ? true : false;
2117                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2118                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2119             }
2120     },
2121
2122     /**
2123      * Imports one email into Sugar
2124      */
2125     importEmail : function(ieId, uid, mbox) {
2126         SE.util.clearHiddenFieldValues('emailUIForm');
2127
2128         SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2129
2130         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2131         AjaxObject.target = '';
2132         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2133     },
2134
2135     /**
2136      * Populates the frameFlex div with the contents of an email
2137      */
2138     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2139         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2140
2141         var mboxStr = new String(mbox);
2142         var compKey = mbox + uid;
2143
2144         if(setRead == true) {
2145                 SE.listView.boldUnreadRows()
2146                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2147         }
2148
2149         if(destination == SE.innerLayout) {
2150                 /*
2151              * loading email into a tab, peer with ListView
2152              * targetDiv must remain in the global namespace as it is used by AjaxObject
2153              */
2154                 //Check if we already have a tab of the email open
2155                 var tabs = SE.innerLayout.get("tabs");
2156                 for (var t in tabs) {
2157                         if (tabs[t].id && tabs[t].id == uid) {
2158                                 SE.innerLayout.set("activeTab", tabs[t]);
2159                                 return;
2160                         }
2161                 }
2162
2163                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2164                                 label: loadingSprite,
2165                                         scroll : true,
2166                                         content : "",
2167                                         active : true
2168                 }, SE.innerLayout);
2169                 targetDiv.id = uid;
2170                 SE.innerLayout.addTab(targetDiv);
2171
2172             // use cache if available
2173             if(SE.cache[compKey]) {
2174                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2175             } else {
2176                 // open email as peer-tab to listView
2177                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2178                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2179             }
2180         } else {
2181             // loading email into preview pane
2182             document.getElementById('_blank').innerHTML = loadingSprite;
2183
2184             // use cache if available
2185             if(SE.cache[compKey]) {
2186                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2187             } else {
2188                 AjaxObject.forceAbort = true;
2189                 // open in preview window
2190                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2191                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2192             }
2193         }
2194     },
2195
2196     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2197     {
2198         if(mboxStr.substring(0,7) == 'sugar::') {
2199             // display an email from Sugar
2200             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2201         } else {
2202             // display an email from an email server
2203             document.getElementById('emailUIAction').value = 'getSingleMessage';
2204         }
2205         document.getElementById('mbox').value = mbox;
2206         document.getElementById('ieId').value = ieId;
2207         document.getElementById('uid').value = uid;
2208
2209         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2210
2211         AjaxObject.forceAbort = true;
2212         AjaxObject.target = '_blank';
2213         AjaxObject.startRequest(callback, null);
2214     },
2215
2216     /**
2217      * Retrieves multiple emails for DetailView
2218      */
2219     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2220         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2221         SE.util.clearHiddenFieldValues('emailUIForm');
2222
2223         var mboxStr = new String(mbox);
2224
2225         uids = SE.util.cleanUids(uids);
2226
2227         if(mboxStr.substring(0,7) == 'sugar::') {
2228             // display an email from Sugar
2229             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2230             document.getElementById('uid').value = uids;
2231         } else {
2232             // display an email from an email server
2233             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2234             document.getElementById('mbox').value = mbox;
2235             document.getElementById('ieId').value = ieId;
2236             document.getElementById('uid').value = uids;
2237         }
2238
2239         var formObject = document.getElementById('emailUIForm');
2240         YAHOO.util.Connect.setForm(formObject);
2241
2242         AjaxObject.target = 'frameFlex';
2243         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2244
2245         if(setRead == true) {
2246             var c = uids.split(",");
2247             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2248         }
2249     },
2250
2251     /**
2252      * Makes async call to get QuickCreate form
2253      * Renders a modal edit view for a given module
2254      */
2255     quickCreate : function(module, ieId, uid, mailbox) {
2256         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2257
2258         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2259             get += "&sugarEmail=true";
2260         }
2261
2262         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2263     },
2264
2265     /**
2266      * Makes async call to save a quick create
2267      * @param bool
2268      */
2269     saveQuickCreate : function(action) {
2270         var qcd = SE.detailView.quickCreateDialog;
2271         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2272                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2273                 var theCallback = callbackQuickCreateSave;
2274                 var accountType = '&sugarEmail=true';
2275                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2276                    accountType = '&ieId=' + qcd.ieId;
2277                 }
2278
2279             if (action == 'reply') {
2280                    theCallback = callbackQuickCreateSaveAndReply;
2281                 } else if (action == true) {
2282                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2283                 }
2284                 formObject.action.value = 'EmailUIAjax';
2285                 YAHOO.util.Connect.setForm(formObject);
2286                 SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2287                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2288                                        accountType + '&mbox=' + qcd.mbox);
2289         }
2290     },
2291
2292     /**
2293      * Code to show/hide long list of email address in DetailView
2294      */
2295     showCroppedEmailList : function(el) {
2296         el.style.display = 'none';
2297         el.previousSibling.style.display = 'inline'
2298     },
2299     showFullEmailList : function(el) {
2300         el.style.display = 'none';
2301         el.nextSibling.style.display = 'inline';
2302     },
2303
2304     /**
2305      * Shows the QuickCreate overlay
2306      * @param string ieId
2307      * @param string uid
2308      * @param string mailbox
2309      */
2310     showQuickCreate : function(ieId, uid, mailbox) {
2311         var panelId = SE.util.getPanelId();
2312         var context = document.getElementById("quickCreateSpan" + panelId);
2313
2314         if (!SE.detailView.cqMenus)
2315                 SE.detailView.cqMenus = {};
2316
2317         if (SE.detailView.cqMenus[context])
2318                 SE.detailView.cqMenus[context].destroy();
2319
2320             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2321                 lazyload:true,
2322                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2323         });
2324
2325             for (var i=0; i < this.qcmodules.length; i++) {
2326             var module = this.qcmodules[i];
2327             menu.addItem({
2328                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2329                 modulename: module,
2330                 value: module,
2331                 onclick: { fn: function() {
2332                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2333                         }
2334                 }
2335             });
2336         }
2337
2338                 menu.render(document.body);
2339                 menu.show();
2340     },
2341
2342     /**
2343      * Displays the "View" submenu in the detailView
2344      * @param string ieId
2345      * @param string uid
2346      * @param string mailbox
2347      */
2348     showViewMenu : function(ieId, uid, mailbox) {
2349         var panelId = SE.util.getPanelId();
2350         var context = "btnEmailView" + panelId;
2351         if (!SE.detailView.viewMenus)
2352                 SE.detailView.viewMenus = {};
2353
2354         if (SE.detailView.viewMenus[context])
2355                 SE.detailView.viewMenus[context].destroy();
2356
2357             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2358                 lazyload:true,
2359                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2360                 clicktohide: true
2361         });
2362                 menu.addItems(
2363                                 (ieId == 'null' || ieId == null) ?
2364                         //No ieId - Sugar Email
2365                         [{
2366                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2367                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2368             }]
2369                         :
2370                         //IeID exists, on a remote server
2371                         [{
2372                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2373                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2374             },{
2375                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2376                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2377             }]
2378         );
2379                 menu.render(document.body);
2380                 menu.show();
2381
2382
2383         /*
2384         //#23108 jchi@07/17/2008
2385         menu.render('quickCreateSpan'+ panelId);*/
2386         //this.viewMenu = menu;
2387         //this.viewMenu.show(context);
2388     },
2389     /**
2390      * Makes async call to get an email's headers
2391      */
2392     viewHeaders : function(ieId, uid, mailbox) {
2393         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2394         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2395     },
2396
2397     /**
2398      * Makes async call to get a printable version
2399      */
2400     viewPrintable : function(ieId, uid, mailbox) {
2401         if(mailbox == 'sugar::Emails') {
2402             // display an email from Sugar
2403             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2404         } else {
2405             // display an email from an email server
2406             var emailUIAction = '&emailUIAction=getSingleMessage';
2407         }
2408
2409         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2410         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2411     },
2412
2413     /**
2414      * Makes async call to get an email's raw source
2415      */
2416     viewRaw : function(ieId, uid, mailbox) {
2417         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2418         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2419     },
2420
2421     /**
2422      * Display all email addresses in detailview.
2423      */
2424     displayAllAddrs : function(el) {
2425         el.style.display = 'none';
2426         Dom.getNextSibling(el).style.display = 'inline';
2427     }
2428 };
2429 ////    END SE.detailView
2430 ///////////////////////////////////////////////////////////////////////////////
2431
2432
2433
2434 ///////////////////////////////////////////////////////////////////////////////
2435 ////    SE.folders
2436 SE.folders = {
2437     contextMenuFocus : new Object(),
2438
2439     /**
2440      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2441      * SugarFolder ID - folder strings
2442      */
2443     _createFolderId : function(node) {
2444         var ret = '';
2445
2446         if(!node.data.id)
2447             return ret;
2448
2449         if(node.data.ieId) {
2450             /* we have a local Sugar folder */
2451             if(node.data.ieId == 'folder') {
2452                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2453             } else if(node.data.ieId.match(SE.reGUID)) {
2454                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2455             }
2456         } else {
2457             ret = node.data.id;
2458         }
2459
2460         return ret;
2461     },
2462
2463     addChildNode : function(parentNode, childNode) {
2464         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2465         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2466         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2467
2468         if(childNode.nodes) {
2469             if(childNode.nodes.length > 0) {
2470                 for(j=0; j<childNode.nodes.length; j++) {
2471                     var newChildNode = childNode.nodes[j];
2472                     this.addChildNode(node, newChildNode);
2473                 }
2474             }
2475         }
2476     },
2477
2478     /**
2479      * Builds and returns a new TreeView Node
2480      * @param string name
2481      * @param string id
2482      * @param int is_group
2483      * @return object
2484      */
2485     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2486         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2487
2488         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2489         node.expanded = expanded;
2490         node.data = new Object;
2491         node.data['id'] = id;
2492         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2493         node.data['label'] = name;
2494         node.data['ieId'] = 'folder';
2495         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2496         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2497         node.data['unseen'] = unseen;
2498         return node;
2499     },
2500
2501     /**
2502      * ensures that a new folder has a valid name
2503      */
2504     checkFolderName : function(name) {
2505         if(name == "")
2506             return false;
2507
2508         this.folderAdd(name);
2509     },
2510
2511     /**
2512      * Pings email servers for new email - forces refresh of folder pane
2513      */
2514     checkEmailAccounts : function() {
2515         this.checkEmailAccountsSilent(true);
2516     },
2517
2518     checkEmailAccountsSilent : function(showOverlay) {
2519         if(typeof(SE.folders.checkingMail)) {
2520             clearTimeout(SE.folders.checkingMail);
2521         }
2522
2523         // don't stomp an on-going request
2524         if(AjaxObject.currentRequestObject.conn == null) {
2525             if(showOverlay) {
2526                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW,
2527                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2528             }
2529             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2530         } else {
2531             // wait 5 secs before trying again.
2532             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2533         }
2534     },
2535
2536     /**
2537      * Starts check of all email Accounts using a loading bar for large POP accounts
2538      */
2539     startEmailAccountCheck : function() {
2540         // don't do two checks at the same time
2541        if(!AjaxObject.requestInProgress()) {
2542             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2543             SE.accounts.ieIds = SE.folders.getIeIds();
2544             if (SE.accounts.ieIds.length > 0) {
2545                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2546                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2547             } else {
2548                SUGAR.hideMessageBox();
2549             }
2550         } else {
2551             // wait 5 secs before trying again.
2552             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2553         }
2554     },
2555
2556     /**
2557      * Checks a single Account check based on passed ieId
2558      */
2559      startEmailCheckOneAccount : function(ieId, synch) {
2560             if (synch) {
2561                 synch = true;
2562             } else {
2563                 synch = false;
2564             }
2565             var mbox = "";
2566             var node = SE.clickedFolderNode;
2567             if (node && !synch) {
2568                 mbox = node.data.mbox;
2569             } // if
2570             SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2571             SE.accounts.ieIds = [ieId];
2572             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2573                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2574       },
2575
2576
2577     /**
2578      * Empties trash for subscribed accounts
2579      */
2580     emptyTrash : function() {
2581         SE.contextMenus.frameFoldersContextMenu.hide();
2582         SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2583         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2584     },
2585
2586     /**
2587      * Clears Cache files of the inboundemail account
2588      */
2589     clearCacheFiles : function(ieId) {
2590         SE.contextMenus.frameFoldersContextMenu.hide();
2591         SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2592         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2593     },
2594
2595
2596     /**
2597      * Returns an array of all the active accounts in the folder view
2598      */
2599     getIeIds : function() {
2600          var ieIds = [];
2601          var root = SE.tree.getRoot();
2602          for(i=0; i < root.children.length; i++) {
2603            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2604                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2605                ieIds.push(root.children[i].children[0].data.ieId);
2606            }
2607          }
2608          return ieIds;
2609      },
2610
2611     /**
2612      * loads folder lists in Settings->Folders
2613      */
2614     lazyLoadSettings : function() {
2615         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2616         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2617     },
2618
2619     /**
2620      * After the add new folder is done via folders tab on seetings, this function should get called
2621      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2622      */
2623     loadSettingFolder : function() {
2624         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2625         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2626     },
2627
2628     /**
2629      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2630      */
2631     removeSugarFolders : function() {
2632         var tree = SE.tree;
2633         var root = tree.getRoot();
2634         var folder = SE.util.findChildNode(root, "ieId", "folder");
2635         while(folder) {
2636             tree.removeNode(folder);
2637             folder = SE.util.findChildNode(root, "ieId", "folder");
2638         }
2639         if (!root.childrenRendered) {
2640                 root.childrenRendered = true;
2641         }
2642     },
2643
2644     rebuildFolders : function(silent) {
2645       if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2646        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2647     },
2648
2649
2650
2651     /**
2652      * Updates TreeView with Sugar Folders
2653      */
2654     setSugarFolders : function(delay) {
2655         this.removeSugarFolders();
2656                 //AjaxObject.forceAbort = true;
2657                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2658     },
2659
2660     /**
2661      * Takes async data object and creates the sugar folders in TreeView
2662      */
2663     setSugarFoldersEnd : function(o) {
2664         var root = SE.tree.getRoot();
2665         addChildNodes(root, {nodes: o});
2666         SE.accounts.renderTree();
2667         //If nothing is loaded in the grid, load "My Inbox"
2668         if (SE.grid.params.ieId == "undefined") {
2669                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2670         }
2671     },
2672
2673     startCheckTimer : function() {
2674         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2675             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2676
2677             if(typeof(SE.folders.checkTimer) != 'undefined') {
2678                 clearTimeout(SE.folders.checkTimer);
2679             }
2680
2681             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2682             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2683             {
2684                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2685                 SE.folders.checkEmailAccountsSilent(false);
2686             }
2687         }
2688     },
2689
2690     /**
2691      * makes an async call to save user preference and refresh folder view
2692      * @param object SELECT list object
2693      */
2694     setFolderSelection : function() {
2695         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2696
2697         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2698         var a_active_accnts = "";
2699         for(i=0;i<a_rs.length;i++)
2700         {
2701                 var t_record = a_rs[i];
2702                 var is_active = t_record.getData('is_active');
2703                 if(is_active)
2704                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2705         }
2706
2707         if(a_active_accnts == "")
2708                 a_active_accnts = "&ieIdShow[]=";
2709
2710         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2711
2712         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2713     },
2714
2715     /**
2716      * makes async call to save user preference for a given node's open state
2717      * @param object node YUI TextNode object
2718      */
2719     setOpenState : function(node) {
2720         SE.util.clearHiddenFieldValues('emailUIForm');
2721         var nodePath = node.data.id;
2722         var nodeParent = node.parent;
2723
2724         while(nodeParent != null) {
2725             // root node has no ID param
2726             if(nodeParent.data != null) {
2727                 nodePath = nodeParent.data.id + "::" + nodePath;
2728             }
2729
2730             var nodeParent = nodeParent.parent;
2731         }
2732
2733         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2734         document.getElementById('focusFolder').value = nodePath;
2735
2736         if(node.expanded == true) {
2737             document.getElementById('focusFolderOpen').value = 'open';
2738         } else {
2739             document.getElementById('focusFolderOpen').value = 'closed';
2740         }
2741
2742         var formObject = document.getElementById('emailUIForm');
2743         YAHOO.util.Connect.setForm(formObject);
2744
2745         AjaxObject.startRequest(null, null);
2746     },
2747
2748     getNodeFromMboxPath : function(path) {
2749         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2750         var a = YAHOO.lang.JSON.parse(path);
2751
2752         var node = tree.getRoot();
2753
2754         var i = 0;
2755         while(i < a.length) {
2756             node = this.getChildNodeFromLabel(node, a[i]);
2757             i++;
2758         }
2759
2760         return node;
2761     },
2762
2763     getChildNodeFromLabel : function(node, nodeLabel) {
2764         for(i=0; i<node.children.length; i++) {
2765             if(node.children[i].data.id == nodeLabel) {
2766                 return node.children[i];
2767             }
2768         }
2769     },
2770
2771     /**
2772      * returns the node that presumably under the user's right-click
2773      */
2774     getNodeFromContextMenuFocus : function() {
2775         //// get the target(parent) node
2776         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2777         var index = -1;
2778         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2779
2780         // filter local folders
2781         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2782             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2783                 if(target.id == '') {
2784                     target = target.parentNode;
2785                 } else {
2786                     break;
2787                 }
2788             }
2789         }
2790
2791         var targetNode = document.getElementById(target.id);
2792         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2793
2794         try {
2795             var matches = re.exec(targetNode.id);
2796         } catch(ex) {
2797             return document.getElementById(ygtvlabelel1);
2798         }
2799
2800         if(matches) {
2801             index = matches[1];
2802         } else {
2803             // usually parent node
2804             matches = re.exec(targetNode.parentNode.id);
2805
2806             if(matches) {
2807                 index = matches[1];
2808             }
2809         }
2810
2811         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2812         parentNode.expand();
2813
2814         return parentNode;
2815     },
2816
2817     /**
2818      * Decrements the Unread Email count in folder text
2819      * @param string ieId ID to look for
2820      * @param string mailbox name
2821      * @param count how many to decrement
2822      */
2823     decrementUnreadCount : function(ieId, mbox, count) {
2824
2825         if(mbox == null)
2826             return;
2827
2828         if(mbox.indexOf("sugar::") === 0) {
2829             var node = this.getNodeFromId(ieId);
2830         } else {
2831             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2832         }
2833         if(node) {
2834             var unseen = node.data.unseen;
2835             if(unseen > 0) {
2836                 var check = unseen - count;
2837                 var finalCount = (check >= 0) ? check : 0;
2838                 node.data.unseen = finalCount;
2839             }
2840             SE.accounts.renderTree();
2841         }
2842     },
2843
2844     /**
2845      * gets the TreeView node with a given ID/ieId
2846      * @param string id ID to look for
2847      * @return object Node
2848      */
2849     getNodeFromId : function(id) {
2850         SE.folders.focusNode = null;
2851         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2852             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2853                 SE.folders.focusNode = this;
2854                 return false;
2855             }
2856         }, null, [id]);
2857         return SE.folders.focusNode;
2858     },
2859
2860     /**
2861      * Uses ieId and mailbox to try to find a node in the tree
2862      */
2863     getNodeFromIeIdAndMailbox : function(id, mbox) {
2864                 SE.folders.focusNode = null;
2865         if (mbox == "sugar::Emails") {
2866                 mbox = id;
2867                 id = "folder";
2868         } // if
2869         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2870                 if (varsarray instanceof Array) {
2871             if (this.data.ieId && this.data.ieId == varsarray[0]
2872                     && this.data.mbox == varsarray[1]) {
2873                 SE.folders.focusNode = this;
2874                 return false;
2875             } }
2876                 else {
2877                         if (this.data.ieId && this.data.ieId == varsarray) {
2878                                 SE.folders.focusNode = this;
2879                     return false;
2880                         }
2881                 }
2882         }, null, [id, mbox]);
2883         return SE.folders.focusNode;
2884     },
2885
2886     unhighliteAll : function() {
2887         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2888     },
2889
2890     /**
2891      * Displays a short form
2892      */
2893     folderAdd : function() {
2894         SE.contextMenus.frameFoldersContextMenu.hide();
2895
2896         var node = SE.clickedFolderNode;
2897
2898         if(node != null && node.data) {
2899             SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2900                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2901                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2902         } else {
2903             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2904         }
2905     },
2906
2907     folderAddRegisterEnter : function() {
2908         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2909                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2910                                                                                                                         this.buttons[1].handler);
2911
2912                 this.enterKeyListener.enable();
2913     },
2914
2915     folderRemoveRegisterEnter : function() {
2916         this.enterKeyListener.disable();
2917     },
2918
2919     folderAddXmlCall : function(name) {
2920         if (trim(name) == "") {
2921                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2922                 return false;
2923         }
2924         name = escape(name);
2925         var post = '';
2926         var type = 'sugar';
2927
2928         var parentNode = SE.clickedFolderNode;
2929
2930         this.contextMenuFocus = parentNode;
2931
2932         if(parentNode.data.ieId) {
2933             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2934                 type = 'imap';
2935             }
2936         }
2937         if(type == 'imap') {
2938                 // make an IMAP folder
2939             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2940             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2941         } else if(type == 'sugar') {
2942             // make a Sugar folder
2943             if(SE.folders.isUniqueFolderName(name)) {
2944                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2945                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2946             } else {
2947                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2948                 SE.folders.folderAdd();
2949                 return;
2950             }
2951         } else {
2952             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2953         }
2954
2955         // hide add-folder diaglogue
2956         SE.e2overlay.hide();
2957     },
2958
2959     /**
2960      * Removes either an IMAP folder or a Sugar Folder
2961      */
2962     folderDelete : function() {
2963         SE.contextMenus.frameFoldersContextMenu.hide();
2964
2965         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2966             var post = '';
2967             var parentNode = SE.clickedFolderNode;
2968
2969             if(parentNode != null && parentNode.data) {
2970                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2971                     SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2972                     return;
2973                 }
2974
2975                 AjaxObject.target = 'frameFlex';
2976
2977                 if(parentNode.data.ieId != 'folder') {
2978                     // delete an IMAP folder
2979                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2980                 } else {
2981                     // delete a sugar folder
2982                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2983                 }
2984                 SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2985                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2986             } else {
2987                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2988             }
2989         }
2990     },
2991
2992     /**
2993      * Rename folder form
2994      */
2995      //EXT111
2996     folderRename : function() {
2997         SE.contextMenus.frameFoldersContextMenu.hide();
2998         var node = SE.clickedFolderNode;
2999
3000         if(node != null) {
3001             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
3002                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
3003                 return;
3004             }
3005
3006                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
3007                     app_strings.LBL_EMAIL_SETTINGS_NAME,
3008                     'prompt',
3009                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3010         } else {
3011             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3012         }
3013     },
3014
3015     /**
3016      * fills an Object with key-value pairs of available folders
3017      */
3018     getAvailableFoldersObject : function() {
3019         var ret = new Object();
3020         var tree = SE.tree.root;
3021
3022         if(tree.children) {
3023             for(var i=0; i<tree.children.length; i++) {
3024                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3025             }
3026         } else {
3027             ret['none'] = app_strings.LBL_NONE;
3028         }
3029
3030         return ret;
3031     },
3032
3033     /**
3034      * Fills in key-value pairs for dependent dropdowns
3035      * @param object ret Associative array
3036      * @param object node TreeView node in focus
3037      * @param string currentPath Built up path thus far
3038      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3039      */
3040     getFolderFromChild : function(ret, node, currentPath, spacer) {
3041         if(node.data != null && node.depth > 0) {
3042             /* handle visual separtors differentiating b/t mailserver and local */
3043             if(node.data.ieId && node.data.ieId == 'folder') {
3044                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3045             }
3046
3047             if(!ret.spacer0) {
3048                 ret['spacer0'] = spacer;
3049             } else if(ret.spacer0 != spacer) {
3050                 ret['spacer1'] = spacer
3051             }
3052
3053             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3054             var depthMarker = currentPath;
3055             var retIndex = SE.folders._createFolderId(node);
3056             ret[retIndex] = depthMarker + theLabel;
3057         }
3058
3059         if(node.children != null) {
3060             if(theLabel) {
3061                 currentPath += theLabel + "/";
3062             }
3063
3064             for(var i=0; i<node.children.length; i++) {
3065                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3066             }
3067         }
3068
3069         return ret;
3070     },
3071
3072     /**
3073      * Wrapper to refresh folders tree
3074      */
3075     getFolders : function() {
3076         SE.accounts.rebuildFolderList();
3077     },
3078
3079     /**
3080      * handles events around folder-rename input field changes
3081      * @param object YUI event object
3082      */
3083     handleEnter : function(e) {
3084         switch(e.browserEvent.type) {
3085             case 'click':
3086                 e.preventDefault(); // click in text field
3087             break;
3088
3089             case 'blur':
3090                 SE.folders.submitFolderRename(e);
3091             break;
3092
3093             case 'keypress':
3094                 var kc = e.browserEvent.keyCode;
3095                 switch(kc) {
3096                     case 13: // enter
3097                         e.preventDefault();
3098                         SE.folders.submitFolderRename(e);
3099                     break;
3100
3101                     case 27: // esc
3102                         e.preventDefault(e);
3103                         SE.folders.cancelFolderRename(e);
3104                     break;
3105                 }
3106             break;
3107         }
3108     },
3109     /**
3110     * Called when a node is clicked on in the folder tree
3111     * @param node, The node clicked on
3112     * @param e, The click event
3113     */
3114     handleClick : function(o) {
3115         var node = o.node;
3116         //If the click was on a sugar folder
3117         if (node.data.ieId == "folder") {
3118             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3119         }
3120         else {
3121             SE.listView.populateListFrame(node, node.data.ieId, false);
3122         }
3123        //eval(node.data.click);
3124        //debugger;
3125     },
3126
3127     /**
3128     * Called when a node is right-clicked on in the folder tree
3129     */
3130     handleRightClick : function(e) {
3131         YAHOO.util.Event.preventDefault(e);
3132                 //Get the Tree Node
3133                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3134                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3135
3136                 //If the click was on a sugar folder
3137         SE.clickedFolderNode = node;
3138         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3139                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3140                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3141                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3142                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3143                 menu.getItem(3).cfg.setProperty("disabled", false);
3144                 menu.getItem(4).cfg.setProperty("disabled", false);
3145                 menu.getItem(5).cfg.setProperty("disabled", false);
3146                 menu.getItem(6).cfg.setProperty("disabled", true);
3147                 //Group folder
3148                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3149                         menu.getItem(0).cfg.setProperty("disabled", true);
3150                         menu.getItem(1).cfg.setProperty("disabled", true);
3151                         menu.getItem(2).cfg.setProperty("disabled", true);
3152                         menu.getItem(3).cfg.setProperty("disabled", true);
3153                         menu.getItem(4).cfg.setProperty("disabled", true);
3154                 }
3155         if (node.data.protocol != null) {
3156                 menu.getItem(6).cfg.setProperty("disabled", false);
3157         }
3158                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3159                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3160                         //Sent or Draft folders
3161                         menu.getItem(3).cfg.setProperty("disabled", true);
3162                         menu.getItem(4).cfg.setProperty("disabled", true);
3163                         menu.getItem(5).cfg.setProperty("disabled", true);
3164                 }
3165
3166                 //For group with auto inbound, disable everything.
3167                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3168                 {
3169                     menu.getItem(0).cfg.setProperty("disabled", true);
3170                 menu.getItem(1).cfg.setProperty("disabled", true);
3171                 menu.getItem(2).cfg.setProperty("disabled", true);
3172                 menu.getItem(3).cfg.setProperty("disabled", true);
3173                 menu.getItem(4).cfg.setProperty("disabled", true);
3174                 menu.getItem(5).cfg.setProperty("disabled", true);
3175                 menu.getItem(6).cfg.setProperty("disabled", true);
3176                 }
3177
3178                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3179                 menu.show();
3180     },
3181
3182     /**
3183     * Called when a row is dropped on a node
3184     */
3185     handleDrop : function(rows, targetFolder) {
3186         var rowData = rows[0].getData();
3187         if (rowData.mbox != targetFolder.data.mbox) {
3188             var srcIeId = rowData.ieId;
3189             var srcFolder = rowData.mbox;
3190             var destIeId = targetFolder.data.ieId;
3191             var destFolder = targetFolder.data.mbox;
3192             var uids = [];
3193             for(var i=0; i<rows.length; i++) {
3194                 uids[i] = rows[i].getData().uid;
3195             }
3196             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3197         }
3198     },
3199
3200     /**
3201     * Called when something is dragged over a Folder Node
3202     */
3203     dragOver : function(dragObject) {
3204        return true;
3205     },
3206
3207     /**
3208      * Determines if a folder name is unique to the folder tree
3209      * @param string name
3210      */
3211     isUniqueFolderName : function(name) {
3212         uniqueFolder = true;
3213         var root = SE.tree.getRoot();
3214         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3215             if (this.attributes && this.attributes.ieId == "folder") {
3216                 if (this.attributes.text == name) {
3217                     uniqueFolder = false;
3218                     return false;
3219                 }
3220             }
3221         }, null, [name]);
3222         return uniqueFolder;
3223     },
3224
3225     /**
3226      * Makes async call to rename folder in focus
3227      * @param object e Event Object
3228      */
3229     submitFolderRename : function(newName) {
3230         if (trim(newName) == "") {
3231                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3232                 return false;
3233         }
3234                 newName = escape(newName);
3235         var node = SE.clickedFolderNode;
3236         var origName = node.data.text
3237         //Ignore no change
3238         if (newName == origName) {
3239             return true;
3240         }
3241         if(SE.folders.isUniqueFolderName(newName)) {
3242             SUGAR.showMessageBox(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3243             if (node.data.ieId == "folder") {
3244                 //Sugar Folder
3245                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3246             }
3247             else {
3248                 //IMAP folder or POP mailbox
3249                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3250                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3251                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3252             }
3253             return true;
3254         } else {
3255             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3256             return false;
3257         }
3258     },
3259
3260     moveFolder : function(folderId, parentFolderId) {
3261         if (folderId != parentFolderId)
3262         {
3263                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3264                     + folderId + "&newParentId=" + parentFolderId);
3265         }
3266     },
3267
3268     /**
3269      * makes async call to do a full synchronization of all accounts
3270      */
3271     synchronizeAccounts : function() {
3272         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3273             SUGAR.showMessageBoxModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3274             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3275         }
3276     },
3277
3278     /**
3279      * Updates user's folder subscriptsion (Sugar only)
3280      * @param object SELECT DOM object in focus
3281      * @param string type of Folder selection
3282      */
3283     updateSubscriptions : function() {
3284         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3285
3286         var active = "";
3287
3288         select = document.getElementById('userFolders');
3289
3290         for(i=0; i<select.options.length; i++) {
3291             var opt = select.options[i];
3292              if(opt.selected && opt.value != "") {
3293                  if(active != "") {
3294                      active += "::";
3295                  }
3296                  active += opt.value;
3297              }
3298         }
3299
3300         //Add the group folder ids.
3301         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3302         for(i=0; i<group_folders.length; i++)
3303         {
3304             active += ("::" + group_folders[i]);
3305         }
3306
3307         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3308     },
3309     /**
3310      * Updates user's group folder subscriptsion (Sugar only)
3311      * @param ieID The group folder to add to the tree view
3312      */
3313     retrieveGroupFolderSubscriptions : function() {
3314
3315         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3316         var activeGroupFolders = "";
3317         var activeGroupIds = [];
3318         for(i=0;i<a_rs.length;i++)
3319         {
3320                 var t_record = a_rs[i];
3321                 var is_active = t_record.getData('is_active');
3322                 var isGroupFolder = t_record.getData('has_groupfolder');
3323                 var ieID = t_record.getData('id');
3324                 if( isGroupFolder )
3325                 {
3326                     if(is_active)
3327                       activeGroupIds.push(ieID);
3328                 }
3329         }
3330
3331         return activeGroupIds;
3332     }
3333
3334 };
3335
3336 SE.folders.checkEmail2 = function() {
3337     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3338 }
3339 ////    END FOLDERS OBJECT
3340 ///////////////////////////////////////////////////////////////////////////////
3341
3342
3343 ///////////////////////////////////////////////////////////////////////////////
3344 ////    SE.keys
3345 /**
3346  * Keypress Event capture and processing
3347  */
3348 SE.keys = {
3349     overall : function(e) {
3350         switch(e.charCode) {
3351             case 119: // "w"
3352                 if(e.ctrlKey || e.altKey) {
3353                     var focusRegion = SE.innerLayout.regions.center;
3354                     if(focusRegion.activePanel.closable == true) {
3355                         focusRegion.remove(focusRegion.activePanel);
3356                     }
3357                 }
3358             break;
3359         }
3360     }
3361 };
3362 ////    END SE.keys
3363 ///////////////////////////////////////////////////////////////////////////////
3364
3365
3366 ///////////////////////////////////////////////////////////////////////////////
3367 ////    SE.listView
3368 /**
3369  * ListView object methods and attributes
3370  */
3371 SE.listView = {
3372     currentRowId : -1,
3373
3374     /**
3375      * Fills the ListView pane with detected messages.
3376      */
3377     populateListFrame : function(node, ieId, forceRefresh) {
3378         SE.innerLayout.selectTab(0);
3379                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3380
3381         Dom.get('_blank').innerHTML = "";
3382         SE.grid.params['emailUIAction'] = 'getMessageList';
3383         SE.grid.params['mbox'] = node.data.mbox;
3384         SE.grid.params['ieId'] = ieId;
3385         forcePreview = true; // loads the preview pane with first item in grid
3386         SE.listView.refreshGrid();
3387     },
3388
3389     /**
3390      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3391      */
3392     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3393         SE.innerLayout.selectTab(0);
3394         Dom.get('_blank').innerHTML = "";
3395         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3396         SE.grid.params['ieId'] = node.data.id;
3397         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3398         SE.listView.refreshGrid();
3399     },
3400
3401     /**Mac
3402      * Sets sort order as user preference
3403      * @param
3404      */
3405     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3406         ieId = ieIdPassed;
3407         ieName = ieNamePassed;
3408         focusFolder = focusFolderPassed;
3409
3410         SE.util.clearHiddenFieldValues('emailUIForm');
3411         var previousSort = document.getElementById('sortBy').value;
3412
3413         document.getElementById('sortBy').value = sortBy;
3414         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3415         document.getElementById('focusFolder').value = focusFolder;
3416         document.getElementById('ieId').value = ieId;
3417
3418         if(sortBy == previousSort) {
3419             document.getElementById('reverse').value = '1';
3420         }
3421
3422         var formObject = document.getElementById('emailUIForm');
3423         YAHOO.util.Connect.setForm(formObject);
3424
3425         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3426     },
3427
3428
3429     /**
3430      * Enables click/arrow select of grid items which then populate the preview pane.
3431      */
3432     selectFirstRow : function() {
3433         SE.grid.selModel.selectFirstRow();
3434     },
3435
3436     selectLastRow : function() {
3437         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3438     },
3439
3440     setEmailListStyles : function() {
3441         SE.listView.boldUnreadRows();
3442         return;
3443         var ds = SE.grid.getStore();
3444         if (SE.grid.getSelections().length == 0) {
3445             document.getElementById('_blank').innerHTML = '';
3446         }
3447
3448         var acctMbox = '';
3449         if(typeof(ds.baseParams.mbox) != 'undefined') {
3450             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3451             var cm = SE.grid.getColumnModel();
3452             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3453                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3454                 //SE.grid.render();
3455             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3456                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3457                 //SE.grid.render();
3458             }
3459         }
3460         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3461         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3462
3463         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3464             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3465             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3466             if (node) node.data.unseen = unread;
3467         }
3468         SE.accounts.renderTree();
3469
3470
3471         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3472         if(forcePreview && ds.totalCount > 0) {
3473             SE.detailView.getEmailPreview();
3474             forcePreview = false;
3475         }
3476     },
3477
3478     /**
3479      * Removes a row if found via its UID
3480      */
3481     removeRowByUid : function(uid) {
3482         uid = new String(uid);
3483         uids = uid.split(',');
3484         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3485
3486         for(j=0; j<uids.length; j++) {
3487             var theUid = uids[j];
3488             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3489                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3490                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3491                 }
3492             } // for
3493         }
3494     },
3495
3496     displaySelectedEmails : function(rows) {
3497         var dm = SE.grid.getDataModel();
3498         var uids = '';
3499
3500         for(i=0; i<rows.length; i++) {
3501             var rowIndex = rows[i].rowIndex;
3502             var metadata = dm.data[rowIndex];
3503
3504             if(uids != "") {
3505                 uids += ",";
3506             }
3507             uids += metadata[5];
3508
3509             // unbold unseen email
3510             this.unboldRow(rowIndex);
3511         }
3512
3513         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3514     },
3515
3516     /**
3517      * exception handler for data load failures
3518      */
3519     loadException : function(dataModel, ex, response) {
3520         //debugger;
3521     },
3522
3523     /**
3524      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3525      * @param string sourceIeId Email's source I-E id
3526      * @param string sourceFolder Email's current folder
3527      * @param destinationIeId Destination I-E id
3528      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3529      *
3530      * @param array emailUids Array of email's UIDs
3531      */
3532     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3533         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3534             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3535         } else {
3536             SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3537             // remove rows from visibility
3538             for(row in selectedRows) {
3539                 //SE.grid.getStore().remove(row);
3540             }
3541
3542             var baseUrl =    '&sourceIeId=' + sourceIeId +
3543                             '&sourceFolder=' + sourceFolder +
3544                             '&destinationIeId=' + destinationIeId +
3545                             '&destinationFolder=' + destinationFolder;
3546             var uids = '';
3547
3548             for(i=0; i<emailUids.length; i++) {
3549                 if(uids != '') {
3550                     uids += app_strings.LBL_EMAIL_DELIMITER;
3551                 }
3552                 uids += emailUids[i];
3553             }
3554             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3555                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3556             } else {
3557                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3558             }
3559         }
3560     },
3561
3562     /**
3563      * Unbolds text in the grid view to denote read status
3564      */
3565     markRead : function(index, record) {
3566         // unbold unseen email
3567         var row = SE.grid.getRecord(record);
3568         row.getData().seen = 1;
3569         SE.grid.getTrEl(record).style.fontWeight = "normal";
3570     },
3571
3572     /**
3573      * grid row output, bolding unread emails
3574      */
3575     boldUnreadRows : function() {
3576         // bold unread emails
3577         var trEl = SE.grid.getFirstTrEl();
3578         while(trEl != null) {
3579                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3580                         trEl.style.fontWeight = "bold";
3581                 else
3582                         trEl.style.fontWeight = "";
3583                 trEl = SE.grid.getNextTrEl(trEl);
3584         }
3585     },
3586
3587     /**
3588      * Show preview for an email if 1 and only 1 is selected
3589      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3590      */
3591     handleRowSelect : function(e) {
3592         if(e.selectedRows.length == 1) {
3593             SE.detailView.getEmailPreview();
3594         }
3595     },
3596
3597     handleDrop : function(e, dd, targetId, e2) {
3598         switch(targetId) {
3599             case 'htmleditordiv':
3600                 var rows = SE.grid.getSelectedRows();
3601                 if(rows.length > 0) {
3602                     SE.listView.displaySelectedEmails(rows);
3603                 }
3604             break;
3605
3606             default:
3607                 var targetElId = new String(targetId);
3608                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3609                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3610                 var dm = SE.grid.getDataModel();
3611                 var emailUids = new Array();
3612                 var destinationIeId = targetNode.data.ieId;
3613                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3614
3615
3616                 var rows = SE.grid.getSelectedRows();
3617                 // iterate through dragged rows
3618                 for(i=0; i<rows.length; i++) {
3619                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3620                     var rowIndex = rows[i].rowIndex;
3621                     var dataModelRow = dm.data[rowIndex];
3622                     var sourceIeId = dataModelRow[7];
3623                     var sourceFolder = dataModelRow[6];
3624                     emailUids[i] = dataModelRow[5];
3625                 }
3626
3627                 // event wrapped call - need FQ
3628                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3629                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3630             break;
3631         }
3632     },
3633
3634     /**
3635      * Hack-around to get double-click and single clicks to work on the grid
3636      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3637      */
3638     handleClick : function(o) {
3639         SUGAR.email2.grid.clearTextSelection();
3640
3641         var el = SUGAR.email2.grid.getSelectedRows();
3642
3643         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3644         if ( el.length == 1)
3645         {
3646            var rowId = el[0];
3647            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3648            SUGAR.email2.listView.currentRowIndex = rowId;
3649            clearTimeout(SUGAR.email2.detailView.previewTimer);
3650            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3651         }
3652     },
3653
3654     /**
3655      * Custom handler for double-click/enter
3656      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3657      */
3658     getEmail : function(e) {
3659         var rows = SE.grid.getSelectedRows();
3660         var row = SE.grid.getRecord(rows[0]).getData();
3661
3662         clearTimeout(SE.detailView.previewTimer);
3663         document.getElementById("_blank").innerHTML = "";
3664
3665         if(row.type != "draft") {
3666             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3667         } else {
3668             // circumventing yui-ext tab generation, let callback handler build new view
3669             SE.util.clearHiddenFieldValues('emailUIForm');
3670             //function(uid, mbox, ieId, setRead, destination) {
3671             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3672             document.getElementById('uid').value = row.uid; // uid;
3673             document.getElementById('mbox').value = row.mbox; // mbox;
3674             document.getElementById('ieId').value = row.ieId; // ieId;
3675
3676             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3677             AjaxObject.target = '_blank';
3678             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3679         }
3680     },
3681
3682     /**
3683      * Retrieves a row if found via its UID
3684      * @param string
3685      * @return int
3686      */
3687     getRowIndexByUid : function(uid) {
3688         uid = new String(uid);
3689         uids = uid.split(',');
3690
3691         for(j=0; j<uids.length; j++) {
3692             var theUid = uids[j];
3693
3694             for(i=0; i<SE.grid.getStore().data.length; i++) {
3695                 if(SE.grid.getStore().data[i].id == theUid) {
3696                     return i;
3697                 }
3698             }
3699         }
3700     },
3701
3702     /**
3703      * Returns the UID's of the seleted rows
3704      *
3705      */
3706      getUidsFromSelection : function() {
3707          var rows = SE.grid.getSelectedRows();
3708          var uids = [];
3709          /* iterate through available rows JIC a row is deleted - use first available */
3710          for(var i=0; i<rows.length; i++) {
3711                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3712          }
3713          return uids;
3714      },
3715
3716     refreshGrid : function() {
3717         SE.grid.getDataSource().sendRequest(
3718             SUGAR.util.paramsToUrl(SE.grid.params),
3719                 SE.grid.onDataReturnInitializeTable,
3720                 SE.grid
3721         );
3722     }
3723
3724 };
3725 ////    END SE.listView
3726 ///////////////////////////////////////////////////////////////////////////////
3727
3728 ///////////////////////////////////////////////////////////////////////////////
3729 ////    SEARCH
3730 SE.search = {
3731     /**
3732      * sends search criteria
3733      * @param reference element search field
3734      */
3735     search : function(el) {
3736         var searchCriteria = new String(el.value);
3737
3738         if(searchCriteria == '') {
3739             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3740             return false;
3741         }
3742
3743         var safeCriteria = escape(searchCriteria);
3744
3745         var accountListSearch = document.getElementById('accountListSearch');
3746
3747         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3748         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3749         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3750         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3751         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3752
3753     },
3754
3755     /**
3756      * sends advanced search criteria
3757      */
3758     searchAdvanced : function() {
3759         var formObject = document.getElementById('advancedSearchForm');
3760         var search = false;
3761
3762         //Set assigned user id to blank if name is not present.
3763         if (formObject.elements['assigned_user_name'].value == "")
3764             formObject.elements['assigned_user_id'].value = "";
3765
3766         for(i=0; i<formObject.elements.length; i++) {
3767             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3768                 search = true;
3769             }
3770             if(formObject.elements[i].type == 'text') {
3771                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3772             }
3773             if(formObject.elements[i].type == 'hidden') {
3774                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3775             }
3776              if(formObject.elements[i].type == 'select-one') {
3777                 var el = formObject.elements[i];
3778                 var v = el.options[el.selectedIndex].value;
3779
3780                 if(v != "")
3781                     SE.grid.params[el.name] = v;
3782                 else
3783                 {
3784                     //Clear previous search results if necessary
3785                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3786                         delete SE.grid.params[el.name]
3787                 }
3788              }
3789         }
3790
3791         if (search)
3792         {
3793             if(! this.validateSearchFormInput() )
3794                 return;
3795
3796                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3797                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3798                 var accountListSearch = document.getElementById('accountListSearch');
3799                 SE.listView.refreshGrid();
3800         } else {
3801             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3802         }
3803     },
3804
3805     /**
3806     *  Validates the search form inputs to ensure all parameters are valid
3807     *  @return bool
3808     */
3809     validateSearchFormInput: function()
3810     {
3811         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3812         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3813         var dateCheck = check_form('advancedSearchForm');
3814
3815         //If the parent type is selected ensure the user selected a parent_id.
3816         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3817             return true;
3818         else
3819             return false;
3820     },
3821     /**
3822     *   Toggles the advanced options, either hidding or showing the selection.
3823     */
3824     toggleAdvancedOptions: function()
3825     {
3826         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3827
3828         for(var i=0;i<el.length;i++)
3829         {
3830             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3831                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3832             else
3833                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3834         }
3835     },
3836     /**
3837      * clears adv search form fields
3838      */
3839     searchClearAdvanced : function() {
3840         var form = document.getElementById('advancedSearchForm');
3841
3842         for(i=0; i<form.elements.length; i++) {
3843             if(form.elements[i].type != 'button') {
3844                 form.elements[i].value = '';
3845             }
3846         }
3847     }
3848 };
3849 ////    END SE.search
3850 //////////////////////////////////////////////////////////////////////////////
3851
3852
3853 //////////////////////////////////////////////////////////////////////////////
3854 ////    SE.settings
3855 SE.settings = {
3856     /******************************************************************************
3857      * USER SIGNATURES calls stolen from Users module
3858      *****************************************************************************/
3859     createSignature : function(record, the_user_id) {
3860         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3861         if(record != "") {
3862             URL += "&record="+record;
3863         }
3864         if(the_user_id != "") {
3865             URL += "&the_user_id="+the_user_id;
3866         }
3867         var windowName = 'email_signature';
3868         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3869
3870         var win = window.open(URL, windowName, windowFeatures);
3871         if(win && win.focus) {
3872             // put the focus on the popup if the browser supports the focus() method
3873             win.focus();
3874         }
3875     },
3876
3877     deleteSignature : function() {
3878         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3879             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3880                 var singature_id = document.getElementById('signature_id').value;
3881                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3882         } // if
3883     },
3884
3885     saveOptionsGeneral :  function(displayMessage) {
3886         var formObject = document.getElementById('formEmailSettingsGeneral');
3887         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3888                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3889                 return false;
3890         } // if
3891         YAHOO.util.Connect.setForm(formObject);
3892         SE.composeLayout.emailTemplates = null;
3893
3894         AjaxObject.target = 'frameFlex';
3895         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3896
3897         if(displayMessage)
3898             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3899
3900         SE.settings.settingsDialog.hide();
3901     },
3902
3903     /**
3904      * Shows settings container screen
3905      */
3906     showSettings : function() {
3907         if(!SE.settings.settingsDialog) {
3908                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3909                 modal:true,
3910                 visible:false,
3911                 fixedcenter:true,
3912                 draggable: false,
3913                 width:"800px",
3914                                 constraintoviewport: true
3915             });
3916                         dlg.showEvent.subscribe( function (){
3917                                 var el = this.element;
3918                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3919                 if (this.header && el && viewH - 50 < el.clientHeight) {
3920                     var body = this.header.nextElementSibling;
3921                                         body.style.overflow = "auto";
3922                     body.style.height = (viewH - 50) + "px";
3923                 }
3924             }, dlg);
3925                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3926                 dlg.setBody('<div id="settingsTabDiv"/>');
3927                 dlg.beforeRenderEvent.subscribe(function() {
3928                         var dd = new YAHOO.util.DDProxy(dlg.element);
3929                         dd.setHandleElId(dlg.header);
3930                         dd.on('endDragEvent', function() {
3931                                 dlg.show();
3932                         });
3933                 }, dlg, true);
3934                 dlg.render();
3935
3936                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3937                         var tabContent = Dom.get("tab_general");
3938                 tp.addTab(new YAHOO.widget.Tab({
3939                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3940                                 scroll : true,
3941                                 content :  tabContent.innerHTML,
3942                                 id : "generalSettings",
3943                                 active : true
3944                         }));
3945                 tabContent.parentNode.removeChild(tabContent);
3946                 tabContent = Dom.get("tab_accounts");
3947                 var accountTab = new YAHOO.widget.Tab({
3948                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3949                                 scroll : true,
3950                                 content : tabContent.innerHTML,
3951                                 id : "accountSettings"
3952                         });
3953                 tp.addTab(accountTab);
3954                 tabContent.parentNode.removeChild(tabContent);
3955
3956                         tp.appendTo(dlg.body);
3957         }
3958
3959         SE.settings.settingsDialog.show();
3960         SE.folders.lazyLoadSettings();
3961         SE.accounts.lazyLoad();
3962     },
3963
3964
3965     lazyLoadRules : function() {
3966         if(false/*!SE.settings.rules*/) {
3967             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3968         }
3969
3970     }
3971 };
3972 ////    END SE.settings
3973 ///////////////////////////////////////////////////////////////////////////////
3974 })();
3975
3976 /******************************************************************************
3977  * UTILITIES
3978  *****************************************************************************/
3979 function removeHiddenNodes(nodes, grid) {
3980     var el;
3981         for(var i = nodes.length - 1; i > -1; i--) {
3982         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3983         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3984                 nodes.splice(i,1);
3985        }
3986     }
3987 }
3988
3989 function strpad(val) {
3990     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3991 };
3992
3993 function refreshTodos() {
3994     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3995     AjaxObject.target = 'todo';
3996     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3997 };
3998
3999 /******************************************************************************
4000  * MUST STAY IN GLOBAL NAMESPACE
4001  *****************************************************************************/
4002 function refresh_signature_list(signature_id, signature_name) {
4003     var field=document.getElementById('signature_id');
4004     var bfound=0;
4005     for (var i=0; i < field.options.length; i++) {
4006             if (field.options[i].value == signature_id) {
4007                 if (field.options[i].selected==false) {
4008                     field.options[i].selected=true;
4009                 }
4010                 bfound=1;
4011             }
4012     }
4013     //add item to selection list.
4014     if (bfound == 0) {
4015         var newElement=document.createElement('option');
4016         newElement.text=signature_name;
4017         newElement.value=signature_id;
4018         field.options.add(newElement);
4019         newElement.selected=true;
4020     }
4021
4022     //enable the edit button.
4023     var field1=document.getElementById('edit_sig');
4024     field1.style.visibility="inherit";
4025     var deleteButt = document.getElementById('delete_sig');
4026     deleteButt.style.visibility="inherit";
4027 };
4028
4029 function setDefaultSigId(id) {
4030     var checkbox = document.getElementById("signature_default");
4031     var default_sig = document.getElementById("signatureDefault");
4032
4033     if(checkbox.checked) {
4034         default_sig.value = id;
4035     } else {
4036         default_sig.value = "";
4037     }
4038 };
4039
4040 function setSigEditButtonVisibility() {
4041     var field = document.getElementById('signature_id');
4042     var editButt = document.getElementById('edit_sig');
4043     var deleteButt = document.getElementById('delete_sig');
4044     if(field.value != '') {
4045         editButt.style.visibility = "inherit";
4046         deleteButt.style.visibility = "inherit";
4047     } else {
4048         editButt.style.visibility = "hidden";
4049         deleteButt.style.visibility = "hidden";
4050     }
4051 }// End of File modules/Emails/javascript/EmailUI.js
4052                                 
4053 /*********************************************************************************
4054  * SugarCRM Community Edition is a customer relationship management program developed by
4055  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4056  * 
4057  * This program is free software; you can redistribute it and/or modify it under
4058  * the terms of the GNU Affero General Public License version 3 as published by the
4059  * Free Software Foundation with the addition of the following permission added
4060  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4061  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4062  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4063  * 
4064  * This program is distributed in the hope that it will be useful, but WITHOUT
4065  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4066  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4067  * details.
4068  * 
4069  * You should have received a copy of the GNU Affero General Public License along with
4070  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4071  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4072  * 02110-1301 USA.
4073  * 
4074  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4075  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4076  * 
4077  * The interactive user interfaces in modified source and object code versions
4078  * of this program must display Appropriate Legal Notices, as required under
4079  * Section 5 of the GNU Affero General Public License version 3.
4080  * 
4081  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4082  * these Appropriate Legal Notices must retain the display of the "Powered by
4083  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4084  * technical reasons, the Appropriate Legal Notices must display the words
4085  * "Powered by SugarCRM".
4086  ********************************************************************************/
4087
4088  (function() {
4089         var sw = YAHOO.SUGAR,
4090                 Event = YAHOO.util.Event,
4091                 Connect = YAHOO.util.Connect,
4092             Dom = YAHOO.util.Dom
4093             SE = SUGAR.email2;
4094
4095 ///////////////////////////////////////////////////////////////////////////////
4096 ////    ADDRESS BOOK
4097 SE.addressBook = {
4098     _contactCache : new Array(), // cache of contacts
4099     _dd : new Array(), // filtered list, same format as _contactCache
4100     _ddLists : new Array(), // list of Lists
4101     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4102     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4103     clickBubble : true, // hack to get around onclick event bubbling
4104         relatedBeanId : '',
4105         relatedBeanType : '',
4106         idx : 0,
4107
4108     itemSpacing : 'white-space:nowrap; padding:2px;',
4109     reGUID : SE.reGUID,
4110
4111
4112
4113     /**
4114     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4115     */
4116     initFixForDatatableSort: function () {
4117         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4118         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4119             var oColumn = this._oColumnSet.getColumn(column);
4120
4121             if(!oColumn) {
4122                 // Validate TD element
4123                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4124                 if(elCell) {
4125                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4126                 }
4127                 // Validate TH element
4128                 else {
4129                     elCell = this.getThEl(column);
4130                     if(elCell) {
4131                         // Find by TH el ID
4132                         var allColumns = this._oColumnSet.flat;
4133                         for(var i=0, len=allColumns.length; i<len; i++) {
4134                             if(allColumns[i].getThEl().id === elCell.id) {
4135                                 oColumn = allColumns[i];
4136                             }
4137                         }
4138                     }
4139                 }
4140             }
4141
4142             return oColumn;
4143         };
4144     },
4145
4146     cancelEdit : function() {
4147         if(this.editContactDialog)
4148             this.editContactDialog.hide();
4149         if(this.editMailingListDialog)
4150             this.editMailingListDialog.hide();
4151     },
4152
4153     /**
4154      * Clears filter form
4155      */
4156     clear : function() {
4157         var t = document.getElementById('contactsFilter');
4158         t.value = '';
4159         this.filter(t);
4160     },
4161
4162     /**
4163      * handle context-menu Compose-to call
4164      * @param string type 'contacts' or 'lists'
4165      */
4166     composeTo : function(type, waited) {
4167         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4168         if (activePanel.substring(0, 10) != "composeTab") {
4169             SE.composeLayout.c0_composeNewEmail();
4170             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4171                 SE.contextMenus.contactsContextMenu.hide();
4172             return;
4173         }
4174         var idx = activePanel.substring(10);
4175         var rows = [ ];
4176         var id = '';
4177         // determine if we have a selection to work with
4178         if(type == 'contacts') {
4179             var ids = SE.contactView.getSelectedRows();
4180             for (var i in ids) {
4181                 rows[i] = SE.contactView.getRecord(ids[i]);
4182             }
4183             removeHiddenNodes(rows, SE.contactView);
4184         }
4185                 else { return; }
4186
4187         if(rows.length > 0) {
4188             SE.composeLayout.handleDrop(
4189                 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4190                 null, rows, 'addressTO' + idx );
4191         } else {
4192             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4193         }
4194     },
4195
4196     editContact : function() {
4197         SE.contextMenus.contactsContextMenu.hide();
4198         var element = SE.contactView.getSelectedNodes()[0];
4199         var elementId = "";
4200         if (element.className.indexOf('address-contact') > -1) {
4201             elementId = element.id;
4202         } else if (element.className.indexOf('address-exp-contact') > -1) {
4203             elementId = element.id.substring(2);
4204         }
4205     },
4206
4207
4208     /**
4209      * Filters contact entries based on user input
4210      */
4211     filter : function(inputEl) {
4212         var ret = new Object();
4213         var re = new RegExp(inputEl.value, "gi");
4214
4215         for(var i in this._contactCache) {
4216             if(this._contactCache[i].name.match(re)) {
4217                 ret[i] = this._contactCache[i];
4218             }
4219         }
4220
4221         this.buildContactList(ret);
4222     },
4223
4224     fullForm : function(id, module) {
4225         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4226     },
4227
4228     /**
4229      * returns a formatted email address from the addressBook cache
4230      */
4231     getFormattedAddress : function(id) {
4232         var o = this._contactCache[id];
4233         var primaryEmail = '';
4234
4235         for(var i=0; i<o.email.length; i++) {
4236             var currentEmail = o.email[i].email_address;
4237
4238             if(o.email[i].primary_address == 1) {
4239                 primaryEmail = o.email[i].email_address;
4240             }
4241         }
4242
4243         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4244         var name = new String(o.name);
4245         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4246         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4247
4248         return ret;
4249     },
4250
4251     /**
4252      * Sets up async call to query for matching contacts, users, etc.
4253      */
4254     searchContacts : function() {
4255         var fn = document.getElementById('input_searchField').value;
4256         var pe = document.getElementById('input_searchPerson').value;
4257
4258         var rb = document.getElementById('hasRelatedBean').checked;
4259         if (rb) {
4260                         var idx = this.idx;
4261                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4262                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4263                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4264                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4265         } else {
4266                 this.addressBookDataModel.params['related_bean_id'] = '';
4267         }
4268
4269         this.addressBookDataModel.params['search_field'] = fn;
4270         this.addressBookDataModel.params['person'] = pe;
4271         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4272         this.grid._oDataSource = this.addressBookDataModel;
4273         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4274     },
4275
4276     /**
4277      * Clear Search Crieteria For Addressbook
4278      */
4279     clearAddressBookSearch : function() {
4280         document.getElementById('input_searchField').value = "";
4281         document.getElementById('input_searchPerson').selectedIndex = 0;
4282     },
4283
4284     /**
4285      * Opens modal select window to add contacts to addressbook
4286      */
4287     selectContactsDialogue : function(destId) {
4288         if(!this.contactsDialogue) {
4289                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4290                 modal:true,
4291                 visible:false,
4292                 draggable: false,
4293                 constraintoviewport: true,
4294                 width   : 980,
4295                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4296                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4297             });
4298                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4299
4300                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4301                 dlg.setBody(body.innerHTML);
4302                 dlg.renderEvent.subscribe(function() {
4303                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4304                 if (iev && !SUGAR.isIE) {
4305                         this.body.style.width = "950px";
4306                 }
4307             }, dlg);
4308
4309
4310                 dlg.beforeRenderEvent.subscribe(function() {
4311                         var dd = new YAHOO.util.DDProxy(dlg.element);
4312                         dd.setHandleElId(dlg.header);
4313                         dd.on('endDragEvent', function() {
4314                                 dlg.show();
4315                         });
4316                 }, dlg, true);
4317                 dlg.render();
4318
4319                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4320
4321                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4322                 tp.addTab(new YAHOO.widget.Tab({
4323                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4324                                 scroll : true,
4325                                 content : tabContent.innerHTML,
4326                                 id : "addressSearchTab",
4327                                 active : true
4328                         }));
4329
4330                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4331                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4332                         if (e.keyCode == 13) {
4333                                 YAHOO.util.Event.stopEvent(e);
4334                                 SUGAR.email2.addressBook.searchContacts();
4335                         }
4336                 });
4337
4338                 this.contactsDialogue.render();
4339                 dlg.center();
4340         }
4341         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4342         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4343             var idx = 0;
4344         else
4345         {
4346             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4347             var idx = activePanel.substring(10);
4348         }
4349         SE.addressBook.idx = idx;
4350
4351                 var relatedBeanId;
4352         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4353                 document.getElementById('relatedBeanColumn').style.display = '';
4354                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4355                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4356                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4357                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4358                         SE.addressBook.relatedBeanType = relatedBeanType;
4359             } else {
4360                 document.getElementById('relatedBeanColumn').style.display = 'none';
4361                 document.getElementById('hasRelatedBean').checked = false;
4362             }
4363
4364             if (!SE.addressBook.grid)
4365             {
4366                 if (hasRelatedBeanId) {
4367                         document.getElementById('hasRelatedBean').checked = true;
4368                 }
4369                 AddressSearchGridInit();
4370                         SE.addressBook.relatedBeanId = relatedBeanId;
4371             }
4372             else
4373             {
4374                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4375                 {
4376                         SE.addressBook.relatedBeanId = relatedBeanId;
4377                         document.getElementById('hasRelatedBean').checked = true;
4378                 }
4379                 if (document.getElementById('hasRelatedBean').checked == true)
4380                 {
4381                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4382                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4383                 } else {
4384                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4385                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4386                 }
4387                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4388                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4389                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4390             }
4391
4392             //Remove any lingering rows in the result set table if the module was closed.
4393             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4394             //Repopulate
4395             SE.addressBook.populateResulstTableEmailAddresses();
4396
4397         this.contactsDialogue.show();
4398     },
4399     /**
4400     *  Clear all email addresses from result table.
4401     *
4402     */
4403     clearAllEmailAddressFieldsFromResultTable: function () {
4404         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4405         //Unhighlight any rows currently selected if the emails were cleared.
4406         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4407         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4408     },
4409     /**
4410     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4411     *  results table.  This function is called when the address book is displayed.
4412     */
4413     populateResulstTableEmailAddresses: function () {
4414
4415         var idx = SE.addressBook.idx;
4416         var emailFields = ['to','cc','bcc'];
4417
4418         for(var k=0;k<emailFields.length;k++)
4419         {
4420             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4421             var allEmails = document.getElementById(elKey).value;
4422             if(allEmails == '')
4423                 continue;
4424
4425             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4426
4427                 for (var i=0; i<formatedEmails.length; i++)
4428                 {
4429                     var t_name = formatedEmails[i].name;
4430                     var t_emailAddr = formatedEmails[i].email_address;
4431                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4432                     if(t_name == '')
4433                         t_name = displayEmail = t_emailAddr;
4434
4435                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4436                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4437                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4438                 }
4439         }
4440     },
4441
4442     /**
4443     * Checks all entries in the result table against a particular email address, returning true
4444     * if the email address is found, false otherwise.
4445     */
4446     doesEmailAdddressExistInResultTable: function(emailAddress)
4447     {
4448         if(trim(emailAddress) == '')
4449             return false;
4450
4451         var emailAddressFound = false;
4452         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4453         for (var i=0; i < contacts.length; i++)
4454         {
4455             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4456             //If we are adding to cc or bcc fields, make them visible.
4457             if(data.email_address == emailAddress)
4458             {
4459                 emailAddressFound = true;
4460                 break;
4461             }
4462         }
4463
4464         return emailAddressFound;
4465     },
4466     /**
4467     *  Takes all email addresses that the users wishes to add from the address book and populates the To
4468     *  fields on the compose tab.
4469     */
4470     populateEmailAddressFieldsFromResultTable: function()
4471     {
4472         //Clear the fields first, all email addresses are stored in the address book
4473         var idx = SE.addressBook.idx;
4474         var emailFields = ['to','cc','bcc'];
4475         for(var k=0;k<emailFields.length;k++)
4476         {
4477             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4478             document.getElementById(elKey).value = "";
4479         }
4480
4481         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4482         for (var i=0; i < contacts.length; i++)
4483         {
4484             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4485
4486             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4487             //If we are adding to cc or bcc fields, make them visible.
4488             if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4489                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4490             //Construct the target id
4491             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4492
4493             var target = document.getElementById(target_id);
4494             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4495         }
4496
4497         //Delete all rows from the result set table
4498         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4499
4500         //Hide the dialogue
4501         SE.addressBook.contactsDialogue.hide()
4502     },
4503     /**
4504     *  Insert contacts into the result table.
4505     */
4506     insertContactToResultTable : function(event,address_type) {
4507
4508         var contactsDialogue = SE.addressBook.contactsDialogue;
4509         var contacts = SE.addressBook.grid.getSelectedRows();
4510
4511         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4512         for (var i = 0; i < rows.length; i++)
4513         {
4514                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4515                         {
4516                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4517                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4518                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4519                 rows[i].setData("selected",true);
4520                         }
4521         }
4522         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4523         for (var i = 0; i < checkBoxes.length; i++) {
4524             checkBoxes[i].checked = false;
4525         }
4526     },
4527     /**
4528     *
4529     */
4530     insertContactRowToResultTable : function(rowId, addressType) {
4531         var data = SE.addressBook.grid.getRecord(rowId).getData();
4532         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4533                 return;
4534         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4535         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4536         if(addressType == null)
4537             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4538         SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':name,'email_address': data.email,'display_email_address': ea,'bean_id': data.bean_id,'idx' : SE.addressBook.idx});
4539     },
4540     /**
4541     * Remove a row from the gridsResult table.
4542     */
4543     removeRowFromGridResults : function(rowId,emailAddress)
4544     {
4545         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4546         for (var i=0; i < contacts.length; i++)
4547         {
4548             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4549             var data = rec.getData();
4550             if(data.email_address == emailAddress)
4551             {
4552                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4553                 break;
4554             }
4555         }
4556
4557        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4558     },
4559     /**
4560     * Translates between the addressType To|Cc|Bcc labels/keys.
4561     */
4562     translateAddresType: function(addressType,fromKey)
4563     {
4564         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4565         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4566         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4567         var mappingObject = {};
4568
4569         if(fromKey)
4570             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4571         else
4572         {
4573             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4574             mappingObject[displayCc] = 'cc';
4575             mappingObject[displayBcc] = 'bcc';
4576         }
4577
4578         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4579
4580     },
4581     /**
4582     *
4583     */
4584     toggleSearchRowIcon : function(rowId,show)
4585     {
4586         if(show)
4587         {
4588             var idToShow = rowId + '_add_img';
4589             var idToHide = rowId + '_rm_img';
4590         }
4591         else
4592         {
4593             var idToShow = rowId + '_rm_img';
4594             var idToHide = rowId + '_add_img';
4595         }
4596
4597
4598         Dom.addClass(idToHide, "yui-hidden");
4599         Dom.removeClass(idToShow, "yui-hidden");
4600     },
4601     /**
4602     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4603     */
4604     doesGridResultsEntryExist: function(emailAddrs)
4605     {
4606
4607         var contactExists = false;
4608         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4609         for (var i=0; i < contacts.length; i++)
4610         {
4611             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4612             if(data.email_address == emailAddrs)
4613             {
4614                 contactExists = true;
4615                 break;
4616             }
4617         }
4618         return contactExists;
4619     },
4620
4621     /**
4622      * adds an email address to a string, but first checks if it exists
4623      * @param string concat The string we are appending email addresses to
4624      * @param string addr Email address to add
4625      * @return string
4626      */
4627     smartAddEmailAddressToComposeField : function(concat, addr) {
4628         var re = new RegExp(addr);
4629
4630         if(!concat.match(re)) {
4631             if(concat != "") {
4632                 concat += "; " + addr;
4633             } else {
4634                 concat = addr;
4635             }
4636         }
4637
4638         return concat;
4639     }
4640 };
4641 ////    END ADDRESS BOOK
4642 ///////////////////////////////////////////////////////////////////////////////
4643
4644
4645
4646 ///////////////////////////////////////////////////////////////////////////////
4647 ////    AUTOCOMPLETE
4648 /**
4649  * Auto-complete object
4650  */
4651 SE.autoComplete = {
4652     config : {
4653         delimChar : [";", ","],
4654         useShadow :    false,
4655         useIFrame : false,
4656         typeAhead : true,
4657         prehighlightClassName : "yui-ac-prehighlight",
4658         queryDelay : 0
4659     },
4660     instances : new Array(),
4661
4662     /**
4663      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4664      * @param object Contact from AddressBook
4665      * @return string
4666      */
4667     getPrimaryAddress : function(contact) {
4668         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4669
4670         for(var eIndex in contact.email) {
4671             address = contact.email[eIndex].email_address;
4672             if(contact.email[eIndex].primary_address == 1) {
4673                 return contact.email[eIndex].email_address;
4674             }
4675         }
4676         return address;
4677     },
4678
4679
4680     /**
4681      * initializes autocomplete widgets for a given compose view
4682      * @param int idx
4683      */
4684     init : function(idx) {
4685         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4686             "queryMatchContains" : false,
4687             "queryMatchSubset" : true
4688         });
4689
4690         this.instances[idx] = {
4691             to : null,
4692             cc : null,
4693             bcc : null
4694         };
4695
4696
4697         // instantiate the autoComplete widgets
4698         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4699         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4700         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4701
4702         // enable hiding of interfering textareas
4703         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4704         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4705         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4706
4707         // enable reshowing of hidden textareas
4708         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4709         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4710         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4711
4712         // enable refreshes of contact lists
4713         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4714         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4715         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4716     },
4717
4718     refreshDataSource : function(sType, aArgs) {
4719         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4720         var idx;
4721         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4722
4723         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4724             idx = textBoxId.substr(9);
4725         } else {
4726             idx = textBoxId.substr(10);
4727         }
4728
4729         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4730         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4731         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4732     },
4733
4734     /**
4735      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4736      */
4737     returnDataSource : function(contacts) {
4738         var ret = new Array();
4739         for(var id in contacts) {
4740             if (contacts[id].name) {
4741                     var primary = this.getPrimaryAddress(contacts[id]);
4742
4743                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4744                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4745
4746                     for(var emailIndex in contacts[id].email) {
4747                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4748                     }
4749             }
4750         }
4751
4752         return ret;
4753     },
4754
4755     /**
4756      * Hides address textareas to prevent autocomplete dropdown from being obscured
4757      */
4758     toggleTextareaHide : function(sType, aArgs) {
4759         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4760         var type = "";
4761         var idx = -1;
4762
4763         if(textBoxId.indexOf("addressTO") > -1) {
4764             type = "to";
4765         } else if(textBoxId.indexOf("addressCC") > -1) {
4766             type = "cc";
4767         }
4768         idx = textBoxId.substr(9);
4769
4770         // follow through if not BCC
4771         if(type != "") {
4772             var cc = document.getElementById("addressCC" + idx);
4773             var bcc = document.getElementById("addressBCC" + idx);
4774
4775             switch(type) {
4776                 case "to":
4777                     cc.style.visibility = 'hidden';
4778                 case "cc":
4779                     bcc.style.visibility = 'hidden';
4780                 break;
4781             }
4782         }
4783     },
4784
4785     /**
4786      * Redisplays the textareas after an address is commited
4787      */
4788     toggleTextareaShow : function(sType, aArgs) {
4789         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4790         var type = "";
4791         var idx = -1;
4792
4793         if(textBoxId.indexOf("addressTO") > -1) {
4794             type = "to";
4795         } else if(textBoxId.indexOf("addressCC") > -1) {
4796             type = "cc";
4797         }
4798         idx = textBoxId.substr(9);
4799
4800         // follow through if not BCC
4801         if(type != "") {
4802             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4803             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4804         }
4805     }
4806 };
4807
4808 ////    END AUTOCOMPLETE
4809 ///////////////////////////////////////////////////////////////////////////////
4810
4811 ///////////////////////////////////////////////////////////////////////////////
4812 ////    COMPOSE & SEND
4813 /**
4814  * expands the options sidebar
4815  */
4816 SE.composeLayout = {
4817     currentInstanceId : 0,
4818     ccHidden : true,
4819     bccHidden : true,
4820     outboundAccountErrors : null,
4821     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4822
4823     showAddressDetails : function(e) {
4824         var linkElement = document.getElementById("More"+e.id);
4825         var spanElement = document.getElementById("Detail"+e.id);
4826         var emailAddressList = e.value;
4827         if(e.value.length > 96)
4828         {
4829                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4830             var displayArray = [];
4831                 for (var i=0; i<resultArray.length; i++)
4832                 {
4833                     var t_name = resultArray[i].name;
4834                     var t_emailAddr = resultArray[i].email_address;
4835                     if(t_name == '')
4836                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4837                     else
4838                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');
4839                 }
4840
4841             var result = displayArray.join('<br/>');
4842                 // Display
4843             linkElement.style.display = "inline";
4844             linkElement.style.height="10px";
4845             linkElement.style.overflow="visible";
4846             spanElement.innerHTML = result;
4847         }
4848         else
4849                 linkElement.style.display = "none";
4850
4851         },
4852
4853    /**
4854     *  Given a string of email address, return an array containing the name portion (if available)
4855     *  and email portion.
4856     */
4857     _getEmailArrayFromString : function (emailAddressList){
4858
4859         var reg = /@.*?;/g;
4860         while ((results = reg.exec(emailAddressList)) != null)
4861         {
4862             orignial = results[0];
4863             parsedResult = results[0].replace(';', ':::::');
4864             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4865         }
4866
4867         reg = /@.*?,/g;
4868         while ((results = reg.exec(emailAddressList)) != null)
4869         {
4870             orignial = results[0];
4871             parsedResult = results[0].replace(',', ':::::');
4872             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4873         }
4874         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4875         var emailArr = emailAddressList.split(":::::");
4876         var resultsArray = [];
4877         var newArr = [];
4878         for (var i=0; i<emailArr.length; i++)
4879         {
4880             var rposition = emailArr[i].indexOf('<');
4881             var lposition = emailArr[i].indexOf('>');
4882
4883             if(trim(emailArr[i]) != '')
4884             {
4885                 if(rposition != -1 && lposition != -1)
4886                 {
4887                     var t_name = emailArr[i].substr(0, rposition-1);
4888                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4889                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4890                 }
4891                 else
4892                 {
4893                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4894                 }
4895             }
4896         }
4897         return resultsArray;
4898     },
4899     ///////////////////////////////////////////////////////////////////////////
4900     ////    COMPOSE FLOW
4901     /**
4902      * Prepare bucket DIV and yui-ext tab panels
4903      */
4904     _0_yui : function() {
4905         var idx = this.currentInstanceId;
4906
4907         var composeTab = new YAHOO.SUGAR.ClosableTab({
4908                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4909                                 scroll : true,
4910                                 content : "<div id='htmleditordiv" + idx + "'/>",
4911                                 id : "composeTab" + idx,
4912                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4913                                 active : true
4914         }, SE.innerLayout);
4915         SE.innerLayout.addTab(composeTab);
4916
4917         // get template engine with template
4918         if (!SE.composeLayout.composeTemplate) {
4919                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4920         }
4921
4922         // create Tab inner layout
4923         var composePanel =  this.getComposeLayout();
4924         composePanel.getUnitByPosition("right").collapse();
4925         composePanel.autoSize();
4926
4927     },
4928         /**
4929      * Generate the quick compose layout
4930          * @method getQuickComposeLayout
4931          * @param {Pannel} parentPanel Parent pannel
4932          * @param {Object} o Options
4933          * @return {} none
4934          **/
4935     getQuickComposeLayout : function (parentPanel,o) {
4936          var idx = SE.composeLayout.currentInstanceId;
4937
4938          //Before rendering the parent pannel we need to initalize the grid layout
4939          parentPanel.beforeRenderEvent.subscribe(function() {
4940
4941                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4942                         SE.composeLayout._createComposeLayout(idx);
4943                         SE.composeLayout[idx].set('height', 350);
4944                         SE.composeLayout[idx].render();
4945            });
4946         });
4947
4948          //Wait until the Compose Layout has rendered, then add the
4949          //options tab and perform the tiny initialization.
4950          parentPanel.renderEvent.subscribe(function() {
4951
4952                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4953                 SE.composeLayout._initComposeOptionTabs(idx);
4954                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4955                 //Initialize tinyMCE
4956             SE.composeLayout._1_tiny(false);
4957
4958                 //Init templates and address book
4959                 SE.composeLayout._2_final();
4960
4961             SE.composeLayout.quickCreateComposePackage(o);
4962
4963                 });
4964          });
4965
4966             //Check if we have the div override for the shortcut bar
4967         if(typeof o.menu_id != 'undefined') {
4968                    parentPanel.render(o.menu_id);
4969             } else {
4970                    parentPanel.render(document.body);
4971             }
4972
4973         return SE.composeLayout[idx];
4974     },
4975     /**
4976      * Fill in all fields into the quick compose layout.
4977          * @method quickCreateComposePackage
4978          * @param {Object} o Options
4979          * @return {} none
4980          **/
4981     quickCreateComposePackage: function(o)
4982     {
4983         //If we have a compose package fill in defaults.
4984         if (typeof(o.composePackage) != 'undefined')
4985         {
4986             composePackage = o.composePackage; //Set the compose data object
4987             //Hijack this method called by composePackage as it's not need for quick creates.
4988             SE.composeLayout.c0_composeNewEmail = function(){};
4989             SE.composeLayout.composePackage(); //Fill in defaults.
4990         }
4991     },
4992     getComposeLayout : function() {
4993         var idx = SE.composeLayout.currentInstanceId;
4994
4995         this._createComposeLayout(idx);
4996         SE.composeLayout[idx].render();
4997         this._initComposeOptionTabs(idx);
4998
4999         return SE.composeLayout[idx];
5000         },
5001
5002         /**
5003         *       Create the layout manager for the compose window.
5004         */
5005         _createComposeLayout : function(idx)
5006         {
5007                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5008                 parent: SE.complexLayout,
5009                 border:true,
5010             hideOnLayout: true,
5011             height: 400,
5012                         units: [{
5013                                         position: "center",
5014                         animate: false,
5015                         scroll: false,
5016                         split:true,
5017                         body:
5018                                 SE.composeLayout.composeTemplate.exec({
5019                                 'app_strings':app_strings,
5020                                 'mod_strings':mod_strings,
5021                                 'linkbeans_options' : linkBeans,
5022                                 'idx' : SE.composeLayout.currentInstanceId
5023                                 })
5024                     },{
5025                         position: "right",
5026                                     scroll:true,
5027                                     collapse: true,
5028                                     collapsed: true,
5029                                     resize: true,
5030                                     border:true,
5031                                     animate: false,
5032                                     width:'230',
5033                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5034                                     titlebar: true,
5035                                     split: true,
5036                                     header: app_strings.LBL_EMAIL_OPTIONS
5037                     }]
5038                 });
5039         },
5040
5041         /**
5042         *  Create compose tab which will populate the 'right' container in the compose window.
5043         */
5044         _initComposeOptionTabs : function(idx)
5045         {
5046                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5047                 var tab = new YAHOO.widget.Tab({
5048                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5049                                 scroll : true,
5050                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5051                                 id : "divAttachments" + idx,
5052                                 active : true
5053                         });
5054
5055                 tab.layout = SE.composeLayout[idx];
5056
5057            tab.on("activeChange", function(o){
5058                         if (o.newValue) {
5059                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5060                         }
5061                 });
5062
5063                 cTabs.addTab(tab);
5064
5065                 tab = new YAHOO.widget.Tab({
5066                                 label: app_strings.LBL_EMAIL_OPTIONS,
5067                                 scroll : true,
5068                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5069                                 id : "divOptions" + idx,
5070                                 active : false
5071                         });
5072
5073                 tab.layout = SE.composeLayout[idx];
5074                 tab.on("activeChange", function(o){
5075                         if (o.newValue) {
5076                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5077                         }
5078                 });
5079                 cTabs.addTab(tab);
5080
5081                 SE.composeLayout[idx].autoSize = function() {
5082                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5083                         this.set("height", pEl.clientHeight-30);
5084                         this.render();
5085                 }
5086
5087                 SE.composeLayout[idx].rightTabs = cTabs;
5088     },
5089     isParentTypeValid : function(idx) {
5090                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5091                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5092                 if (trim(parentTypeValue) == ""){
5093                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5094                         return false;
5095                 } // if
5096                 return true;
5097     },
5098
5099     isParentTypeAndNameValid : function(idx) {
5100                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5101                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5102                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5103                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5104                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5105                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5106                         return false;
5107                 } // if
5108                 return true;
5109     },
5110
5111     callopenpopupForEmail2 : function(idx,options) {
5112
5113         var formName = 'emailCompose' + idx;
5114
5115         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5116             formName = options.form_name;
5117
5118                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5119                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5120                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5121                         return;
5122                 } // if
5123                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5124                 {
5125                         call_back_function:"SE.composeLayout.popupAddEmail",
5126                         form_name:formName,
5127                         field_to_name_array:{
5128                                 id:'data_parent_id' + idx,
5129                                 name:'data_parent_name' + idx,
5130                                 email1:'email1'}
5131                 });
5132         },
5133
5134         popupAddEmail : function(o)
5135         {
5136                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5137                 var data = o.name_to_value_array;
5138                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5139                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5140         {
5141                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5142                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5143         }
5144                 set_return(o);
5145         },
5146     /**
5147      * Prepare TinyMCE
5148      */
5149     _1_tiny : function(isReplyForward) {
5150         var idx = SE.composeLayout.currentInstanceId;
5151         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5152         SE.tinyInstances[elId] = { };
5153         SE.tinyInstances[elId].ready = false;
5154
5155         if (!SUGAR.util.isTouchScreen()) {
5156             var t = tinyMCE.getInstanceById(elId);
5157         }
5158         if(typeof(t) == 'undefined')  {
5159             if (!SUGAR.util.isTouchScreen()) {
5160                 tinyMCE.execCommand('mceAddControl', false, elId);
5161             }
5162             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5163                 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5164                 }, this);
5165         }
5166     },
5167
5168     resizeEditorSetSignature : function(idx,setSignature)
5169     {
5170         var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5171
5172         if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5173             setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+setSignature+"');",500);
5174                     return;
5175                 }
5176
5177         SE.composeLayout.resizeEditor(idx);
5178         if(setSignature) {
5179             setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5180         }
5181
5182     },
5183
5184     resizeEditor : function(idx)
5185     {
5186         var cof = Dom.get('composeOverFrame' + idx);
5187         var head = Dom.get('composeHeaderTable' + idx);
5188         var targetHeight = cof.clientHeight - head.clientHeight;
5189         var instance = SE.util.getTiny('htmleditor' + idx);
5190
5191         try {
5192         var parentEl = Dom.get(instance.editorId + '_parent');
5193         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5194         var contentEl  = instance.contentAreaContainer;
5195         var iFrame = contentEl.firstChild;
5196         var tinMceToolbarOffset = 18;
5197         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5198
5199         } catch(e) {
5200             setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5201         }
5202     },
5203
5204     /**
5205      * Initializes d&d, auto-complete, email templates
5206      */
5207     _2_final : function() {
5208         var idx = SE.composeLayout.currentInstanceId;
5209
5210         if(this.emailTemplates) {
5211             this.setComposeOptions(idx);
5212         } else {
5213             //populate email template cache
5214             AjaxObject.target = '';
5215             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5216         }
5217
5218         // handle drop targets for addressBook
5219        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5220        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5221        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5222        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5223
5224         // auto-complete setup
5225         SE.autoComplete.init(idx);
5226
5227         // set focus on to:
5228         document.getElementById("addressTO" + idx).focus();
5229     },
5230
5231         /**
5232      * hide tinyMCE tool bar if send email as plaintext is checked
5233      */
5234     renderTinyMCEToolBar : function (idx, hide) {
5235         if (hide) {
5236                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5237         } else {
5238                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5239         }
5240     },
5241
5242     c1_composeEmail : function(isReplyForward, retry) {
5243         if (!retry) {
5244             this._0_yui();
5245         }
5246         if  (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
5247             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5248         } else {
5249                 this._1_tiny(isReplyForward);
5250                 this._2_final();
5251
5252                 if(isReplyForward) {
5253                     this.replyForwardEmailStage2();
5254                 }
5255         }
5256     },
5257
5258     /**
5259      * takes draft info and prepopulates
5260      */
5261     c0_composeDraft : function() {
5262         this.getNewInstanceId();
5263         inCompose = true;
5264         document.getElementById('_blank').innerHTML = '';
5265         var idx = SE.composeLayout.currentInstanceId;
5266                 SE.composeLayout.draftObject = new Object();
5267                 SE.composeLayout.draftObject.id = idx;
5268                 SE.composeLayout.draftObject.isDraft = true;
5269         SE.composeLayout.currentInstanceId = idx;
5270         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5271         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5272         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5273
5274         SE.composeLayout._0_yui();
5275         SE.composeLayout._1_tiny(true);
5276
5277         // final touches
5278         SE.composeLayout._2_final();
5279
5280         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5281         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5282     },
5283
5284     /**
5285      * Strip & Prep editor hidden fields
5286      */
5287     c0_composeNewEmail : function() {
5288         this.getNewInstanceId();
5289         this.c1_composeEmail(false);
5290     },
5291
5292     /**
5293      * Sends async request to get the compose view.
5294      * Requests come from "reply" or "forwards"
5295      */
5296     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5297         SE.composeLayout.replyForwardObj = new Object();
5298         SE.composeLayout.replyForwardObj.ieId = ieId;
5299         SE.composeLayout.replyForwardObj.uid = uid;
5300         SE.composeLayout.replyForwardObj.mbox = mbox;
5301         SE.composeLayout.replyForwardObj.type = type;
5302
5303         if(mbox == 'sugar::Emails') {
5304             SE.composeLayout.replyForwardObj.sugarEmail = true;
5305         }
5306
5307         SE.composeLayout.getNewInstanceId();
5308         SE.composeLayout.c1_composeEmail(true);
5309     },
5310     ////    END COMPOSE FLOW
5311     ///////////////////////////////////////////////////////////////////////////
5312
5313     /**
5314      * Called when a contact, email, or mailinglist is dropped
5315      * into one of the compose fields.
5316      */
5317     handleDrop : function (source, event, data, target) {
5318         var nodes;
5319         if (!target) {
5320             target = event.getTarget();
5321             if (data.single) {
5322                 data.nodes = [data.nodes];
5323             }
5324             nodes = data.nodes;
5325         } else {
5326             target = document.getElementById(target);
5327             nodes = data;
5328         }
5329
5330         if (target.id.indexOf('address') > -1) {
5331             // dropped onto email to/cc/bcc field
5332             for(var i in nodes) {
5333                 var node = nodes[i].getData();
5334                 var email = "";
5335                 if (node[1].indexOf('contact') > -1) {
5336                     email = SE.addressBook.getFormattedAddress(node[0]);
5337                 } else if (node[1].indexOf('address-email') > -1){
5338                     email = node[3].replace(/&nbsp;/gi, '');
5339                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5340                     var tr = source.getTrEl(nodes[i]);
5341                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5342                         tr = source.getPreviousTrEl(tr);
5343                     }
5344                     var CID = source.getRecord(tr).getData()[0];
5345                     var o = SE.addressBook._contactCache[CID];
5346                     var name = new String(o.name);
5347                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5348                     email = finalName + email;
5349                 }
5350                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5351             }
5352         }
5353     },
5354
5355
5356     /*/////////////////////////////////////////////////////////////////////////////
5357     ///    EMAIL TEMPLATE CODE
5358      */
5359     applyEmailTemplate : function (idx, id) {
5360
5361         //bug #20680
5362         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5363                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5364                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5365
5366                 //bug #6224
5367                 var to_addr = document.getElementById('addressTO'+idx);
5368                 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5369                 {
5370                         box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5371                         box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5372                 }
5373
5374                 // id is selected index of email template drop-down
5375                 if(id == '' || id == "0") {
5376                         YAHOO.SUGAR.MessageBox.show({
5377                    title:box_title,
5378                    msg: box_none_msg,
5379                    type: 'confirm',
5380                    fn: function(btn){
5381                                 if(btn=='no'){return;};
5382                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5383                    modal:true,
5384                    scope:this
5385                });
5386                return;
5387                 }
5388
5389                 YAHOO.SUGAR.MessageBox.show({
5390            title:box_title,
5391            msg: box_msg,
5392            type: 'confirm',
5393            fn: function(btn){
5394                         if(btn=='no'){return;};
5395                         SUGAR.email2.composeLayout.processResult(idx, id);},
5396            modal:true,
5397            scope:this
5398        });
5399     },
5400
5401     processNoneResult : function(idx, id) {
5402         var tiny = SE.util.getTiny('htmleditor' + idx);
5403         var tinyHTML = tiny.getContent();
5404         var openTag = '<div><span><span>';
5405         var htmllow = tinyHTML.toLowerCase();
5406         var start = htmllow.indexOf(openTag);
5407                 if (start > -1) {
5408                 tinyHTML = tinyHTML.substr(start);
5409             tiny.setContent(tinyHTML);
5410                 } else {
5411             tiny.setContent('');
5412                 }
5413     },
5414
5415         processResult : function(idx , id){
5416                 var post_data = {"module":"EmailTemplates","record":id};
5417                 var global_rpcClient =  new SugarRPCClient();
5418
5419                 result = global_rpcClient.call_method('retrieve', post_data, true);
5420                 if(!result['record']) return;
5421                 json_objects['email_template_object'] = result['record'];
5422                 this.appendEmailTemplateJSON();
5423
5424         // get attachments if any
5425         AjaxObject.target = '';
5426         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5427     },
5428
5429     appendEmailTemplateJSON : function() {
5430         var idx = SE.composeLayout.currentInstanceId; // post increment
5431
5432         // query based on template, contact_id0,related_to
5433         //jchi 09/10/2008 refix #7743
5434         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5435             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5436         }
5437
5438         var text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body_html'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
5439
5440         // cn: bug 14361 - text-only templates don't fill compose screen
5441         if(text == '') {
5442             text = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body'])).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"').replace(/\r\n/gi,"<br/>");
5443         }
5444
5445         var tiny = SE.util.getTiny('htmleditor' + idx);
5446         var tinyHTML = tiny.getContent();
5447         var openTag = '<div><span><span>';
5448         var closeTag = '</span></span></div>';
5449         var htmllow = tinyHTML.toLowerCase();
5450         var start = htmllow.indexOf(openTag);
5451                 if (start > -1) {
5452                 var htmlPart2 = tinyHTML.substr(start);
5453                 tinyHTML = text + htmlPart2;
5454                 tiny.setContent(tinyHTML);
5455                 } else {
5456                 tiny.setContent(text);
5457                 }
5458     },
5459
5460     /**
5461      * Writes out the signature in the email editor
5462      */
5463     setSignature : function(idx) {
5464         if (!tinyMCE)
5465             return false;
5466         var hide = document.getElementById('setEditor' + idx).checked;
5467         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5468         //wait for signatures to load before trying to set them
5469         if (!SE.composeLayout.signatures) {
5470             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5471                         return;
5472         }
5473
5474         if(idx) {
5475             var sel = document.getElementById('signatures' + idx);
5476         } else {
5477             var sel = document.getElementById('signature_id');
5478             idx = SE.tinyInstances.currentHtmleditor;
5479         }
5480
5481         //Ensure that the tinyMCE html has been rendered.
5482         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5483             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5484                     return;
5485                 }
5486
5487         var signature = '';
5488
5489         try {
5490             signature = sel.options[sel.selectedIndex].value;
5491         } catch(e) {
5492
5493         }
5494
5495         var openTag = '<div><span>&nbsp;</span>';
5496         var closeTag = '<span>&nbsp;</span></div>';
5497         var t = tinyMCE.getInstanceById('htmleditor' + idx);
5498         //IE 6 Hack
5499         if(typeof(t) != 'undefined')
5500         {
5501             t.contentDocument = t.contentWindow.document;
5502             var html = t.getContent();
5503         }
5504         else
5505         {
5506             var html = '';
5507         }
5508
5509         var htmllow = html.toLowerCase();
5510         var start = htmllow.indexOf(openTag);
5511         var end = htmllow.indexOf(closeTag) + closeTag.length;
5512
5513         // selected "none" - remove signature from email
5514         if(signature == '') {
5515             if (start > -1) {
5516                 var htmlPart1 = html.substr(0, start);
5517                 var htmlPart2 = html.substr(end, html.length);
5518
5519                 html = htmlPart1 + htmlPart2;
5520                 t.setContent(html);
5521             }
5522             SE.signatures.lastAttemptedLoad = '';
5523             return false;
5524         }
5525
5526         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5527             SE.signatures.lastAttemptedLoad = '';
5528
5529         SE.signatures.lastAttemptedLoad = signature;
5530
5531         if(typeof(SE.signatures[signature]) == 'undefined') {
5532             //lazy load
5533             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5534             SE.signatures.targetInstance = (idx) ? idx : "";
5535             AjaxObject.target = '';
5536             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5537         } else {
5538             var newSignature = this.prepareSignature(SE.signatures[signature]);
5539
5540             // clear out old signature
5541             if(SE.signatures.lastAttemptedLoad && start > -1) {
5542                 var htmlPart1 = html.substr(0, start);
5543                 var htmlPart2 = html.substr(end, html.length);
5544
5545                 html = htmlPart1 + htmlPart2;
5546             }
5547
5548             // [pre|ap]pend
5549                         start = html.indexOf('<div><hr></div>');
5550             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5551                                 var htmlPart1 = html.substr(0, start);
5552                                 var htmlPart2 = html.substr(start, html.length);
5553                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5554             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5555                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5556             } else {
5557                 var body = html.indexOf('</body>');
5558                 if (body > -1) {
5559                     var part1 = html.substr(0, body);
5560                     var part2 = html.substr(body, html.length);
5561                     var newHtml = part1 + openTag + newSignature + closeTag + part2;
5562                 } else {
5563                     var newHtml = html + openTag + newSignature + closeTag;
5564                 }
5565             }
5566             //tinyMCE.setContent(newHtml);
5567             t.setContent(newHtml);
5568         }
5569     },
5570
5571     prepareSignature : function(str) {
5572         var signature = new String(str);
5573
5574         signature = signature.replace(/&lt;/gi, '<');
5575         signature = signature.replace(/&gt;/gi, '>');
5576
5577         return signature;
5578     },
5579
5580
5581     showAttachmentPanel : function(idx) {
5582         var east = SE.composeLayout[idx].getUnitByPosition("right");
5583         var tabs = SE.composeLayout[idx].rightTabs;
5584         east.expand();
5585         tabs.set("activeTab", tabs.getTab(0));
5586     },
5587
5588     /**
5589      * expands sidebar and displays options panel
5590      */
5591     showOptionsPanel : function(idx) {
5592         var east = SE.composeLayout[idx].getUnitByPosition("right");
5593         var tabs = SE.composeLayout[idx].rightTabs;
5594         east.expand();
5595         tabs.set("activeTab", tabs.getTab(1));
5596     },
5597
5598     /**
5599      * Selects the Contacts tab
5600      */
5601     showContactsPanel : function() {
5602         SE.complexLayout.regions.west.showPanel("contactsTab");
5603     },
5604
5605     /**
5606      * Generates fields for Select Document
5607      */
5608     addDocumentField : function(idx) {
5609         var basket = document.getElementById('addedDocuments' + idx);
5610         if(basket) {
5611             var index = (basket.childNodes.length / 7) - 1;
5612             if(index < 0)
5613                 index = 0;
5614         } else {
5615             index = 0;
5616         }
5617
5618         var test = document.getElementById('documentId' + idx + index);
5619
5620         while(test != null) {
5621             index++;
5622             test = document.getElementById('documentId' + idx + index);
5623         }
5624
5625         var documentCup = document.createElement("div");
5626         documentCup.id = 'documentCup' + idx + index;
5627         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5628                 // document id field
5629                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5630                 // document name field
5631                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5632                 // select button
5633                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5634                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5635                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5636                 // remove button
5637                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5638                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5639                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5640                 "<br/>";
5641
5642         basket.appendChild(documentCup);
5643         //basket.innerHTML += out;
5644         return index;
5645     },
5646
5647     /**
5648      * Makes async call to save a draft of the email
5649      * @param int Instance index
5650      */
5651     saveDraft : function(tinyInstance) {
5652         this.sendEmail(tinyInstance, true);
5653     },
5654
5655     selectDocument : function(target) {
5656         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5657         windowName = 'selectDocument';
5658         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5659
5660         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5661         if(window.focus) {
5662             // put the focus on the popup if the browser supports the focus() method
5663             win.focus();
5664         }
5665     },
5666
5667     /**
5668      * Modal popup for file attachment dialogue
5669      */
5670     addFileField : function() {
5671         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5672             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5673                 modal:true,
5674                 visible:false,
5675                 fixedcenter:true,
5676                 constraintoviewport: true,
5677                 scroll: true,
5678                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5679                         fn:function(){SE.addFileDialog.hide();}
5680                 })
5681             });
5682             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5683             SE.addFileDialog.render();
5684            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5685         }
5686         Dom.removeClass("addFileDialog", "yui-hidden");
5687
5688         SE.addFileDialog.show();
5689     },
5690
5691     /**
5692      * Async upload of file to temp dir
5693      */
5694     uploadAttachment : function() {
5695         if(document.getElementById('email_attachment').value != "") {
5696             var formObject = document.getElementById('uploadAttachment');
5697             YAHOO.util.Connect.setForm(formObject, true, true);
5698             AjaxObject.target = '';
5699             AjaxObject.startRequest(callbackUploadAttachment, null);
5700         } else {
5701             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5702         }
5703     },
5704
5705     /**
5706      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5707      * @param string target in focus compose layout
5708      */
5709     setDocument : function(idx, target, documentId, documentName, docRevId) {
5710         // fields are named/id'd [fieldName][instanceId][index]
5711         var addedDocs = document.getElementById("addedDocuments" + idx);
5712         var docId = document.getElementById('documentId' + idx + target);
5713         var docName = document.getElementById('documentName' + idx + target);
5714         var docRevisionId = document.getElementById('document' + idx + target);
5715         docId.value = documentId;
5716         docName.value = documentName;
5717         docRevisionId.value = docRevId;
5718     },
5719
5720     /**
5721      * Removes the bucket div containing the document input fields
5722      */
5723     deleteDocumentField : function(documentCup) {
5724         var f0 = document.getElementById(documentCup);
5725         f0.parentNode.removeChild(f0);
5726     },
5727
5728     /**
5729      * Removes a Template Attachment field
5730      * @param int
5731      * @param int
5732      */
5733     deleteTemplateAttachmentField : function(idx, index) {
5734         // create not-in-array values for removal filtering
5735         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5736
5737         if(r != "") {
5738             r += "::";
5739         }
5740
5741         r += document.getElementById('templateAttachmentId' + idx + index).value;
5742         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5743
5744         var target = 'templateAttachmentCup' + idx + index;
5745         d =  document.getElementById(target);
5746         d.parentNode.removeChild(d);
5747     },
5748
5749     /**
5750      * Async removal of uploaded temp file
5751      * @param string index Should be a concatenation of idx and index
5752      * @param string
5753      */
5754     deleteUploadAttachment : function(index, file) {
5755         var d = document.getElementById('email_attachment_bucket' + index);
5756         d.parentNode.removeChild(d);
5757
5758         // make async call to delete cached file
5759         AjaxObject.target = '';
5760         AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5761     },
5762
5763     /**
5764      * Attaches files coming from Email Templates
5765      */
5766     addTemplateAttachmentField : function(idx) {
5767         // expose title
5768         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5769
5770         var basket = document.getElementById('addedTemplateAttachments' + idx);
5771
5772         if(basket) {
5773             var index = basket.childNodes.length;
5774             if(index < 0)
5775                 index = 0;
5776         } else {
5777             index = 0;
5778         }
5779
5780         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5781                                 // remove button
5782                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5783                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5784                                         idx + "\",\"" + index + "\");'/>" +
5785                                 // file icon
5786                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5787                                 // templateAttachment field
5788                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5789                                 // docId field
5790                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5791                                 // file name
5792                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
5793                                 "<br id='br" + index + "></br>" +
5794                                 "<br id='brdoc" + index + "></br>" +
5795                         "</div>";
5796                 basket.innerHTML = basket.innerHTML + out;
5797
5798         return index;
5799     },
5800
5801     /**
5802      * Sends one email via async call
5803      * @param int idx Editor instance ID
5804      * @param bool isDraft
5805      */
5806     sendEmail : function(idx, isDraft) {
5807
5808         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5809         var obAccountID = document.getElementById('addressFrom' + idx).value;
5810
5811         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5812         {
5813             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5814             return false;
5815         }
5816
5817
5818         var form = document.getElementById('emailCompose' + idx);
5819         var composeOptionsFormName = "composeOptionsForm" + idx;
5820
5821
5822         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5823         if (t != null || typeof(t) != "undefined") {
5824             var html = t.getContent();
5825         } else {
5826             var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
5827         }
5828
5829             var subj = document.getElementById('emailSubject' + idx).value;
5830         var to = trim(document.getElementById('addressTO' + idx).value);
5831         var cc = trim(document.getElementById('addressCC' + idx).value);
5832         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5833         var email_id = document.getElementById('email_id' + idx).value;
5834         var composeType = document.getElementById('composeType').value;
5835         var parent_type = document.getElementById("parent_type").value;
5836         var parent_id = document.getElementById("parent_id").value;
5837
5838         var el_uid = document.getElementById("uid");
5839         var uid = (el_uid == null) ? '' : el_uid.value;
5840
5841         var el_ieId = document.getElementById("ieId");
5842         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5843
5844         var el_mbox = document.getElementById("mbox");
5845         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5846
5847         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5848                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5849                 return false;
5850         }
5851
5852         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5853                 return;
5854         } // if
5855                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5856                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5857         parent_id = parentIdValue;
5858         parent_type = parentTypeValue;
5859
5860         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5861         // baseline viability check
5862
5863         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5864             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5865             return false;
5866         } else if(subj == '' && !isDraft) {
5867             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5868                 return false;
5869             } else {
5870                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5871             }
5872         } else if(html == '' && !isDraft) {
5873             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5874                 return false;
5875             }
5876         }
5877
5878         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5879                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5880                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5881         SUGAR.showMessageBox(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5882         html = html.replace(/&lt;/ig, "sugarLessThan");
5883         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5884
5885         form.sendDescription.value = html;
5886         form.sendSubject.value = subj;
5887         form.sendTo.value = to;
5888         form.sendCc.value = cc;
5889         form.sendBcc.value = bcc;
5890         form.email_id.value = email_id;
5891         form.composeType.value = composeType;
5892         form.composeLayoutId.value = 'composeLayout' + idx;
5893         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5894         form.saveToSugar.value = 1;
5895         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5896         form.parent_type.value = parent_type;
5897         form.parent_id.value = parent_id;
5898         form.uid.value = uid;
5899         form.ieId.value = ieId;
5900         form.mbox.value = mbox;
5901
5902         // email attachments
5903         var addedFiles = document.getElementById('addedFiles' + idx);
5904         if(addedFiles) {
5905             for(i=0; i<addedFiles.childNodes.length; i++) {
5906                 var bucket = addedFiles.childNodes[i];
5907
5908                 for(j=0; j<bucket.childNodes.length; j++) {
5909                     var node = bucket.childNodes[j];
5910                     var nName = new String(node.name);
5911
5912                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5913                         if(form.attachments.value != '') {
5914                             form.attachments.value += "::";
5915                         }
5916                         form.attachments.value += node.value;
5917                     }
5918                 }
5919             }
5920         }
5921
5922         // sugar documents
5923         var addedDocs = document.getElementById('addedDocuments' + idx);
5924         if(addedDocs) {
5925             for(i=0; i<addedDocs.childNodes.length; i++) {
5926                 var cNode = addedDocs.childNodes[i];
5927                 for(j=0; j<cNode.childNodes.length; j++) {
5928                     var node = cNode.childNodes[j];
5929                     var nName = new String(node.name);
5930                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5931                         if(form.documents.value != '') {
5932                             form.documents.value += "::";
5933                         }
5934                         form.documents.value += node.value;
5935                     }
5936                 }
5937             }
5938         }
5939
5940         // template attachments
5941         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5942         if(addedTemplateAttachments) {
5943             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5944                 var cNode = addedTemplateAttachments.childNodes[i];
5945                 for(j=0; j<cNode.childNodes.length; j++) {
5946                     var node = cNode.childNodes[j];
5947                     var nName = new String(node.name);
5948                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5949                         if(form.templateAttachments.value != "") {
5950                             form.templateAttachments.value += "::";
5951                         }
5952                         form.templateAttachments.value += node.value;
5953                     }
5954                 }
5955             }
5956         }
5957
5958         // remove attachments
5959         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5960
5961         YAHOO.util.Connect.setForm(form);
5962
5963         AjaxObject.target = 'frameFlex';
5964
5965         // sending a draft email
5966         if(!isDraft && in_draft) {
5967             // remove row
5968             SE.listView.removeRowByUid(email_id);
5969         }
5970
5971         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5972         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5973
5974         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5975     },
5976
5977     /**
5978      * Handles clicking the email address link from a given view
5979      */
5980     composePackage : function() {
5981         if(composePackage != null) {
5982             SE.composeLayout.c0_composeNewEmail();
5983
5984
5985             if(composePackage.to_email_addrs) {
5986                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5987             } // if
5988             if (composePackage.subject != null && composePackage.subject.length > 0) {
5989                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5990             }
5991
5992             //If no parent fields are set in the composePackage, ensure they are cleared.
5993             var parentFields = ['parent_type','parent_name','parent_id'];
5994             for(var i=0;i<parentFields.length;i++)
5995             {
5996                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5997                     composePackage[parentFields[i]] = "";
5998             }
5999
6000             document.getElementById("parent_type").value = composePackage.parent_type;
6001             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
6002             document.getElementById("parent_id").value = composePackage.parent_id;
6003             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
6004             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
6005
6006             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
6007                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
6008             } // if
6009             if (composePackage.body != null && composePackage.body.length > 0) {
6010                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6011                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
6012                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
6013             } // if
6014             if (composePackage.attachments != null) {
6015                                 SE.composeLayout.loadAttachments(composePackage.attachments);
6016             } // if
6017
6018             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
6019                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
6020                         SE.util.emptySelectOptions(addressFrom);
6021                         var fromAccountOpts = composePackage.fromAccounts.data;
6022                         for(i=0; i<fromAccountOpts.length; i++) {
6023                               var key = fromAccountOpts[i].value;
6024                               var display = fromAccountOpts[i].text;
6025                               var opt = new Option(display, key);
6026                               if (fromAccountOpts[i].selected) {
6027                                 opt.selected = true;
6028                               }
6029                               addressFrom.options.add(opt);
6030                         }
6031
6032             } // if
6033         } // if
6034     },
6035
6036     setContentOnThisTiny : function() {
6037         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6038         var tinyHTML = tiny.getContent();
6039         composePackage.body = decodeURI(encodeURI(composePackage.body));
6040         // cn: bug 14361 - text-only templates don't fill compose screen
6041         if(composePackage.body == '') {
6042             composePackage.body = decodeURI(encodeURI(composePackage.body)).replace(/<BR>/ig, '\n').replace(/<br>/gi, "\n").replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
6043         } // if
6044         //Flag determines if we should clear the tiny contents or just append
6045         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6046             SE.composeLayout.tinyHTML = '';
6047         else
6048             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6049
6050          tiny.setContent(SE.composeLayout.tinyHTML);
6051          //Indicate that the contents has been loaded successfully.
6052          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6053     },
6054     /**
6055      * Confirms closure of a compose screen if "x" is clicked
6056      */
6057     confirmClose : function(panel) {
6058         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6059             SE.composeLayout.closeCompose(panel.id);
6060             return true;
6061         } else {
6062             return false;
6063         }
6064     },
6065
6066     /**
6067      * forces close of a compose screen
6068      */
6069     forceCloseCompose : function(id) {
6070         SE.composeLayout.closeCompose(id);
6071
6072         // handle flow back to originating view
6073         if(composePackage) {
6074             // check if it's a module we need to return to
6075             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6076                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6077                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6078                     window.location = url;
6079                 }
6080             }
6081         }
6082     },
6083
6084     /**
6085      * closes the editor that just sent email
6086      * @param string id ID of composeLayout tab
6087      */
6088     closeCompose : function(id) {
6089         // destroy tinyMCE instance
6090         var idx = id.substr(13, id.length);
6091         var instanceId = "htmleditor" + idx;
6092         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6093
6094         // nullify DOM and namespace values.
6095         inCompose = false;
6096         SE.composeLayout[idx] = null;
6097         SE.tinyInstances[instanceId] = null;
6098         var tabsArray = SE.innerLayout.get("tabs");
6099         for (i = 0 ; i < tabsArray.length ; i++) {
6100                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6101                         tabsArray[i].close();
6102                         break;
6103                 }
6104         }
6105         //SE.innerLayout.getTab(idx).close();
6106     },
6107
6108     /**
6109     *  Enable the quick search for the compose relate field or search tab
6110     */
6111     enableQuickSearchRelate: function(idx,overides){
6112
6113         if(typeof overides != 'undefined')
6114         {
6115             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6116             var newModule = document.getElementById(newModuleID).value;
6117             var formName = overides['formName'];
6118             var fieldName = overides['fieldName'];
6119             var fieldId = overides['fieldId'];
6120             var fullName = formName + "_" + fieldName;
6121             var postBlurFunction = null;
6122         }
6123         else
6124         {
6125             var newModule = document.getElementById('data_parent_type'+idx).value;
6126             var formName = 'emailCompose'+idx;
6127             var fieldName = 'data_parent_name'+idx;
6128             var fieldId = 'data_parent_id'+idx;
6129             var fullName = formName + "_" + fieldName;
6130             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6131         }
6132
6133         if(typeof sqs_objects == 'undefined')
6134             window['sqs_objects'] = new Array;
6135
6136         window['sqs_objects'][fullName] = {
6137             form:formName,
6138                         method:"query",
6139                         modules:[newModule],
6140                         group:"or",
6141             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6142             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6143                         post_onblur_function: postBlurFunction,
6144             order:"name","limit":"30","no_match_text":"No Match"};
6145
6146
6147         if(typeof QSProcessedFieldsArray != 'undefined')
6148                 QSProcessedFieldsArray[fullName] = false;
6149         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6150                 QSFieldsArray[fullName].destroy();
6151                 delete QSFieldsArray[fullName];
6152         }
6153         if (Dom.get(fullName + "_results")) {
6154                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6155         }
6156
6157         enableQS(false);
6158     },
6159
6160         qsAddAddress : function(o) {
6161         if (o.name != "" && o.email1 != "")
6162         {
6163                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6164                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6165         }
6166     },
6167     /**
6168      * Returns a new instance ID, 0-index
6169      */
6170     getNewInstanceId : function() {
6171         this.currentInstanceId = this.currentInstanceId + 1;
6172         return this.currentInstanceId;
6173     },
6174
6175     /**
6176      * Takes an array of objects that contain the filename and GUID of a Note (attachment or Sugar Document) and applies the values to the compose screen.  Valid use-cases are applying an EmailTemplate or resuming a Draft Email.
6177      */
6178     loadAttachments : function(result) {
6179         var idx = SE.composeLayout.currentInstanceId;
6180
6181         if(typeof(result) == 'object') {
6182                 //jchi #20680. Clean the former template attachments;
6183                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6184                         if(basket.innerHTML != ''){
6185                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6186                                         if (btn != 'yes'){
6187                                                 basket.innerHTML = '';
6188                                         }
6189                                 });
6190                         }
6191             for(i in result) {
6192                 if(typeof result[i] == 'object') {
6193                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6194                     var bean = result[i];
6195                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6196                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6197                 }
6198             }
6199         }
6200     },
6201
6202     /**
6203      * fills drop-down values for email templates and signatures
6204      */
6205     setComposeOptions : function(idx) {
6206         // send from accounts
6207         var addressFrom = document.getElementById('addressFrom' + idx);
6208
6209         if (addressFrom.options.length <= 0) {
6210                 SE.util.emptySelectOptions(addressFrom);
6211                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6212                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6213                       var key = fromAccountOpts[id].value;
6214                       var display = fromAccountOpts[id].text;
6215                       var is_default = false;
6216                       if(key == SUGAR.default_inbound_accnt_id)
6217                         is_default = true;
6218                       var opt = new Option(display, key);
6219                       addressFrom.options.add(opt);
6220                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6221                 }
6222         }
6223
6224         // email templates
6225         var et = document.getElementById('email_template' + idx);
6226         SE.util.emptySelectOptions(et);
6227
6228         for(var key in this.emailTemplates) { // iterate through assoc array
6229             var display = this.emailTemplates[key];
6230             var opt = new Option(display, key);
6231             et.options.add(opt);
6232         }
6233
6234         // signatures
6235         var sigs = document.getElementById('signatures' + idx);
6236         SE.util.emptySelectOptions(sigs);
6237
6238         for(var key in this.signatures) { // iterate through assoc array
6239             var display = this.signatures[key];
6240             var opt = new Option(display, key);
6241
6242             if(key == SE.userPrefs.signatures.signature_default) {
6243                 opt.selected = true;
6244             }
6245
6246             sigs.options.add(opt);
6247         }
6248
6249         // html/plain email?
6250         var htmlEmail = document.getElementById('setEditor' + idx);
6251         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6252             htmlEmail.checked = true;
6253         } else {
6254                 htmlEmail.checked = false;
6255         }
6256
6257         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6258     },
6259
6260     /**
6261      * After compose screen is rendered, async call to get email body from Sugar
6262      */
6263     replyForwardEmailStage2 : function() {
6264         SE.util.clearHiddenFieldValues('emailUIForm');
6265         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6266
6267         var ieId = SE.composeLayout.replyForwardObj.ieId;
6268         var uid = SE.composeLayout.replyForwardObj.uid;
6269         var mbox = SE.composeLayout.replyForwardObj.mbox;
6270         var type = SE.composeLayout.replyForwardObj.type;
6271         var idx = SE.composeLayout.currentInstanceId;
6272
6273         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6274
6275         document.getElementById('emailSubject' + idx).value = type;
6276         document.getElementById('emailUIAction').value = 'composeEmail';
6277         document.getElementById('composeType').value = type;
6278         document.getElementById('ieId').value = ieId;
6279         document.getElementById('uid').value = uid;
6280         document.getElementById('mbox').value = mbox;
6281                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6282         var formObject = document.getElementById('emailUIForm');
6283         YAHOO.util.Connect.setForm(formObject);
6284
6285         var sendType = type;
6286         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6287     },
6288
6289     /**
6290     *  Show the hidden cc or bcc fields
6291     */
6292     showHiddenAddress: function(addrType,idx){
6293
6294         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6295         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6296                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6297                 this[addrType+'Hidden'+idx] = false;
6298
6299                 //After bcc or cc is added, move options below last addr field
6300                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6301
6302                 //If both cc and bcc hidden, remove the empty row containing text.
6303                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6304                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6305                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6306
6307                 // SE.composeLayout.resizeEditor(idx);
6308     },
6309     /**
6310     *  Hide the cc and bcc fields if they were shown.
6311     */
6312     hideHiddenAddresses: function(idx){
6313
6314         var addrTypes = ['cc','bcc'];
6315         for(var i = 0;i<addrTypes.length;i++)
6316         {
6317             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6318             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6319             this[addrTypes[i] + 'Hidden'+idx] = true
6320         }
6321
6322         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6323         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6324         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6325     }
6326 };
6327
6328 ////    END SE.composeLayout
6329 ///////////////////////////////////////////////////////////////////////////////
6330 ///////////////////////////////////////////////////////////////////////////////
6331 ////    SE.util
6332 SE.util = {
6333     /**
6334      * Cleans serialized UID lists of duplicates
6335      * @param string
6336      * @return string
6337      */
6338     cleanUids : function(str) {
6339         var seen = new Object();
6340         var clean = "";
6341         var arr = new String(str).split(",");
6342
6343         for(var i=0; i<arr.length; i++) {
6344             if(seen[arr[i]]) {
6345                 continue;
6346             }
6347
6348             clean += (clean != "") ? "," : "";
6349             clean += arr[i];
6350             seen[arr[i]] = true;
6351         }
6352
6353         return clean;
6354     },
6355
6356     /**
6357      * Clears hidden field values
6358      * @param string id ID of form element to clear
6359      */
6360     clearHiddenFieldValues : function(id) {
6361         var form = document.getElementById(id);
6362
6363         for(i=0; i<form.elements.length; i++) {
6364             if(form.elements[i].type == 'hidden') {
6365                 var e = form.elements[i];
6366                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6367                     e.value = '';
6368                 }
6369             }
6370         }
6371     },
6372
6373     /**
6374      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6375      */
6376     emptySelectOptions : function(el) {
6377         if(el) {
6378             for(i=el.childNodes.length - 1; i >= 0; i--) {
6379                 if(el.childNodes[i]) {
6380                     el.removeChild(el.childNodes[i]);
6381                 }
6382             }
6383         }
6384     },
6385
6386     /**
6387      * Returns the MBOX path in the manner php_imap expects:
6388      * ie: INBOX.DEBUG.test
6389      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6390      */
6391     generateMboxPath : function(str) {
6392         var ex = str.split("::");
6393
6394         /* we have a serialized MBOX path */
6395         if(ex.length > 1) {
6396             var start = false;
6397             var ret = '';
6398             for(var i=0; i<ex.length; i++) {
6399                 if(ex[i] == 'INBOX') {
6400                     start = true;
6401                 }
6402
6403                 if(start == true) {
6404                     if(ret != "") {
6405                         ret += ".";
6406                     }
6407                     ret += ex[i];
6408                 }
6409             }
6410         } else {
6411             /* we have a Sugar folder GUID - do nothing */
6412             return str;
6413         }
6414
6415         return ret;
6416     },
6417
6418     /**
6419      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6420      * @param HTMLElement el
6421      * @return string GUID of found element or empty on failure
6422      */
6423     getGuidFromElement : function(el) {
6424         var GUID = '';
6425         var iterations = 4;
6426         var passedEl = el;
6427
6428         // upwards
6429         for(var i=0; i<iterations; i++) {
6430             if(el) {
6431                 if(el.id.match(SE.reGUID)) {
6432                     return el.id;
6433                 } else {
6434                     el = el.parentNode;
6435                 }
6436             }
6437         }
6438
6439         return GUID;
6440     },
6441
6442     /**
6443      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6444      * @return string
6445      */
6446     getPanelId : function() {
6447         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6448     },
6449
6450     /**
6451      * wrapper to handle weirdness with IE
6452      * @param string instanceId
6453      * @return tinyMCE Controller object
6454      */
6455     getTiny : function(instanceId) {
6456         if(instanceId == '') {
6457             return null;
6458         }
6459
6460         var t = tinyMCE.getInstanceById(instanceId);
6461
6462         if(this.isIe()) {
6463             this.sleep(200);
6464             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6465         }
6466         return t;
6467     },
6468
6469     /**
6470      * Simple check for MSIE browser
6471      * @return bool
6472      */
6473     isIe : function() {
6474         var nav = new String(navigator.appVersion);
6475         if(nav.match(/MSIE/)) {
6476             return true;
6477         }
6478         return false;
6479     },
6480
6481     /**
6482      * Recursively removes an element from the DOM
6483      * @param HTMLElement
6484      */
6485     removeElementRecursive : function(el) {
6486         this.emptySelectOptions(el);
6487     },
6488
6489     /**
6490      * Fakes a sleep
6491      * @param int
6492      */
6493     sleep : function(secs) {
6494         setTimeout("void(0);", secs);
6495     },
6496
6497     /**
6498      * Converts a <select> element to an Ext.form.combobox
6499      */
6500      convertSelect : function(select) {
6501        alert('in convertSelect');
6502        if (typeof(select) == "string") {
6503            select = document.getElementById(select);
6504        }
6505      },
6506
6507      findChildNode : function (parent, property, value) {
6508          for (i in parent.children) {
6509                  var child = parent.children[i];
6510                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6511                          return child;
6512                  var searchChild = SE.util.findChildNode(child, property, value);
6513                  if (searchChild)
6514                          return searchChild;
6515          }
6516          return false;
6517      },
6518
6519      cascadeNodes : function (parent, fn, scope, args) {
6520          for (i in parent.children) {
6521                  var child = parent.children[i];
6522                  var s = scope ? scope : child;
6523                  var a = args ? args : child;
6524                  fn.call(s, a);
6525                  SE.util.cascadeNodes(child, fn, scope, args);
6526          }
6527      }
6528 };
6529
6530
6531 ////    END UTIL
6532 ///////////////////////////////////////////////////////////////////////////////
6533
6534
6535 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6536                                 
6537 /*********************************************************************************
6538  * SugarCRM Community Edition is a customer relationship management program developed by
6539  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6540  * 
6541  * This program is free software; you can redistribute it and/or modify it under
6542  * the terms of the GNU Affero General Public License version 3 as published by the
6543  * Free Software Foundation with the addition of the following permission added
6544  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6545  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6546  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6547  * 
6548  * This program is distributed in the hope that it will be useful, but WITHOUT
6549  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6550  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6551  * details.
6552  * 
6553  * You should have received a copy of the GNU Affero General Public License along with
6554  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6555  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6556  * 02110-1301 USA.
6557  * 
6558  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6559  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6560  * 
6561  * The interactive user interfaces in modified source and object code versions
6562  * of this program must display Appropriate Legal Notices, as required under
6563  * Section 5 of the GNU Affero General Public License version 3.
6564  * 
6565  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6566  * these Appropriate Legal Notices must retain the display of the "Powered by
6567  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6568  * technical reasons, the Appropriate Legal Notices must display the words
6569  * "Powered by SugarCRM".
6570  ********************************************************************************/
6571
6572
6573 if (typeof console == "undefined")
6574         console = { log: function(o) {alert(o)} };
6575
6576 var AjaxObject = {
6577         ret : '',
6578         currentRequestObject : null,
6579         //timeout : 30000, // 30 second timeout default
6580         timeout : 9999999999, // 30 second timeout default
6581         forceAbort : false,
6582         trail : new Array(),
6583
6584         /**
6585          */
6586         _reset : function() {
6587                 this.timeout = 30000;
6588                 this.forceAbort = false;
6589         },
6590
6591         folderRenameCleanup : function() {
6592                 SUGAR.email2.folders.setSugarFolders();
6593         },
6594
6595         fullSyncCleanup : function(o) {
6596                 this.folders.checkMailCleanup(o);
6597                 SUGAR.email2.settings.settingsDialog.hide();
6598         },
6599
6600         /**
6601          */
6602         composeCache : function(o) {
6603                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6604                 // get email templates and user signatures
6605                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6606
6607                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6608                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6609                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6610
6611                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6612
6613                 //Set the error array so we can notify the user when they try to hit send if any errors
6614                 //are present.  We will also notify them now (after hitting compose button).
6615                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6616
6617
6618                 //if error element is returning an array, then check the length to make sure we have error messages
6619                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6620                         //add error messages for display
6621                         for(i in ret.errorArray)
6622                                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6623                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6624                         //if error element is returning an object, and the object value is not empty or null, then display error message
6625                         for(i in ret.errorArray)
6626                                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6627                 }
6628
6629                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6630                 if(SUGAR.isIE) {
6631                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6632                         if(overlayPanel) {
6633                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6634                         }
6635                 }
6636         },
6637
6638
6639         handleDeleteSignature : function(o) {
6640                 SUGAR.hideMessageBox();
6641         var ret = YAHOO.lang.JSON.parse(o.responseText);
6642                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6643         var field = document.getElementById('signature_id');
6644                 SUGAR.email2.util.emptySelectOptions(field);
6645
6646                 for(var i in ret.signatures) { // iterate through assoc array
6647                         var opt = new Option(ret.signatures[i], i);
6648                         field.options.add(opt);
6649                 }
6650                 setSigEditButtonVisibility();
6651         },
6652
6653         /**
6654          */
6655         handleDeleteReturn : function(o) {
6656                 // force refresh ListView
6657                 SUGAR.hideMessageBox();
6658                 if(document.getElementById('focusEmailMbox')) {
6659                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6660                 }
6661
6662                 // need to display success message before calling next async call?
6663                 document.getElementById(this.target).innerHTML = o.responseText;
6664         },
6665
6666         /**
6667          */
6668     handleFailure : function(o) {
6669                 // Failure handler
6670                 SUGAR.showMessageBox('Exception occurred...', o.statusText, 'alert');
6671                 if(document.getElementById('saveButton')) {
6672                         document.getElementById('saveButton').disabled = false;
6673                 }
6674         },
6675
6676         handleReplyForward : function(o) {
6677                 var a = YAHOO.lang.JSON.parse(o.responseText);
6678                 globalA = a;
6679                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6680
6681                 document.getElementById('email_id' + idx).value = a.uid;
6682                 document.getElementById('emailSubject' + idx).value = a.name;
6683                 document.getElementById('addressTO' + idx).value = a.from;
6684                 document.getElementById('uid' + idx).value = a.uid;
6685                 if(a.cc) {
6686                         document.getElementById('addressCC' + idx).value = a.cc;
6687                         SE.composeLayout.showHiddenAddress('cc', idx);
6688                 }
6689
6690                 if(a.type) {
6691                         document.getElementById('type' + idx).value = a.type;
6692                 }
6693
6694                 // apply attachment values
6695                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6696
6697                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6698         },
6699
6700         handleReplyForwardForDraft : function(o) {
6701                 var a = YAHOO.lang.JSON.parse(o.responseText);
6702                 globalA = a;
6703                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6704
6705                 document.getElementById('email_id' + idx).value = a.uid;
6706                 document.getElementById('emailSubject' + idx).value = a.name;
6707                 document.getElementById('addressTO' + idx).value = a.to;
6708
6709                 if(a.cc) {
6710                         document.getElementById('addressCC' + idx).value = a.cc;
6711                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6712                 }
6713
6714                 if(a.bcc) {
6715                         document.getElementById('addressBCC' + idx).value = a.bcc;
6716                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6717                 }
6718
6719
6720                 if(a.type) {
6721                         document.getElementById('type' + idx).value = a.type;
6722                 }
6723
6724
6725                 // apply attachment values
6726                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6727
6728                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6729         },
6730
6731         /**
6732          */
6733         handleSuccess : function(o) {
6734                 document.getElementById(this.target).innerHTML = o.responseText;
6735                 SUGAR.hideMessageBox();
6736         },
6737
6738         /**
6739          */
6740         ieDeleteSuccess : function(o) {
6741                 SUGAR.hideMessageBox();
6742                 SUGAR.email2.accounts.refreshInboundAccountTable();
6743                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6744                 SUGAR.email2.accounts.rebuildFolderList();
6745         },
6746
6747         /**
6748          */
6749         ieSaveSuccess : function(o) {
6750                 document.getElementById('saveButton').disabled = false;
6751                 var a = YAHOO.lang.JSON.parse(o.responseText);
6752                 if (a) {
6753                         if(a.error) {
6754                                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6755                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6756                         } else {
6757                                 resp = YAHOO.lang.JSON.parse(o.responseText);
6758                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6759                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6760                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6761                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6762                         }
6763                 } else {
6764                      SUGAR.hideMessageBox();
6765                      SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6766                 }
6767
6768         },
6769
6770         /**
6771          */
6772         loadAttachments : function(o) {
6773                 var result = YAHOO.lang.JSON.parse(o.responseText);
6774
6775                 SUGAR.email2.composeLayout.loadAttachments(result);
6776         },
6777
6778         /**
6779          */
6780         loadSignature : function(o) {
6781                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6782                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6783                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6784         },
6785
6786         /**
6787          * Follow up to mark email read|unread|flagged
6788          */
6789         markEmailCleanup : function(o) {
6790                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6791                 if (!ret['status']) {
6792                 SUGAR.hideMessageBox();
6793                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6794                 } else {
6795                         SUGAR.email2.contextMenus.markEmailCleanup();
6796                 } // else
6797         },
6798
6799         /**
6800          */
6801         rebuildShowFolders : function(o) {
6802                 var t = YAHOO.lang.JSON.parse(o.responseText);
6803                 var show = document.getElementById('ieAccountListShow');
6804
6805                 SUGAR.email2.util.emptySelectOptions(show);
6806
6807                 for(i=0; i<t.length; i++) { // iterate through assoc array
6808                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6809                         opt.selected = t[i].selected;
6810                         show.options.add(opt);
6811                 }
6812
6813                 SUGAR.email2.accounts.renderTree();
6814         },
6815         /**
6816          */
6817         saveListViewSortOrderPart2 : function() {
6818                 // create the JSON string the func expects
6819                 focusFolderPath = '[ "Home", "' + ieName + '"';
6820
6821                 var f = new String(focusFolder);
6822                 var fEx = f.split('.');
6823
6824                 for(i=0; i<fEx.length; i++) {
6825                         focusFolderPath += ', "' + fEx[i] +'"'
6826                 }
6827
6828                 focusFolderPath += ']';
6829
6830                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6831                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6832         },
6833
6834         /**
6835          *
6836          */
6837         sendEmailCleanUp : function(o) {
6838         var ret;
6839         SUGAR.hideMessageBox();
6840
6841         try {
6842             ret = YAHOO.lang.JSON.parse(o.responseText);
6843             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6844             //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6845         } catch(err) {
6846             if (o.responseText) {
6847                 SUGAR.showMessageBox(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6848                     }
6849             // Else we have an error here.
6850         }        
6851
6852                 if (typeof(SE.grid) != 'undefined')
6853                         SE.listView.refreshGrid();
6854                 //Disabled while address book is disabled
6855
6856                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6857                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6858                 //close the shortcut bar menu
6859                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6860                         if(action_sugar_grp1 == 'DetailView') {
6861                                 showSubPanel('history',null,true);
6862                         } else if(action_sugar_grp1 == 'quickcreate') {
6863                                 closeEmailOverlay();
6864                         }
6865                 }
6866
6867         },
6868
6869         ieSendSuccess : function(o) {
6870                 SUGAR.hideMessageBox();
6871                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6872         },
6873
6874         /**
6875          */
6876         settingsFolderRefresh : function(o) {
6877                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6878                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6879                 var user = document.getElementById('userFolders');
6880
6881                 SUGAR.email2.util.emptySelectOptions(user);
6882
6883                 for(i=0; i<ret.userFolders.length; i++) {
6884                         var display = ret.userFolders[i].name;
6885                         var value = ret.userFolders[i].id;
6886                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6887                         var opt = new Option(display, value, selected);
6888                         opt.selected = selected;
6889                         user.options.add(opt);
6890                 }
6891         },
6892
6893         /**
6894          */
6895         startRequest : function(callback, args, forceAbort) {
6896                 if(this.currentRequestObject != null) {
6897                         if(this.forceAbort == true) {
6898                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6899                         }
6900                 }
6901                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6902                 this._reset();
6903         },
6904
6905         requestInProgress : function() {
6906                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6907         },
6908
6909         /**
6910          */
6911         updateFolderSubscriptions : function() {
6912                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6913                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6914                 SUGAR.hideMessageBox();
6915         },
6916
6917         /**
6918          */
6919         updateFrameFolder : function() {
6920                 SUGAR.email2.folders.checkEmailAccounts();
6921         },
6922
6923         /**
6924          */
6925         updateUserPrefs : function(o) {
6926                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6927                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6928         },
6929
6930         /**
6931          */
6932         uploadAttachmentSuccessful : function(o) {
6933                 // clear out field
6934                 document.getElementById('email_attachment').value = '';
6935                 
6936                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6937                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6938                 var overall = document.getElementById('addedFiles' + idx);
6939                 var index = overall.childNodes.length;
6940                 var out =
6941                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6942                                 // remove button
6943                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6944                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6945                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6946                                 // file icon
6947                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6948                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6949                                 // hidden id field
6950                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6951                                 // file name
6952                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6953                                 "<br/>" +
6954                         "</div>";
6955                 overall.innerHTML += out;
6956                 if(SUGAR.email2.util.isIe()) {
6957                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6958                 }
6959
6960                 // hide popup
6961                 SUGAR.email2.addFileDialog.hide();
6962                 // focus attachments
6963                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6964         }
6965 };
6966
6967
6968 ///////////////////////////////////////////////////////////////////////////
6969 ////    PER MODULE CALLBACK OBJECTS
6970 AjaxObject.accounts = {
6971         saveOutboundCleanup : function(o) {
6972                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6973                 SUGAR.email2.accounts.outboundDialog.hide();
6974                 var id = o.responseText;
6975                 SUGAR.email2.accounts.newAddedOutboundId = id;
6976                 },
6977         saveDefaultOutboundCleanup: function(o){
6978
6979         },
6980         callbackEditOutbound : {
6981                 success : function(o)
6982                 {
6983                         var ret = YAHOO.lang.JSON.parse(o.responseText);
6984                         // show overlay
6985                         SUGAR.email2.accounts.showAddSmtp();
6986
6987                         // fill values
6988                         document.getElementById("mail_id").value = ret.id;
6989                         document.getElementById("type").value = ret.type;
6990                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6991                         document.getElementById("mail_name").value = ret.name;
6992                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6993                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6994                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6995                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6996                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6997                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6998                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6999
7000             if(ret.type == 'system-override') {
7001                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
7002                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
7003             }
7004             else {
7005                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
7006                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
7007             }
7008             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
7009
7010                 },
7011                 failure : AjaxObject.handleFailure,
7012                 timeout : AjaxObject.timeout,
7013                 scope   : AjaxObject
7014         },
7015         callbackDeleteOutbound : {
7016                 success : function(o) {
7017                     var ret = YAHOO.lang.JSON.parse(o.responseText);
7018                     if(ret.is_error)
7019                     {
7020                         if(confirm(ret.error_message))
7021                 {
7022                     SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
7023                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7024                 }
7025                 else
7026                     SUGAR.hideMessageBox();
7027                     }
7028                     else
7029                     {
7030                              SUGAR.hideMessageBox();
7031                              SUGAR.email2.accounts.refreshOuboundAccountTable();
7032                     }
7033                 },
7034
7035                 failure : AjaxObject.handleFailure,
7036                 timeout : AjaxObject.timeout,
7037                 scope   : AjaxObject
7038         },
7039
7040         callbackCheckMailProgress : {
7041            success : function(o) {
7042                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7043                    SUGAR.email2.accounts.totalMsgCount = -1;
7044                }
7045
7046                //Check for server timeout / errors
7047                var ret = YAHOO.lang.JSON.parse(o.responseText);
7048                var done = false;
7049
7050                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7051                    SUGAR.hideMessageBox();
7052                    SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7053                    SUGAR.email2.accounts.totalMsgCount = -1;
7054                //SUGAR.email2.folders.rebuildFolders();
7055                done = true;
7056                }
7057
7058                var currIeId = ret['ieid'];
7059
7060
7061                var serverCount = ret.count;
7062
7063                if (ret['status'] == 'done') {
7064                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7065                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7066                            //We are all done
7067                            done = true;
7068                            break;
7069                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7070                            //Go to next account
7071                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
7072                            ret.count = 0;
7073                            SUGAR.email2.accounts.totalMsgCount = -1;
7074                            break;
7075                        }
7076                    }
7077                }
7078                else if (ret.mbox && ret.totalcount && ret.count) {
7079                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7080                    if (ret.count >= ret.totalcount) {
7081                        serverCount = 0;
7082                    }
7083                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7084                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7085                } else {
7086                        SUGAR.hideMessageBox();
7087                SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7088                SUGAR.email2.accounts.totalMsgCount = -1;
7089                done = true;
7090                    }
7091
7092                if (done) {
7093                    SUGAR.email2.accounts.totalMsgCount = -1;
7094                    SUGAR.hideMessageBox();
7095                    SUGAR.email2.folders.rebuildFolders();
7096                    SE.listView.refreshGrid();
7097                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7098                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7099                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7100                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7101            } else {
7102                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7103                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7104                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7105                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7106                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7107                }
7108            },
7109            failure : AjaxObject.handleFailure,
7110        timeout : AjaxObject.timeout,
7111        scope   : AjaxObject
7112         }
7113 };
7114
7115 ///////////////////////////////////////////////////////////////////////////////
7116 ////    COMPOSE LAYOUT
7117 AjaxObject.composeLayout = {
7118         /**
7119          * Populates the record id
7120          */
7121     saveDraftCleanup : function(o) {
7122         var ret;
7123         SUGAR.hideMessageBox();
7124
7125         try {
7126             ret = YAHOO.lang.JSON.parse(o.responseText);
7127             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7128         } catch(err) {
7129             if (o.responseText) {
7130                 SUGAR.showMessageBox(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7131             }
7132         }
7133     }
7134 };
7135
7136 AjaxObject.composeLayout.callback = {
7137         saveDraft : {
7138                 success : AjaxObject.composeLayout.saveDraftCleanup,
7139                 failure : AjaxObject.handleFailure,
7140                 timeout : AjaxObject.timeout,
7141                 scope   : AjaxObject
7142         }
7143 };
7144
7145 AjaxObject.detailView = {
7146         /**
7147          * Pops-up a printable view of an email
7148          */
7149         displayPrintable : function(o) {
7150                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7151                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7152                 // 2 below must be in global context
7153                 meta = ret.meta;
7154                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7155                 email = ret.meta.email;
7156                 if (typeof(email.cc) == 'undefined') {
7157                   email.cc = "";
7158                 }
7159
7160                 var out = displayTemplate.exec({
7161                         'app_strings'   : app_strings,
7162                         'theme'                 : theme,
7163                         'idx'                   : 'Preview',
7164                         'meta'                  : meta,
7165                         'email'                 : meta.email
7166                 });
7167
7168                 // open popup window
7169                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7170                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7171
7172                 popup.document.write(out);
7173                 popup.document.close();
7174         },
7175
7176         /**
7177          * Takes formatted response and creates a modal pop-over containing a title and content
7178          */
7179         displayView : function(o) {
7180                 var SED = SUGAR.email2.detailView;
7181                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7182
7183                 if(!SED.viewDialog) {
7184                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7185                                 modal:true,
7186                 visible:true,
7187                 fixedcenter:true,
7188                 constraintoviewport: true,
7189                                 shadow  : true
7190                         });
7191             SED.viewDialog.renderEvent.subscribe(function() {
7192                 var content = this.body.firstChild;
7193                 var viewH = YAHOO.util.Dom.getViewportHeight();
7194                 if (content) {
7195                         this.body.style.overflow = "auto";
7196                         this.body.style.width = "800px";
7197                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7198                 }
7199             }, SED.viewDialog);
7200                 } // end lazy load
7201                 SED.viewDialog.setHeader(ret.title);
7202                 SED.viewDialog.setBody(ret.html);
7203                 SED.viewDialog.render();
7204                 SED.viewDialog.show();
7205         },
7206
7207         /**
7208          * Generates a modal popup to populate with the contents of bean's full EditView
7209          */
7210         showQuickCreateForm : function(o) {
7211                 var SED = SUGAR.email2.detailView;
7212                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7213
7214                 if(!SED.quickCreateDialog) {
7215                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7216                                 modal:true,
7217                                 visible:true,
7218                 fixedcenter:true,
7219                 constraintoviewport: true,
7220                                 shadow  : true
7221                         });
7222
7223             SED.quickCreateDialog.renderEvent.subscribe(function() {
7224                 var viewH = YAHOO.util.Dom.getViewportHeight();
7225                 var contH = 0;
7226                 for (var i in this.body.childNodes) {
7227                         if (this.body.childNodes[i].clientHeight) {
7228                                 contH += this.body.childNodes[i].clientHeight;
7229                         } else if (this.body.childNodes[i].offsetHeight) {
7230                                 contH += this.body.childNodes[i].offsetHeight;
7231                         } // if
7232                 }
7233                         this.body.style.width = "800px";
7234                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7235                         this.body.style.overflow = "auto";
7236             }, SED.quickCreateDialog);
7237
7238             SED.quickCreateDialog.hideEvent.subscribe(function(){
7239                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7240                                 /*for(var qsField in qsFields){
7241                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7242                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7243                                 }*/
7244                         });
7245             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7246                 } // end lazy load
7247                 if (ret.html) {
7248                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7249                 }
7250                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7251                 SED.quickCreateDialog.render();
7252                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7253
7254                 SED.quickCreateDialog.ieId = ret.ieId;
7255                 SED.quickCreateDialog.uid = ret.uid;
7256         SED.quickCreateDialog.mbox = ret.mbox;
7257         SED.quickCreateDialog.qcmodule = ret.module;
7258
7259         SED.quickCreateDialog.show();
7260
7261                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7262                 if (editForm) {
7263                   editForm.module.value = 'Emails';
7264                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7265                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7266                   var instId = ret.module + count;
7267                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7268                   SED.quickCreateEmailCallback = function(instId, tableId) {
7269                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7270                           if (typeof(eaw) == "undefined")
7271                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7272                                                 + instId + "','" + tableId + "');", 100);
7273                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7274                   }
7275                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7276                                         + instId + "','" + tableId + "');", 100);
7277                 }
7278         },
7279
7280         saveQuickCreateForm : function(o) {
7281             SUGAR.hideMessageBox();
7282                 SUGAR.email2.detailView.quickCreateDialog.hide();
7283                 validate['EditView'] = [ ];
7284         },
7285
7286         saveQuickCreateFormAndReply : function(o) {
7287         SUGAR.hideMessageBox();
7288         var ret = YAHOO.lang.JSON.parse(o.responseText);
7289         SUGAR.email2.detailView.quickCreateDialog.hide();
7290         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7291         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7292         if (ret) {
7293             var emailID = ret.id;
7294             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7295         } else {
7296             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7297         }
7298         //Cean the validate cache to prevent errors on the next call
7299         validate['EditView'] = [ ];
7300     },
7301
7302         saveQuickCreateFormAndAddToAddressBook : function(o) {
7303            SUGAR.hideMessageBox();
7304                 SUGAR.email2.detailView.quickCreateDialog.hide();
7305                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7306                 validate['EditView'] = [ ];
7307         },
7308
7309         handleAssignmentDialogAssignAction : function() {
7310
7311
7312             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7313
7314             var dist = 'direct';
7315             var users = false;
7316             var rules = false;
7317             var get = "";
7318             var found_teams = false;
7319             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7320             if(!found_teams && assign_user_id == '' )
7321             {
7322                 alert(warning_message);
7323                 return;
7324             }
7325
7326             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7327             var uids = "";
7328             for(i=0; i<emailUids.length; i++) {
7329                 if(uids != '') {
7330                     uids += app_strings.LBL_EMAIL_DELIMITER;
7331                 }
7332                 uids += emailUids[i];
7333             }
7334
7335             var row = SUGAR.email2.grid.getSelectedRows()[0];
7336             var data = SUGAR.email2.grid.getRecord(row).getData();
7337             var ieid = data.ieId;
7338             var mbox = data.mbox;
7339             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7340             SUGAR.email2.contextMenus.assignToDialogue.hide();
7341             SUGAR.showMessageBox('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7342
7343         },
7344
7345         handleAssignmentDialogDeleteAction : function() {
7346                 // TO pass list of UIDS/emailIds
7347                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7348                 var row = SUGAR.email2.grid.getSelections()[0];
7349                 var ieid = row.data.ieId;
7350             var mbox = row.data.mbox;
7351         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7352         SUGAR.email2.contextMenus.assignmentDialog.hide();
7353                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7354
7355                 // AJAX Call
7356
7357         },
7358
7359         showEmailDetailView : function(o) {
7360         SUGAR.hideMessageBox();
7361         var SED = SUGAR.email2.detailView;
7362                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7363
7364                 if(!SED.quickCreateDialog) {
7365                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7366                                 modal:true,
7367                                 visible:true,
7368                 //fixedcenter:true,
7369                 constraintoviewport: true,
7370                 draggable: true,
7371                                 autofillheight: "body",
7372                                 shadow  : true
7373                         });
7374                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7375                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7376                 var contH = 0;
7377                 for (var i in this.body.childNodes) {
7378                         if (this.body.childNodes[i].offsetHeight)
7379                                 contH += this.body.childNodes[i].offsetHeight;
7380                 }
7381                         this.body.style.overflow = "auto";
7382                         this.body.style.width = "800px";
7383                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7384                         this.center();
7385             }, SED.quickCreateDialog);
7386                 }
7387                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7388                 SED.quickCreateDialog.setBody(ret.html);
7389                 SED.quickCreateDialog.render();
7390         SUGAR.util.evalScript(ret.html);
7391         SED.quickCreateDialog.show();
7392         },
7393
7394         showAssignmentDialogWithData : function(o) {
7395         var SEC = SUGAR.email2.contextMenus;
7396                 SUGAR.hideMessageBox();
7397         var ret = YAHOO.lang.JSON.parse(o.responseText);
7398         if (!SEC.assignmentDialog) {
7399                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7400                         visible:false,
7401                 fixedcenter:true,
7402                 constraintoviewport: true,
7403                         modal   : true
7404                 });
7405                 SEC.assignmentDialog.setBody("");
7406                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7407                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7408                 var iev = YAHOO.util.Dom.get("Distribute");
7409                 if (iev) {
7410                         this.body.style.width = "700px";
7411                 }
7412             },  SEC.assignmentDialog);
7413                 SEC.assignmentDialog.render();
7414         }
7415         SEC.assignmentDialog.setBody(ret);
7416         SEC.assignmentDialog.render();
7417         validate = [];
7418         SEC.assignmentDialog.show();
7419         SUGAR.util.evalScript(ret);
7420         },
7421
7422         showImportForm : function(o) {
7423                 var SED = SUGAR.email2.detailView;
7424                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7425         
7426         document.getElementById('quickCreateContent').innerHTML = "";
7427         SUGAR.hideMessageBox();
7428         if (!ret) {
7429             return false;
7430         }
7431
7432         if(!SED.importDialog) {
7433             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7434                 modal:true,
7435                 visible:false,
7436                 fixedcenter:true,
7437                 constraintoviewport: true,
7438                 buttons : [{
7439                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7440                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7441                 }]//,
7442                 //scroll : true
7443             });
7444             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7445             SED.importDialog.setBody("");
7446             SED.importDialog.hideEvent.subscribe(function(){
7447                 for(var i in QSFieldsArray) {
7448                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7449                                 QSFieldsArray[i].destroy();
7450                                 delete QSFieldsArray[i];
7451                         }
7452                         if (QSProcessedFieldsArray[i]) {
7453                                 QSProcessedFieldsArray[i] = false;
7454                         } // if
7455                                 }
7456             });
7457             SED.importDialog.renderEvent.subscribe(function() {
7458                 var iev = YAHOO.util.Dom.get("ImportEditView");
7459                 if (iev) {
7460                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7461                         this.body.style.width = "600px";
7462                 }
7463             }, SED.importDialog);
7464             SED.importDialog.render();
7465         } // end lazy load
7466         SED.importDialog.setBody(ret.html);
7467         SED.importDialog.ret = ret;
7468         SUGAR.util.evalScript(ret.html);
7469         SED.importDialog.render();
7470         validate = [];
7471         SED.importDialog.show();
7472         SED.importDialog.focusFirstButton();
7473     },
7474     getImportAction : function(ret) {
7475         if (!check_form('ImportEditView')) return false;
7476         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7477                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7478                 return false;
7479         } // if
7480                 var get = "";
7481         var editView = document.getElementById('ImportEditView');
7482         if (editView.assigned_user_id != null) {
7483             get = get + "&user_id=" + editView.assigned_user_id.value
7484             //var user_id = editView.assigned_user_id.value;
7485         }
7486         var parent_id = editView.parent_id.value;
7487         var parent_type = editView.parent_type.value;
7488         var row = SUGAR.email2.grid.getSelectedRows()[0];
7489         row = SUGAR.email2.grid.getRecord(row);
7490         var data = row.getData();
7491         var ieId = data.ieId;
7492         var mbox = data.mbox;
7493         var serverDelete = editView.serverDelete.checked;
7494         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7495         var uids = "";
7496         for(i=0; i<emailUids.length; i++) {
7497             if(uids != '') {
7498                 uids += app_strings.LBL_EMAIL_DELIMITER;
7499             }
7500             uids += emailUids[i];
7501         }
7502
7503         var action = 'importEmail&uid=';
7504         if (ret.move) {
7505             action = 'moveEmails';
7506             action = action + '&sourceFolder=' + ret['srcFolder'];
7507             action = action + '&sourceIeId=' + ret['srcIeId'];
7508             action = action + '&destinationFolder=' + ret['dstFolder'];
7509             action = action + '&destinationIeId=' + ret['dstIeId'];
7510             action = action + '&emailUids=';
7511         }
7512         if (action.search(/importEmail/) != -1) {
7513             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7514         } else {
7515             SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7516         }
7517
7518         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7519         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7520         SUGAR.email2.detailView.importDialog.hide();
7521         document.getElementById('importDialogContent').innerHTML = "";
7522
7523     },
7524     showRelateForm : function(o) {
7525         var SED = SUGAR.email2.detailView;
7526         var ret = YAHOO.lang.JSON.parse(o.responseText);
7527         document.getElementById('quickCreateContent').innerHTML = "";
7528         SUGAR.hideMessageBox();
7529         if (!ret) {
7530             return false;
7531         }
7532         dialog_loaded = true;
7533
7534         if(!SED.relateDialog) {
7535             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7536                                 modal:true,
7537                                 visible:true,
7538                 fixedcenter:true,
7539                 width: '800px',
7540                 constraintoviewport: true,
7541                                 buttons : [{
7542                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7543                                         if (!check_form('RelateEditView')) return false;
7544                                         var get = "";
7545                         var editView = document.getElementById('RelateEditView');
7546                         var parent_id = editView.parent_id.value;
7547                         var parent_type = editView.parent_type.value;
7548                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7549                         row  = SUGAR.email2.grid.getRecord(row);
7550                         var ieId = row.getData().ieId;
7551                         var mbox = row.getData().mbox;
7552                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7553                         var uids = "";
7554                         for(i=0; i<emailUids.length; i++) {
7555                             if(uids != '') {
7556                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7557                             }
7558                             uids += emailUids[i];
7559                         }
7560                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7561                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7562                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7563                         SED.relateDialog.hide();
7564                         document.getElementById('relateDialogContent').innerHTML = "";
7565                         }
7566                 }]
7567                         });
7568
7569             SED.relateDialog.hideEvent.subscribe(function(){
7570                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7571                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7572                         delete QSFieldsArray['ImportEditView_parent_name'];
7573                 } // if
7574                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7575                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7576                                 } // if
7577             });
7578
7579             SED.relateDialog.renderEvent.subscribe(function() {
7580                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7581                 var contH = 0;
7582                 for (var i in this.body.childNodes) {
7583                         if (this.body.childNodes[i].clientHeight)
7584                                 contH += this.body.childNodes[i].clientHeight;
7585                 }
7586             }, SED.relateDialog);
7587             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7588                 } // end lazy load
7589
7590         SED.relateDialog.setBody(ret.html);
7591         SED.relateDialog.render();
7592         SUGAR.util.evalScript(ret.html);
7593         SED.relateDialog.show();
7594     }
7595 };
7596 /**
7597  * DetailView callbacks
7598  */
7599 AjaxObject.detailView.callback = {
7600         emailDetail : {
7601                 success : function(o) {
7602                         SUGAR.email2.o = o;
7603                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7604                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7605                 },
7606                 argument: [targetDiv],
7607                 failure : AjaxObject.handleFailure,
7608                 timeout : 0,
7609                 scope   : AjaxObject
7610         },
7611         emailPreview : {
7612                 success : function(o) {
7613                         SUGAR.email2.o = o;
7614                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7615                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7616                 },
7617                 failure : AjaxObject.handleFailure,
7618                 timeout : 0,
7619                 scope   : AjaxObject
7620         },
7621         viewPrint : {
7622                 success : AjaxObject.detailView.displayPrintable,
7623                 failure : AjaxObject.handleFailure,
7624                 timeout : AjaxObject.timeout,
7625                 scope   : AjaxObject
7626         },
7627         viewRaw : {
7628                 success : AjaxObject.detailView.displayView,
7629                 failure : AjaxObject.handleFailure,
7630                 timeout : AjaxObject.timeout,
7631                 scope   : AjaxObject
7632         }
7633 };
7634
7635
7636
7637
7638
7639 AjaxObject.folders = {
7640         /**
7641          * check-mail post actions
7642          */
7643         checkMailCleanup : function(o) {
7644                 SUGAR.hideMessageBox();
7645                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7646
7647                 // refresh focus ListView
7648                 SE.listView.refreshGrid();
7649                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7650         },
7651
7652         /**
7653          */
7654         rebuildFolders : function(o) {
7655                 SUGAR.hideMessageBox();
7656
7657                 var data = YAHOO.lang.JSON.parse(o.responseText);
7658
7659                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7660                 SUGAR.email2.folders.setSugarFolders();
7661         }
7662 };
7663 AjaxObject.folders.callback = {
7664         checkMail : {
7665                 success : AjaxObject.folders.checkMailCleanup,
7666                 failure : AjaxObject.handleFailure,
7667                 timeout : 600000, // 5 mins
7668                 scope   : AjaxObject
7669         }
7670 }
7671
7672 AjaxObject.rules = {
7673         loadRulesForSettings : function(o) {
7674                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7675                 // assume we have the class we need
7676                 SUGAR.routing.getStrings();
7677                 SUGAR.routing.getDependentDropdowns();
7678         }
7679 };
7680 ////    END PER MODULE CALLBACK OBJECTS
7681 ///////////////////////////////////////////////////////////////////////////
7682
7683
7684 var callback = {
7685         success : AjaxObject.handleSuccess,
7686         failure : AjaxObject.handleFailure,
7687         timeout : AjaxObject.timeout,
7688         scope   : AjaxObject
7689 };
7690 var callbackAccount = {
7691         success : AjaxObject.ieSaveSuccess,
7692         failure : AjaxObject.handleFailure,
7693         timeout : AjaxObject.timeout,
7694         scope   : AjaxObject
7695 };
7696 var callbackAccountDelete = {
7697         success : AjaxObject.ieDeleteSuccess,
7698         failure : AjaxObject.handleFailure,
7699         timeout : AjaxObject.timeout,
7700         scope   : AjaxObject
7701 };
7702 var callbackOutboundTest = {
7703         success : AjaxObject.ieSendSuccess,
7704         failure : AjaxObject.handleFailure,
7705         timeout : AjaxObject.timeout,
7706         scope   : AjaxObject
7707 };
7708
7709
7710
7711 var callbackTeamInfoForSettings = {
7712 success : function (o) {
7713         var data = YAHOO.lang.JSON.parse(o.responseText);
7714         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7715 },
7716 failure : AjaxObject.handleFailure,
7717 timeout : AjaxObject.timeout,
7718 scope   : AjaxObject
7719
7720 };
7721
7722 var callbackStatusForImport = {
7723 success : function (o) {
7724         SUGAR.hideMessageBox();
7725         if (o.responseText != "")  {
7726                 var statusString = "";
7727                 var data = YAHOO.lang.JSON.parse(o.responseText);
7728                 for(i=0; i<data.length; i++) {
7729                         statusString = statusString + data[i] + '<br/>';
7730                 }
7731                 SUGAR.showMessageBox(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7732         }
7733         SE.listView.refreshGrid();
7734
7735 },
7736 failure : AjaxObject.handleFailure,
7737 timeout : AjaxObject.timeout,
7738 scope   : AjaxObject
7739
7740 };
7741 var callbackComposeCache = {
7742         success : AjaxObject.composeCache,
7743         failure : AjaxObject.handleFailure,
7744         timeout : AjaxObject.timeout,
7745         scope   : AjaxObject
7746 };
7747 var callbackDelete = {
7748         success : AjaxObject.handleDeleteReturn,
7749         failure : AjaxObject.handleFailure,
7750         timeout : AjaxObject.timeout,
7751         scope   : AjaxObject
7752 };
7753 var callbackEmailDetailMultiple = {
7754         success : function(o) {
7755                 SUGAR.hideMessageBox();
7756         var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7757                 var ret = new Object();
7758
7759                 for(var i=0; i<retMulti.length; i++) {
7760                         ret = retMulti[i];
7761
7762                         SUGAR.email2._setDetailCache(ret);
7763                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7764                 }
7765         },
7766         failure : AjaxObject.handleFailure,
7767         timeout : 0,
7768         scope   : AjaxObject
7769 };
7770 var callbackListViewSortOrderChange = {
7771         success : AjaxObject.saveListViewSortOrderPart2,
7772         failure : AjaxObject.handleFailure,
7773         timeout : AjaxObject.timeout,
7774         scope   : AjaxObject,
7775         argument        : [ieId, ieName, focusFolder]
7776 };
7777 var callbackEmptyTrash = {
7778         success : function(o) {
7779                 SUGAR.hideMessageBox();
7780                 AjaxObject.folderRenameCleanup;
7781         },
7782         failure : AjaxObject.handleFailure,
7783         timeout : AjaxObject.timeout,
7784         scope   : AjaxObject
7785 };
7786 var callbackClearCacheFiles = {
7787         success : function(o) {
7788                 SUGAR.hideMessageBox();
7789         },
7790         failure : AjaxObject.handleFailure,
7791         timeout : AjaxObject.timeout,
7792         scope   : AjaxObject
7793 };
7794 var callbackFolderRename = {
7795         success : function(o) {SUGAR.hideMessageBox();SUGAR.email2.folders.rebuildFolders();},
7796         failure : AjaxObject.handleFailure,
7797         timeout : AjaxObject.timeout,
7798         scope   : AjaxObject
7799 };
7800 var callbackFolderDelete = {
7801         success : function(o) {
7802                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7803                 if (ret.status) {
7804                     if (ret.folder_id) {
7805                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7806                         if(node)
7807                                 SUGAR.email2.tree.removeNode(node, true);
7808                     } else if (ret.ieId && ret.mbox) {
7809                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7810                         if(node)
7811                                 SUGAR.email2.tree.removeNode(node, true);
7812                     }
7813                         SUGAR.hideMessageBox();
7814                         //SUGAR.email2.folders.loadSettingFolder();
7815                 } else {
7816                         SUGAR.hideMessageBox();
7817                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7818                 } // else
7819         },
7820         failure : AjaxObject.handleFailure,
7821         timeout : AjaxObject.timeout,
7822         scope   : AjaxObject
7823 };
7824 var callbackFolderSave = {
7825         success : function(o) {
7826                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7827
7828                 switch(ret.action) {
7829                         case 'newFolderSave':
7830                                 SUGAR.email2.folders.rebuildFolders();
7831                         break;
7832                 }
7833         },
7834         failure : AjaxObject.handleFailure,
7835         timeout : AjaxObject.timeout,
7836         scope   : AjaxObject
7837 };
7838 var callbackFolderSubscriptions = {
7839         success : AjaxObject.updateFolderSubscriptions,
7840         failure : AjaxObject.handleFailure,
7841         timeout : AjaxObject.timeout,
7842         scope   : AjaxObject
7843 };
7844 var callbackFolderUpdate = {
7845         success : AjaxObject.updateFrameFolder,
7846         failure : AjaxObject.handleFailure,
7847         timeout : AjaxObject.timeout,
7848         scope   : AjaxObject
7849 };
7850 var callbackFolders = {
7851         success : AjaxObject.folders.rebuildFolders,
7852         //success : void(true),
7853         failure : AjaxObject.handleFailure,
7854         timeout : AjaxObject.timeout,
7855         scope   : AjaxObject
7856 };
7857 var callbackFullSync = {
7858         success : AjaxObject.fullSyncCleanup,
7859         failure : AjaxObject.handleFailure,
7860         timeout : 9999999999999,
7861         scope   : AjaxObject
7862 };
7863 var callbackGeneric = {
7864         success : function() {
7865                 SUGAR.hideMessageBox();
7866         },
7867         failure : AjaxObject.handleFailure,
7868         timeout : AjaxObject.timeout,
7869         scope   : AjaxObject
7870 };
7871 var callbackIeAccountRetrieve = {
7872         success : function(o) {
7873                 // return JSON encoding
7874                 SUGAR.hideMessageBox();
7875                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7876                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7877         },
7878         failure : AjaxObject.handleFailure,
7879         timeout : AjaxObject.timeout,
7880         scope   : AjaxObject
7881 };
7882 var callbackImportOneEmail = {
7883         success :  AjaxObject.detailView.showImportForm,
7884         failure : AjaxObject.handleFailure,
7885         timeout : AjaxObject.timeout,
7886         scope   : AjaxObject
7887 };
7888 var callbackRelateEmail = {
7889     success : AjaxObject.detailView.showRelateForm,
7890     failure : AjaxObject.handleFailure,
7891     timeout : AjaxObject.timeout,
7892     scope   : AjaxObject
7893 }
7894 var callbackEmailDetailView = {
7895     success : AjaxObject.detailView.showEmailDetailView,
7896     failure : AjaxObject.handleFailure,
7897     timeout : AjaxObject.timeout,
7898     scope   : AjaxObject
7899 }
7900 var callbackAssignmentDialog = {
7901         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7902         failure : AjaxObject.handleFailure,
7903         timeout : AjaxObject.timeout,
7904         scope   : AjaxObject
7905 };
7906 var callbackAssignmentAction = {
7907         success :  function(o) {
7908                 SE.listView.refreshGrid();
7909                 SUGAR.hideMessageBox();
7910                 if(o.responseText != '') {
7911                SUGAR.showMessageBox('Assignment action result', o.responseText, 'alert');
7912             } // if
7913         } ,
7914         failure : AjaxObject.handleFailure,
7915         timeout : AjaxObject.timeout,
7916         scope   : AjaxObject
7917 };
7918 var callbackMoveEmails = {
7919         success :  function(o) {
7920             SE.listView.refreshGrid();
7921                 SUGAR.hideMessageBox();
7922                 if(o.responseText != '') {
7923                SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7924             } // if
7925         } ,
7926         failure : AjaxObject.handleFailure,
7927         timeout : AjaxObject.timeout,
7928         scope   : AjaxObject
7929 };
7930 var callbackLoadAttachments = {
7931         success : AjaxObject.loadAttachments,
7932         failure : AjaxObject.handleFailure,
7933         timeout : AjaxObject.timeout,
7934         scope   : AjaxObject
7935 };
7936 var callbackLoadRules = {
7937         success : AjaxObject.rules.loadRulesForSettings,
7938         failure : AjaxObject.handleFailure,
7939         timeout : AjaxObject.timeout,
7940         scope   : AjaxObject
7941 };
7942 var callbackLoadSignature = {
7943         success : AjaxObject.loadSignature,
7944         failure : AjaxObject.handleFailure,
7945         timeout : AjaxObject.timeout,
7946         scope   : AjaxObject
7947 };
7948 var callbackDeleteSignature = {
7949         success : AjaxObject.handleDeleteSignature,
7950         failure : AjaxObject.handleFailure,
7951         timeout : AjaxObject.timeout,
7952         scope   : AjaxObject
7953 };
7954 /*var callbackMoveEmails = {
7955     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7956     failure : AjaxObject.handleFailure,
7957     timeout : AjaxObject.timeout,
7958     scope   : AjaxObject
7959 }*/
7960 var callbackOutboundSave = {
7961         success : AjaxObject.accounts.saveOutboundCleanup,
7962         failure : AjaxObject.handleFailure,
7963         timeout : AjaxObject.timeout,
7964         scope   : AjaxObject
7965 };
7966 var callbackDefaultOutboundSave = {
7967         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7968         failure : AjaxObject.handleFailure,
7969         timeout : AjaxObject.timeout,
7970         scope   : AjaxObject
7971 };
7972 var callbackQuickCreate = {
7973         success : AjaxObject.detailView.showQuickCreateForm,
7974         failure : AjaxObject.handleFailure,
7975         timeout : AjaxObject.timeout,
7976         scope   : AjaxObject
7977 };
7978 var callbackQuickCreateSave = {
7979         success : AjaxObject.detailView.saveQuickCreateForm,
7980         failure : AjaxObject.handleFailure,
7981         timeout : AjaxObject.timeout,
7982         scope   : AjaxObject
7983 };
7984 var callbackQuickCreateSaveAndAddToAddressBook = {
7985         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7986         failure : AjaxObject.handleFailure,
7987         timeout : AjaxObject.timeout,
7988         scope   : AjaxObject
7989 };
7990 var callbackQuickCreateSaveAndReply = {
7991     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7992     failure : AjaxObject.handleFailure,
7993     timeout : AjaxObject.timeout,
7994     scope   : AjaxObject
7995 }
7996 var callbackQuickCreateSaveAndReplyCase = {
7997     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7998     failure : AjaxObject.handleFailure,
7999     timeout : AjaxObject.timeout,
8000     scope   : AjaxObject
8001 }
8002 var callbackRebuildShowAccountList = {
8003         success : AjaxObject.rebuildShowFolders,
8004         failure : AjaxObject.handleFailure,
8005         timeout : AjaxObject.timeout,
8006         scope   : AjaxObject
8007 };
8008
8009 var callbackRefreshSugarFolders = {
8010         success : function(o) {
8011                 var t = YAHOO.lang.JSON.parse(o.responseText);
8012                 SUGAR.email2.folders.setSugarFoldersEnd(t);
8013         },
8014         failure : AjaxObject.handleFailure,
8015         timeout : AjaxObject.timeout,
8016         scope   : AjaxObject
8017 };
8018 var callbackReplyForward = {
8019         success : AjaxObject.handleReplyForward,
8020         finish : function(a, retryCount) {
8021                 if (typeof(retryCount) == 'undefined') {
8022                         retryCount = 0;
8023                 } else {
8024                         retryCount++;
8025                 }
8026                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8027                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8028         try {
8029                         var html = t.getContent();
8030
8031             html = "&nbsp;<div><hr></div>" + a.description;
8032
8033                         t.setContent(html);//
8034
8035             if (a.type != 'draft') {
8036                 // Next step, attach signature
8037                 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8038             }
8039
8040                 } catch(e) {
8041                         if (retryCount < 5) {
8042                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8043                                 return;
8044                         }
8045                 }
8046                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8047                 if (tabArray != null && tabArray.length > 0) {
8048                         for (i = 0 ; i < tabArray.length ; i++) {
8049                                 var tabObject = tabArray[i];
8050                                 if (tabObject.get("id") == ("composeTab" + idx)) {
8051                                         var tabLabel = a.name;
8052                                 if (tabLabel != null && tabLabel.length > 25) {
8053                                         tabLabel = tabLabel.substring(0, 25) + "...";
8054                                 } // if
8055                                         tabObject.get("labelEl").firstChild.data = tabLabel;
8056                                         break;
8057                                 }
8058                         }
8059                 }
8060
8061                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8062                 if (a.parent_name != null && a.parent_name != "") {
8063                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
8064                 }
8065                 if (a.parent_type != null && a.parent_type != "") {
8066                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
8067                 }
8068                 if (a.parent_id != null && a.parent_id != "") {
8069                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
8070                 }
8071                 if (a.fromAccounts.status) {
8072                         var addressFrom = document.getElementById('addressFrom' + idx);
8073                 SUGAR.email2.util.emptySelectOptions(addressFrom);
8074                 var fromAccountOpts = a.fromAccounts.data;
8075                 for(i=0; i<fromAccountOpts.length; i++) {
8076                       var key = fromAccountOpts[i].value;
8077                       var display = fromAccountOpts[i].text;
8078                       var opt = new Option(display, key);
8079                       if (fromAccountOpts[i].selected) {
8080                         opt.selected = true;
8081                       }
8082                       addressFrom.options.add(opt);
8083                 }
8084                 } // if
8085                 SUGAR.hideMessageBox();
8086
8087         },
8088         failure : AjaxObject.handleFailure,
8089         timeout : AjaxObject.timeout,
8090         scope   : AjaxObject,
8091         argument        : [sendType]
8092 };
8093 var callbackSendEmail = {
8094         success : AjaxObject.sendEmailCleanUp,
8095         failure : AjaxObject.handleFailure,
8096         timeout : AjaxObject.timeout,
8097         scope   : AjaxObject
8098 };
8099 var callbackSettings = {
8100         success : AjaxObject.updateUserPrefs,
8101         failure : AjaxObject.handleFailure,
8102         timeout : AjaxObject.timeout,
8103         scope   : AjaxObject
8104 };
8105 var callbackSettingsFolderRefresh = {
8106         success : AjaxObject.settingsFolderRefresh,
8107         failure : AjaxObject.handleFailure,
8108         timeout : AjaxObject.timeout,
8109         scope   : AjaxObject
8110 };
8111 var callbackLoadSettingFolder = {
8112         success : function(o) {
8113                 AjaxObject.settingsFolderRefresh(o);
8114                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8115         },
8116         failure : AjaxObject.handleFailure,
8117         timeout : AjaxObject.timeout,
8118         scope   : AjaxObject
8119
8120 };
8121 var callbackUploadAttachment = {
8122         success : AjaxObject.uploadAttachmentSuccessful,
8123         upload  : AjaxObject.uploadAttachmentSuccessful,
8124         failure : AjaxObject.handleFailure,
8125         timeout : AjaxObject.timeout,
8126         scope   : AjaxObject
8127 };
8128 var callbackUserPrefs = {
8129         success : function(o) {
8130                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8131         },
8132         failure : AjaxObject.handleFailure,
8133         timeout : AjaxObject.timeout,
8134         scope   : AjaxObject
8135 };
8136
8137 var callbackContextmenus = {
8138         markUnread : {
8139                 success : AjaxObject.markEmailCleanup,
8140                 failure : AjaxObject.handleFailure,
8141                 timeout : AjaxObject.timeout,
8142                 scope   : AjaxObject
8143         }
8144 };
8145
8146 var callbackCheckEmail2 = {
8147         success : function(o) {
8148         var ret = YAHOO.lang.JSON.parse(o.responseText);
8149                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8150
8151
8152         },
8153         failure : AjaxObject.handleFailure,
8154         timeout : AjaxObject.timeout,
8155         scope   : AjaxObject
8156 }// End of File modules/Emails/javascript/ajax.js
8157                                 
8158 /*********************************************************************************
8159  * SugarCRM Community Edition is a customer relationship management program developed by
8160  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8161  * 
8162  * This program is free software; you can redistribute it and/or modify it under
8163  * the terms of the GNU Affero General Public License version 3 as published by the
8164  * Free Software Foundation with the addition of the following permission added
8165  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8166  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8167  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8168  * 
8169  * This program is distributed in the hope that it will be useful, but WITHOUT
8170  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8171  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8172  * details.
8173  * 
8174  * You should have received a copy of the GNU Affero General Public License along with
8175  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8176  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8177  * 02110-1301 USA.
8178  * 
8179  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8180  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8181  * 
8182  * The interactive user interfaces in modified source and object code versions
8183  * of this program must display Appropriate Legal Notices, as required under
8184  * Section 5 of the GNU Affero General Public License version 3.
8185  * 
8186  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8187  * these Appropriate Legal Notices must retain the display of the "Powered by
8188  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8189  * technical reasons, the Appropriate Legal Notices must display the words
8190  * "Powered by SugarCRM".
8191  ********************************************************************************/
8192
8193 function gridInit() {
8194         if(SUGAR.email2.grid) {
8195                 SUGAR.email2.grid.destroy();
8196         }
8197         
8198         e2Grid = {
8199                 init : function() {
8200                 
8201                         var Ck = YAHOO.util.Cookie;
8202                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8203
8204                         if (Ck.get("EmailGridWidths")) {
8205                                 for (var i=0; i < widths.length; i++) {
8206                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8207                                 }
8208                         } else {
8209                                 for (var i=0; i < widths.length; i++) {
8210                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8211                                 }
8212                         }
8213                         
8214                         // changes "F" to an icon
8215                         function flaggedIcon(cell, record, column, value) {
8216                                 if(value != "") {
8217                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8218                                 }
8219                         }
8220                         // changes "A" to replied icon
8221                         function repliedIcon(cell, record, column, value) {
8222                                 if(value != "") {
8223                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8224                                 }
8225                         }
8226                 function attachIcon(cell, record, column, value) {
8227                                 if(value == "1") {
8228                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8229                                 }
8230                         }
8231
8232                         var colModel = 
8233                                 [
8234                                         {
8235                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8236                                                 width: 10, 
8237                                                 sortable: false, 
8238                                                 fixed: true,
8239                                                 resizeable: true,
8240                                                 formatter: attachIcon,
8241                                                 key: 'hasAttach'
8242                                         }, 
8243                                     {
8244                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8245                                                 width: widths[0], 
8246                                                 sortable: true, 
8247                                                 fixed: true,
8248                                                 resizeable: true,
8249                                                 formatter: flaggedIcon,
8250                                                 key: 'flagged'
8251                                         }, 
8252                                         {
8253                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8254                                                 width: widths[1], 
8255                                                 sortable: true, 
8256                                                 fixed: true,
8257                                                 resizeable: true,
8258                                                 formatter: repliedIcon,
8259                                                 key: 'status'
8260                                         },
8261                                         {
8262                                                 label: app_strings.LBL_EMAIL_FROM, 
8263                                                 width: widths[2],
8264                                                 sortable: true,
8265                                                 resizeable: true,
8266                                                 key: 'from'
8267                                         }, 
8268                                         {
8269                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8270                                                 width: widths[3], 
8271                                                 sortable: true,
8272                                                 resizeable: true,
8273                                                 key: 'subject'
8274                                         }, 
8275                                         {
8276                                                 label: mod_strings.LBL_LIST_DATE,
8277                                                 width: widths[4], 
8278                                                 sortable: true,
8279                                                 resizeable: true,
8280                         key: 'date'
8281                                         }, 
8282                                         {
8283                                                 label: app_strings.LBL_EMAIL_TO,
8284                                                 width: widths[5], 
8285                                                 sortable: false,
8286                                                 resizeable: true,
8287                         key: 'to_addrs'
8288                                         }, 
8289                                         {
8290                                                 label: 'uid',
8291                                                 hidden: true,
8292                         key: 'uid'
8293                                         }, 
8294                                         {
8295                                                 label: 'mbox',
8296                                                 hidden: true,
8297                         key: 'mbox'
8298                                         }, 
8299                                         {
8300                                                 label: 'ieId',
8301                                                 hidden: true,
8302                         key: 'ieId'
8303                                         }, 
8304                                         {       
8305                                                 label: 'site_url',
8306                                                 hidden: true,
8307                         key: 'site_url'
8308                                         },
8309                                         {       label: 'seen',
8310                                                 hidden: true,
8311                         key: 'seen'
8312                                         },
8313                                         {       label: 'type',
8314                                                 hidden: true,
8315                         key: 'type'
8316                                         }
8317                                 ];
8318                         
8319                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8320                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8321                                 responseSchema: {
8322                                     resultsList: 'Email',
8323                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8324                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8325                                 }
8326                     });
8327                         var params = {
8328                                         to_pdf : "true",
8329                                         module : "Emails",
8330                                         action : "EmailUIAjax",
8331                                         emailUIAction : "getMessageList",
8332                                         mbox : "INBOX",
8333                                         ieId : "",
8334                                         forceRefresh : "false"
8335                         };
8336                         if(lazyLoadFolder != null) {
8337                                 params['mbox'] = lazyLoadFolder.folder;
8338                                 params['ieId'] = lazyLoadFolder.ieId;
8339                                 //Check if the folder is a Sugar Folder
8340                                 var test = new String(lazyLoadFolder.folder);
8341                                 if(test.match(/SUGAR\./)) {
8342                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8343                                         params['mbox'] = test.substr(6);
8344                                 }
8345                         }
8346                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8347         
8348                         // create the Grid
8349                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8350                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8351                                 dynamicData: true,
8352                                 paginator: new YAHOO.widget.Paginator({ 
8353                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8354                                         containers : ["dt-pag-nav"],
8355                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8356                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8357                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8358                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8359                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8360                                 }),
8361                                 initialRequest:SUGAR.util.paramsToUrl(params),
8362                                 width:  "800px",
8363                                 height: "400px"
8364                         });
8365
8366                         initRowDD();
8367
8368                         //Override Paging request construction
8369                         grid.set("generateRequest", function(oState, oSelf) {
8370                     oState = oState || {pagination:null, sortedBy:null};
8371                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[5].getKey();
8372                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_ASC) ? "asc" : "desc";
8373                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8374                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8375                     // Build the request 
8376                     var ret = 
8377                             SUGAR.util.paramsToUrl(oSelf.params) + 
8378                             "&sort=" + sort +
8379                         "&dir=" + dir +
8380                         "&start=" + startIndex +
8381                         ((results !== null) ? "&limit=" + results : "");
8382                     return  ret;
8383                 });
8384                         
8385                         
8386                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8387                                 oPayload = oPayload || { };
8388                                 
8389                                 oPayload.totalRecords = oResponse.meta.total;
8390                                 oPayload.unreadRecords = oResponse.meta.unread;
8391                                 
8392                         var tabObject = SE.innerLayout.get("tabs")[0];
8393                         var mboxTitle = "";
8394                         if (this.params.mbox != null) {
8395                                 mboxTitle = this.params.mbox;
8396                         }
8397                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8398                         tabObject.get("labelEl").firstChild.data = tabtext;
8399                         
8400                         if (SE.tree) {
8401                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8402                                 if (node) {
8403                                         node.data.unseen = oResponse.meta.unread;
8404                                         SE.accounts.renderTree();
8405                                 }
8406                         }
8407                                 return oPayload; 
8408                         }
8409                         
8410                         var resize = grid.resizeGrid = function () {
8411                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8412                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8413                         }
8414                         grid.convertDDRows = function() {
8415                                 var rowEl = this.getFirstTrEl();
8416                                 while (rowEl != null) {
8417                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8418                                         rowEl = this.getNextTrEl(rowEl);
8419                                 }
8420                         }
8421                         
8422                         
8423                         grid.on("columnResizeEvent", function(o) {
8424                                 //Find the index of the column
8425                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8426                                 for (var i=0; i < colSet.length; i++) {
8427                                         if (o.column == colSet[i]) {
8428                                                 //Store it in the cookie
8429                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8430                                         }
8431                                 }
8432                                 //this.resizeGrid();
8433                         }, null, grid); 
8434                         
8435                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8436                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8437                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8438                         grid.render();
8439                         SUGAR.email2.listViewLayout.on("render", resize);
8440                         resize();
8441                         
8442                         //Setup the default load parameters
8443                         SUGAR.email2.grid.params = params;
8444                         
8445                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8446                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8447                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8448                 }
8449         };
8450         e2Grid.init();
8451 };
8452
8453
8454 function initRowDD() {
8455         var sg = SUGAR.email2.grid,
8456         Dom = YAHOO.util.Dom;
8457         sg.DDRow = function(oDataTable, oRecord, elTr) {
8458                 if(oDataTable && oRecord && elTr) {
8459                         this.ddtable = oDataTable;
8460                 this.table = oDataTable.getTableEl();
8461                 this.row = oRecord;
8462                 this.rowEl = elTr;
8463                 this.newIndex = null;
8464                 this.init(elTr);
8465                 this.initFrame(); // Needed for DDProxy
8466                 this.invalidHandleTypes = {};
8467             }   
8468         };
8469         
8470         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8471             _resizeProxy: function() {
8472                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8473                 var dragEl = this.getDragEl(),
8474                     el = this.getEl();
8475                 var xy = Dom.getXY(el);
8476                 
8477                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8478                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8479                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8480                 Dom.setStyle(dragEl, 'display', "");
8481             },
8482             
8483             startDrag: function(x, y) { 
8484                 //Check if we should be dragging a set of rows rather than just the one.
8485                 var selectedRows = this.ddtable.getSelectedRows();
8486                 var iSelected = false;
8487                 for (var i in selectedRows) {
8488                         if (this.rowEl.id == selectedRows[i]) {
8489                                 iSelected = true;
8490                                 break
8491                         }
8492                 }
8493                 if (iSelected) {
8494                         this.rows = [];
8495                         for (var i in selectedRows) {
8496                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8497                         }
8498                 } else {
8499                         this.rows = [this.row];
8500                         this.ddtable.unselectAllRows();
8501                         this.ddtable.selectRow(this.row);
8502                 }
8503                 
8504                 //Initialize the dragable proxy
8505                 var dragEl = this.getDragEl(); 
8506                 var clickEl = this.getEl(); 
8507                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8508                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8509                 Dom.addClass(dragEl, "yui-dt-liner");
8510                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8511                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8512                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8513                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8514             },
8515             
8516             clickValidator: function(e) {
8517                 if (this.row.getData()[0] == " ")
8518                         return false;
8519                 var target = YAHOO.util.Event.getTarget(e);
8520                 return ( this.isValidHandleChild(target) && 
8521                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8522             },
8523             /**
8524              * This funciton checks that the target of the drag is a table row in this
8525              * DDGroup and simply moves the sourceEL to that location as a preview.
8526              */
8527             onDragOver: function(ev, id) {
8528                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8529                 if (node && node != this.targetNode) {
8530                         this.targetNode = node;
8531                         SUGAR.email2.folders.unhighliteAll();
8532                         node.highlight();
8533                 }
8534             },
8535             
8536             onDragOut: function(e, id) {
8537                 if (this.targetNode) {
8538                         SUGAR.email2.folders.unhighliteAll();
8539                         this.targetNode = false;
8540                 }
8541             },
8542             endDrag: function() {
8543                 Dom.setStyle(this.getEl(), "opacity", "");
8544                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8545                 if (this.targetNode) {
8546                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8547                 }
8548                 SUGAR.email2.folders.unhighliteAll();
8549                 this.rows = null;
8550             }
8551         });
8552 }
8553
8554 function AddressSearchGridInit() {
8555     function moduleIcon(elCell, oRecord, oColumn, oData) {
8556         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8557     };
8558     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8559         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8560     };
8561     var checkHeader = '<input type="checkbox" ';
8562     if (SUGAR.email2.util.isIe()) {
8563         checkHeader += 'style="top:-5px" ';
8564     }
8565     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8566     var colModel = 
8567             [{
8568                 label: checkHeader,
8569             width: 30,
8570             formatter: selectionCheckBox,
8571             key: 'bean_id'
8572         },
8573             {
8574                 label: mod_strings.LBL_LIST_TYPE,
8575                 width: 25,
8576                 formatter: moduleIcon,
8577                 key: 'bean_module'
8578         },
8579             {
8580                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8581                 width: 180,
8582                 sortable: true,
8583                 key: 'name'
8584             }, 
8585             {
8586                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8587                 width: 300, 
8588                 sortable: true,
8589                 key: 'email'
8590             }];
8591     
8592     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8593                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8594         responseSchema: {
8595             resultsList: 'Person',
8596             fields: ['name', 'email', 'bean_id', 'bean_module'],
8597                     metaFields: {total: 'TotalCount'}
8598         },
8599         //enable sorting on the server accross all data
8600         remoteSort: true
8601     });
8602     dataModel.params = {
8603                 to_pdf          : true,
8604                 module          : "Emails",
8605                 action          : "EmailUIAjax",
8606                 emailUIAction:"getAddressSearchResults"
8607     }
8608     var rb = document.getElementById('hasRelatedBean').checked;
8609         if (rb) {
8610                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8611                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8612                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8613                 dataModel.params['related_bean_id'] = relatedBeanId;
8614                 dataModel.params['related_bean_type'] = relatedBeanType;
8615                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8616         }
8617     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8618     
8619     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8620         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8621                 dynamicData: true,
8622                 paginator: new YAHOO.widget.Paginator({ 
8623                         rowsPerPage: 25,  
8624                         containers : ["dt-pag-nav-addressbook"],
8625                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8626                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8627                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8628                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8629                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8630                 }),
8631                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8632                 width:  "560px",
8633                 height: "250px"
8634     });
8635         //Override Paging request construction
8636         grid.set("generateRequest", function(oState, oSelf) {
8637         oState = oState || {pagination:null, sortedBy:null};
8638         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8639         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8640         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8641         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8642         // Build the request 
8643         var ret = 
8644             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8645             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8646             ((results !== null) ? "&limit=" + results : "");
8647         return  ret;
8648     });
8649     
8650         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8651                 oPayload = oPayload || { };
8652                 oPayload.totalRecords = oResponse.meta.total;
8653                 return oPayload; 
8654         }
8655         
8656         grid.clickToggleSelect= function(args) {
8657                 var isIE = (args.event.target == null);
8658                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8659                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8660                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8661                 }
8662         }
8663         
8664         grid.reSelectRowsOnRender = function (){
8665             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8666         for (var i = 0; i < rows.length; i++) 
8667         {
8668                 var emailAddress = rows[i].getData("email");
8669             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8670             if(alreadyAdded)
8671             {
8672                 rows[i].setData("selected",  true);
8673                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8674             }
8675             else
8676             {
8677                 rows[i].setData("selected",  false);
8678                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8679             }
8680         }
8681         }
8682         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8683         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8684         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8685     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8686     
8687     grid.render();
8688     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8689     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8690     
8691     grid.toggleSelectCheckbox = function(id,checked){
8692         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8693         row.setData("checked",checked);
8694     };
8695     grid.toggleSelect = function(id, checked) {
8696         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8697         checked = row.getData("selected");
8698         if (!checked)
8699         {
8700             SUGAR.email2.addressBook.grid.selectRow(row);
8701             SE.addressBook.insertContactRowToResultTable(id,null)
8702         } else 
8703         {
8704             SUGAR.email2.addressBook.grid.unselectRow(row);
8705             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8706         }
8707         row.setData("selected", !checked);
8708     };
8709     
8710     grid.toggleSelectAll = function(checked) {
8711         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8712         for (var i = 0; i < rows.length; i++) {
8713                         if (typeof(rows[i]) != "undefined")
8714                                 rows[i].setData("checked",  checked);
8715         }
8716         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8717         for (var i = 0; i < checkBoxes.length; i++) {
8718             checkBoxes[i].checked = checked;
8719         }
8720     };
8721     
8722     //Initialize the grid result table.
8723     AddressSearchResultsGridInit();
8724 }
8725
8726
8727
8728 /**
8729 *  Initalize the results table for the address book selection.
8730 *
8731 */
8732 function AddressSearchResultsGridInit()
8733 {
8734     
8735     /* Full name sort funciton to compare by last name if available */
8736     var fullNameSort = function(a, b, desc) {
8737         // Deal with empty values
8738         if(!YAHOO.lang.isValue(a))
8739             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8740         else if(!YAHOO.lang.isValue(b))
8741             return -1;
8742
8743         var aNames = a.getData("name").split(' ');
8744         var bNames = b.getData("name").split(' ');
8745
8746         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8747         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8748
8749         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8750
8751     };
8752     
8753     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8754                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8755                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8756               
8757     var ColumnDefs = [{key:'type',label:app_strings.LBL_EMAIL_ADDRESS_BOOK_ADRRESS_TYPE, width: 60, sortable: true, editor: new YAHOO.widget.RadioCellEditor({radioOptions:typeDdOptions,disableBtns:true})},
8758                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8759      
8760      var myDataSource = new YAHOO.util.DataSource([]); 
8761          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8762          myDataSource.responseSchema = { 
8763                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8764                 };                                                                 
8765     
8766          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8767                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8768     
8769      var highlightEditableCell = function(oArgs) {
8770             var elCell = oArgs.target;
8771             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8772                 this.highlightCell(elCell);
8773             }
8774         };
8775       
8776      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8777      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8778      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8779      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8780          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8781      
8782      //Setup the context menus
8783      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8784              var task = p_aArgs[1]; 
8785              if(task) 
8786              { 
8787                  var elRow = this.contextEventTarget; 
8788                  elRow = p_myDataTable.getTrEl(elRow); 
8789          
8790                  if(elRow) 
8791                  { 
8792                      switch(task.index) 
8793                      { 
8794                          case 0:     
8795                              var oRecord = p_myDataTable.getRecord(elRow); 
8796                              p_myDataTable.deleteRow(elRow);  
8797                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8798                      } 
8799                  } 
8800              } 
8801          };
8802      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8803                         {trigger:gridResults.getTbodyEl()}); 
8804          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8805          contextMenu.render("addrSearchResultGrid"); 
8806          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8807 }
8808 // End of File modules/Emails/javascript/grid.js
8809                                 
8810 /*********************************************************************************
8811  * SugarCRM Community Edition is a customer relationship management program developed by
8812  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8813  * 
8814  * This program is free software; you can redistribute it and/or modify it under
8815  * the terms of the GNU Affero General Public License version 3 as published by the
8816  * Free Software Foundation with the addition of the following permission added
8817  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8818  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8819  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8820  * 
8821  * This program is distributed in the hope that it will be useful, but WITHOUT
8822  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8823  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8824  * details.
8825  * 
8826  * You should have received a copy of the GNU Affero General Public License along with
8827  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8828  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8829  * 02110-1301 USA.
8830  * 
8831  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8832  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8833  * 
8834  * The interactive user interfaces in modified source and object code versions
8835  * of this program must display Appropriate Legal Notices, as required under
8836  * Section 5 of the GNU Affero General Public License version 3.
8837  * 
8838  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8839  * these Appropriate Legal Notices must retain the display of the "Powered by
8840  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8841  * technical reasons, the Appropriate Legal Notices must display the words
8842  * "Powered by SugarCRM".
8843  ********************************************************************************/
8844
8845
8846 /******************************************************************************
8847  * Initialize Email 2.0 Application
8848  */
8849
8850 //Override Sugar Languge so quick creates work properly
8851
8852
8853 function email2init() {
8854
8855         //Init Tiny MCE
8856     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8857     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8858     if (!SUGAR.util.isTouchScreen()) {
8859          tinyMCE.init({
8860                  convert_urls : false,
8861          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8862          width: tinyConfig.width,
8863          theme: tinyConfig.theme,
8864          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8865          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8866          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8867          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8868          plugins : tinyConfig.plugins,
8869          elements : tinyConfig.elements,
8870          language : tinyConfig.language,
8871          extended_valid_elements : tinyConfig.extended_valid_elements,
8872          mode: tinyConfig.mode,
8873          strict_loading_mode : true,
8874                  force_br_newlines : true,
8875          forced_root_block : '',
8876          directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8877      });
8878     }
8879
8880     // initialze message overlay
8881     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8882             //iframe        : true,
8883             modal       : false,
8884             autoTabs    : true,
8885             width       : 300,
8886             height      : 120,
8887             shadow      : true
8888         }
8889     );
8890         // Hide Sugar menu
8891         if (SUGAR.themes.tempHideLeftCol)
8892         SUGAR.themes.tempHideLeftCol();
8893
8894         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8895 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8896
8897         // set defaults for YAHOO.util.DragDropManager
8898         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8899
8900         SUGAR.email2.nextYear = new Date();
8901         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8902
8903         
8904     // initialize and display UI framework (complexLayout.js)
8905     complexLayoutInit();
8906     
8907     // initialize and display grid (grid.js)
8908     gridInit();
8909     
8910     // initialize treeview for folders
8911         //onloadTreeinit();
8912         SUGAR.email2.folders.rebuildFolders(true);
8913         
8914         
8915     //Setup the Message Box overlay
8916     /*Ext.MessageBox.maxWidth = 350;
8917     Ext.MessageBox.minProgressWidth = 350;
8918
8919         ///////////////////////////////////////////////////////////////////////////
8920         ////    CONTEXT MENUS
8921         // detailView array
8922         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8923 */
8924         var SEC = SUGAR.email2.contextMenus; 
8925         
8926         //Grid menu
8927         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8928                 trigger: SUGAR.email2.grid.get("element"),
8929                 lazyload: true
8930         });
8931         emailMenu.subscribe("beforeShow", function() {
8932                 var oTarget = this.contextEventTarget;
8933                 if (typeof(oTarget) == "undefined")
8934                   return;
8935                 var grid = SUGAR.email2.grid;
8936                 var selectedRows = grid.getSelectedRows();
8937                 var multipleSelected = (selectedRows.length > 1) ? true: false;
8938                 if (!multipleSelected)
8939                 {
8940                         grid.unselectAllRows();
8941                         grid.selectRow(oTarget);
8942                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
8943                 }
8944                 else if(multipleSelected)
8945                 {
8946                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8947                 }
8948         });
8949         
8950         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8951         //us to access individual elements easier by name rather than by index
8952         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
8953                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8954         emailMenu.addItems([
8955         {
8956             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8957             id: 'showDetailView',
8958             onclick: { fn: SEC.showDetailView }
8959         },
8960         {
8961             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8962             onclick: { fn: SEC.openMultiple }
8963         },
8964         {
8965             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8966             onclick: { fn: SEC.archiveToSugar }
8967         },
8968         {
8969             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8970             id: 'reply',
8971             onclick: { fn: SEC.replyForwardEmailContext }
8972         },
8973         {
8974             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8975             id: 'replyAll',
8976             onclick: { fn: SEC.replyForwardEmailContext }
8977         },
8978         {
8979             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8980             id: 'forward',
8981             onclick: { fn: SEC.replyForwardEmailContext }
8982         },
8983         {
8984             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8985             id: 'delete',
8986             onclick: { fn: SEC.markDeleted }
8987         },
8988         {
8989             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8990             id: 'print',
8991             onclick: { fn: SEC.viewPrintable }
8992         },                
8993         // Mark... submenu
8994         {
8995             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8996             submenu: {
8997                         id: "markEmailMenu",
8998                 itemdata : [
8999                     {
9000                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9001                         onclick: { fn: SEC.markUnread }
9002                     },
9003                     {
9004                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9005                         onclick: { fn: SEC.markRead }
9006                     },
9007                     {
9008                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9009                         onclick: { fn: SEC.markFlagged }
9010                     },
9011                     {
9012                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9013                         onclick: {  fn: SEC.markUnflagged }
9014                     }
9015                 ]
9016             }
9017          },
9018         {
9019             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9020                 id: 'assignTo',
9021                 onclick: { fn: SEC.assignEmailsTo }
9022          },
9023          {
9024             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9025             id: 'relateTo',
9026             onclick: { fn: SEC.relateTo }
9027          }
9028     ]);
9029         SEC.emailListContextMenu.render();
9030         
9031         //Handle the Tree folder menu trigger ourselves
9032         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9033
9034         
9035         //Folder Menu
9036     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9037                 trigger: "",
9038                 lazyload: true 
9039         });
9040     SEC.frameFoldersContextMenu.addItems([
9041                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9042                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9043                         onclick: {  fn: function() {
9044                         var node = SUGAR.email2.clickedFolderNode;
9045                         if (node.data.ieId) {
9046                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9047                     }}
9048                 },
9049                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9050                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9051                         onclick: {  fn: function() {
9052                         var node = SUGAR.email2.clickedFolderNode;
9053                         if (node.data.ieId) {
9054                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9055                     }}
9056                 },
9057                 {
9058                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9059                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9060                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9061                 },
9062                 {
9063                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9064                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9065                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9066                 },
9067                 {
9068                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9069                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9070                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9071                  },
9072                  {
9073                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9074                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9075                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9076                   },
9077                  {
9078                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9079                     onclick: {  fn: function() {
9080                         var node = SUGAR.email2.clickedFolderNode;
9081                         if (node.data.ieId) {
9082                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9083                     }}
9084                   } 
9085         ]);
9086     SEC.frameFoldersContextMenu.render();
9087     
9088     SEC.initContactsMenu = function() {
9089         // contacts
9090         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9091                 trigger: "contacts",
9092                 lazyload: true
9093         });
9094         SEC.contactsContextMenu.addItems([
9095                 {
9096                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9097                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9098                 },
9099                 {
9100                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9101                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9102                 }
9103         ]);
9104         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9105                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9106                 if (oTarget && !grid.isSelected(oTarget)) {
9107                         grid.unselectAllRows();
9108                         grid.selectRow(oTarget);
9109                 }
9110         });
9111         SEC.contactsContextMenu.render();
9112         }
9113         
9114         
9115         // set auto-check timer
9116         SUGAR.email2.folders.startCheckTimer();
9117         // check if we're coming from an email-link click
9118         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9119         
9120         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9121         
9122         //Init fix for YUI 2.7.0 datatable sort.
9123         SUGAR.email2.addressBook.initFixForDatatableSort();
9124 }
9125
9126 function createTreePanel(treeData, params) {
9127         var tree = new YAHOO.widget.TreeView(params.id);
9128         var root = tree.getRoot();
9129         
9130         //if (treeData.nodes && treeData[0].id == "Home")
9131         //      treeData = treeData[0];
9132         return tree;
9133 }
9134
9135 function addChildNodes(parentNode, parentData) {
9136         var Ck = YAHOO.util.Cookie;
9137         var nextyear = SUGAR.email2.nextYear;
9138         var nodes = parentData.nodes || parentData.children;
9139         for (i in nodes) {
9140                 if (typeof(nodes[i]) == 'object') {
9141                         if (nodes[i].data) {
9142                 // See comment about href below.
9143                                 // nodes[i].data.href = '#';
9144                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9145                                 node.action = nodes[i].data.action;
9146                         } else {
9147                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9148                                         addChildNodes(parentNode, nodes[i]);
9149                                         return;
9150                                 }
9151                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9152                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9153                                 if (nodes[i].cls) {
9154                                         nodes[i].className = nodes[i].cls;
9155                                 }
9156                 // Previously, span was added in the label so it was rendering in the tree.
9157                 // Default behavior is to wrap in span if no href property, and since this href
9158                 // doesn't do anything, remove it so that it will be wrapped in spans.
9159                 // nodes[i].href = "#";
9160                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9161                                 //Override YUI child node creation
9162                                 if (nodes[i].children) {
9163                                         nodes[i].nodes = nodes[i].children;
9164                                         nodes[i].children = [ ];
9165                                 }
9166                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9167                         }
9168                         
9169                         if (typeof(nodes[i].nodes) == 'object') {
9170                                 addChildNodes(node, nodes[i]);
9171                         }
9172                 }
9173         }
9174 }
9175
9176 /**
9177  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9178  */
9179 function email2treeinit(tree, treedata, treediv, params) {
9180         //ensure the tree data is not corrupt
9181         if (!treedata) {
9182            return;
9183         }
9184         if (SUGAR.email2.tree) {
9185                 SUGAR.email2.tree.destroy();
9186                 SUGAR.email2.tree = null;
9187         }
9188         
9189         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9190                 id: 'emailtree'
9191         });
9192         
9193         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9194         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9195         tree.subscribe("expandComplete", function(node){
9196                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9197                 for (var i in node.children) {
9198                         SE.accounts.setupDDTarget(node.children[i]);
9199                 }
9200         });
9201         tree.setCollapseAnim("TVSlideOut");
9202         tree.setExpandAnim("TVSlideIn");
9203         var root = tree.root;
9204         while (root.hasChildren()) {
9205                 var node = root.children[0];
9206                 node.destroy();
9207                 tree.removeNode(root.children[0], false);
9208         }
9209         addChildNodes(root, treedata);
9210         tree.render();
9211         SUGAR.email2.accounts.renderTree();
9212 }
9213
9214 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9215         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9216 };
9217
9218
9219 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9220     startDrag: function(x, y) {
9221                 var Dom = YAHOO.util.Dom;       
9222                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9223                 
9224                 this.dragId = "";
9225                 var dragEl = this.getDragEl();  
9226         var clickEl = this.getEl(); 
9227         Dom.setStyle(clickEl, "color", "#AAA");
9228         Dom.setStyle(clickEl, "opacity", "0.25"); 
9229         dragEl.innerHTML = clickEl.innerHTML; 
9230          
9231         Dom.addClass(dragEl, "ygtvcell");
9232         Dom.addClass(dragEl, "ygtvcontent");
9233         Dom.addClass(dragEl, "folderDragProxy");
9234         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9235         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9236         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9237         Dom.setStyle(dragEl, "opacity", "0.5"); 
9238             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9239     },
9240     
9241     onDragOver: function(ev, id) {
9242         var Dom = YAHOO.util.Dom;
9243         if (id != this.dragId)
9244         {
9245                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9246                 if(node.data.cls != "sugarFolder") {
9247                         SUGAR.email2.folders.unhighliteAll();
9248                         return;
9249                 }
9250                 this.dragId = id;
9251                 this.targetNode = node;
9252                 SUGAR.email2.folders.unhighliteAll();
9253                 node.highlight();
9254         }
9255     },
9256     
9257     onDragOut: function(e, id) {
9258         if (this.targetNode) {
9259                 SUGAR.email2.folders.unhighliteAll();
9260                 this.targetNode = false;
9261                 this.dragId = false;
9262         }
9263     },
9264     
9265     endDrag: function() { 
9266         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9267         if (this.targetNode) {
9268                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9269         }
9270     }
9271 });// End of File modules/Emails/javascript/init.js
9272                                 
9273 /*********************************************************************************
9274  * SugarCRM Community Edition is a customer relationship management program developed by
9275  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9276  * 
9277  * This program is free software; you can redistribute it and/or modify it under
9278  * the terms of the GNU Affero General Public License version 3 as published by the
9279  * Free Software Foundation with the addition of the following permission added
9280  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9281  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9282  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9283  * 
9284  * This program is distributed in the hope that it will be useful, but WITHOUT
9285  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9286  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9287  * details.
9288  * 
9289  * You should have received a copy of the GNU Affero General Public License along with
9290  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9291  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9292  * 02110-1301 USA.
9293  * 
9294  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9295  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9296  * 
9297  * The interactive user interfaces in modified source and object code versions
9298  * of this program must display Appropriate Legal Notices, as required under
9299  * Section 5 of the GNU Affero General Public License version 3.
9300  * 
9301  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9302  * these Appropriate Legal Notices must retain the display of the "Powered by
9303  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9304  * technical reasons, the Appropriate Legal Notices must display the words
9305  * "Powered by SugarCRM".
9306  ********************************************************************************/
9307
9308 /**
9309   Complex layout init
9310  */
9311 function complexLayoutInit() {
9312         var se = SUGAR.email2;
9313         var Dom = YAHOO.util.Dom;
9314         se.e2Layout = {
9315         getInnerLayout : function(rows) {
9316                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9317                 parent: se.complexLayout,  
9318                         border:true,
9319                     hideOnLayout: true,
9320                     height: 400,
9321                                 units: [{
9322                                         position: "center",
9323                                     scroll:false, // grid should autoScroll itself
9324                                     split:true,
9325                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9326                                 },{
9327                                         position: "bottom",
9328                                     scroll:true,
9329                                     collapse: false,
9330                                     resize: true,
9331                                     useShim:true,
9332                                     height:'250',
9333                                     body: "<div id='listBottom' />"
9334                                 },{
9335                                     position: "right",
9336                                     scroll:true,
9337                                     collapse: false,
9338                                     resize: true,
9339                                     useShim:true,
9340                                     width:'250',
9341                                     body: "<div id='listRight' />",
9342                                     titlebar: false //,header: "right"
9343                                 }]
9344             });
9345                 se.complexLayout.on("render", function(){
9346                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9347                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9348                                 SUGAR.email2.listViewLayout.set("height", height);
9349                                 SUGAR.email2.listViewLayout.render();
9350                 });
9351             se.listViewLayout.render();
9352             //CSS hack for now
9353             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9354             var rp = se.listViewLayout.resizePreview = function() {
9355                 var pre = Dom.get("displayEmailFramePreview");
9356                 if (pre) {
9357                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9358                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9359                 }
9360             };
9361             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9362             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9363             se.e2Layout.setPreviewPanel(rows);
9364             se.previewLayout = se.listViewLayout;
9365             return se.listViewLayout;
9366         },
9367         
9368         getInnerLayout2Rows : function() {
9369             return this.getInnerLayout(true);
9370         },
9371         getInnerLayout2Columns : function() {
9372             return this.getInnerLayout(false);
9373         },
9374         
9375         init : function(){
9376             // initialize state manager, we will use cookies
9377 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9378                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9379                 se.complexLayout = new YAHOO.widget.Layout("container", {
9380                         border:true,
9381                 hideOnLayout: true,
9382                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9383                 width: Dom.getViewportWidth() - 40,
9384                 units: [{
9385                         position: "center",
9386                     scroll:false,
9387                     body: "<div id='emailtabs'></div>"
9388                 },
9389                 {
9390                         position: "left",
9391                         scroll: true,
9392                         body: "<div id='lefttabs'></div>",
9393                     collapse: true,
9394                     width: 210,
9395                     minWidth: 100,
9396                     resize:true,
9397                     useShim:true,
9398                     titlebar: true,
9399                     header: "&nbsp;"
9400                 },
9401                 {
9402                     header: Dom.get('footerLinks').innerHTML,
9403                                         position: 'bottom',
9404                                         id: 'mbfooter',
9405                                         height: 22,
9406                                         border: false
9407                 }]
9408             });
9409                 se.complexLayout.render();
9410                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9411                         tp.addTab(new YAHOO.widget.Tab({ 
9412                                 label: "Inbox",
9413                                 scroll : true,
9414                                 content : "<div id='listViewDiv'/>",
9415                                 id : "center",
9416                                 active : true
9417                         }));
9418                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9419                         tp.appendTo(centerEl);
9420                         //CSS hack for now
9421                         tp.get("element").style.borderRight = "1px solid #666"
9422                         
9423                         var listV =  this.getInnerLayout2Rows();
9424                         listV.set("height", tp.get("element").clientHeight - 25);
9425                         listV.render();
9426             
9427             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9428             var folderTab = new YAHOO.widget.Tab({ 
9429                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9430                                 scroll : true,
9431                                 content : "<div id='emailtree'/>",
9432                                 id : "tree",
9433                                 active : true
9434                         });
9435             folderTab.on("activeChange", function(o){ 
9436                 if (o.newValue) {
9437                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9438                 }
9439             });
9440             se.leftTabs.addTab(folderTab);
9441             
9442             var tabContent = SUGAR.util.getAndRemove("searchTab");
9443             var searchTab = new YAHOO.widget.Tab({ 
9444                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9445                                 scroll : true,
9446                                 content : tabContent.innerHTML,
9447                                 id : tabContent.id
9448                         });
9449             searchTab.on("activeChange", function(o){ 
9450                 if (o.newValue) 
9451                 {
9452                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9453                    //Setup the calendars if needed
9454                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9455                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9456                    
9457                        //Initalize sqs object for assigned user name 
9458                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
9459                        
9460                        //Attach event handler for when the relate module option is selected for the correct sqs object
9461                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9462                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9463                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
9464                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9465                        
9466                        //If enter key is pressed, perform search
9467                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9468                        for(var i=0; i < addKeyPressFields.length;i++)
9469                        {
9470                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9471                                 if (e.keyCode == 13) {
9472                                         YAHOO.util.Event.stopEvent(e);
9473                                         SUGAR.email2.search.searchAdvanced();
9474                                 }
9475                        });
9476                        }
9477                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
9478                        enableQS(true);
9479                        //Clear parent values if selecting another parent type.
9480                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
9481                            function(){ 
9482                                document.getElementById('data_parent_id_search').value =''; 
9483                                document.getElementById('data_parent_name_search').value =''; 
9484                            });
9485                 
9486                 }
9487             });
9488             se.leftTabs.addTab(searchTab);
9489             
9490             var resizeTabBody = function() {
9491                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9492                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9493             }
9494             resizeTabBody();
9495             se.complexLayout.on("render", resizeTabBody);
9496             se.leftTabs.on("activeTabChange", resizeTabBody);
9497                         //hack to allow left pane scroll bar to fully show
9498                 var lefttabsDiv = document.getElementById('lefttabs');
9499                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9500                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9501                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9502           
9503         },
9504         initSQSObject: function(formName,fieldName)
9505         {
9506             var fullFieldName = formName + '_' + fieldName; //SQS Convention
9507             var resultName = fullFieldName + '_' + 'results';
9508             
9509             if (QSFieldsArray[fullFieldName] != null) 
9510             {
9511                 QSFieldsArray[fullFieldName].destroy();
9512                 delete QSFieldsArray[fullFieldName];
9513             }
9514             if (QSProcessedFieldsArray[fullFieldName])
9515             QSProcessedFieldsArray[fullFieldName] = false;
9516
9517             if( Dom.get(resultName) )
9518             {
9519                 var obj = document.getElementById(resultName);
9520                 obj.parentNode.removeChild(obj);
9521             }
9522         },
9523         setPreviewPanel: function(rows) {
9524                 if (rows) {
9525                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9526                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9527                 Dom.get("listRight").innerHTML = "";
9528                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9529             } else {
9530                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9531                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9532                 Dom.get("listBottom").innerHTML = "";
9533                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9534             }
9535         }
9536     };
9537         se.e2Layout.init();
9538 }
9539
9540 var myBufferedListenerObject = new Object();
9541 myBufferedListenerObject.refit = function() {
9542     if(SUGAR.email2.grid) {
9543         SUGAR.email2.grid.autoSize();
9544     }
9545 }
9546 // End of File modules/Emails/javascript/complexLayout.js
9547                                 
9548 /*********************************************************************************
9549  * SugarCRM Community Edition is a customer relationship management program developed by
9550  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9551  * 
9552  * This program is free software; you can redistribute it and/or modify it under
9553  * the terms of the GNU Affero General Public License version 3 as published by the
9554  * Free Software Foundation with the addition of the following permission added
9555  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9556  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9557  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9558  * 
9559  * This program is distributed in the hope that it will be useful, but WITHOUT
9560  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9561  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9562  * details.
9563  * 
9564  * You should have received a copy of the GNU Affero General Public License along with
9565  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9566  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9567  * 02110-1301 USA.
9568  * 
9569  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9570  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9571  * 
9572  * The interactive user interfaces in modified source and object code versions
9573  * of this program must display Appropriate Legal Notices, as required under
9574  * Section 5 of the GNU Affero General Public License version 3.
9575  * 
9576  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9577  * these Appropriate Legal Notices must retain the display of the "Powered by
9578  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9579  * technical reasons, the Appropriate Legal Notices must display the words
9580  * "Powered by SugarCRM".
9581  ********************************************************************************/
9582
9583 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9584 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9585 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9586 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9587 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9588 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9589 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9590 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9591 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9592 '               <input type="hidden" id="composeType" name="composeType">' +
9593 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9594 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9595 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9596 '               <input type="hidden" id="sendTo" name="sendTo">' +
9597 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9598 '               <input type="hidden" id="sendCc" name="sendCc">' +
9599 '               <input type="hidden" id="setEditor" name="setEditor">' +
9600 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9601 '               <input type="hidden" id="parent_id" name="parent_id">' +
9602 '               <input type="hidden" id="parent_type" name="parent_type">' +
9603 '               <input type="hidden" id="attachments" name="attachments">' +
9604 '               <input type="hidden" id="documents" name="documents">' +
9605 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9606 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9607 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9608 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9609 '                       <tr>' +
9610 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9611 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.sendEmail({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_send.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_SEND}</button>' +
9612 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.saveDraft({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_save.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_SAVE_DRAFT}</button>' +
9613 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.showAttachmentPanel({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_attach.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_ATTACHMENT}</button>' +
9614 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.showOptionsPanel({idx}, false);"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_options.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_OPTIONS}</button>' +
9615 '</td><td style="padding: 0px !important;margin:0px; !important">&nbsp;&nbsp;{mod_strings.LBL_EMAIL_RELATE}:&nbsp;&nbsp;<select class="select" id="data_parent_type{idx}" onchange="document.getElementById(\'data_parent_name{idx}\').value=\'\';document.getElementById(\'data_parent_id{idx}\').value=\'\'; SUGAR.email2.composeLayout.enableQuickSearchRelate(\'{idx}\');" name="data_parent_type{idx}">{linkbeans_options}</select>' + 
9616 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9617 '<input class="sqsEnabled" id="data_parent_name{idx}" name="data_parent_name{idx}" type="text" value="">&nbsp;<button type="button" class="button" onclick="SUGAR.email2.composeLayout.callopenpopupForEmail2({idx});"><img src="index.php?entryPoint=getImage&themeName=default&imageName=id-ff-select.png" align="absmiddle" border="0"></button>' +
9618 '                       </td></tr></tbody></table></th>'     +
9619 '                       </tr>' +
9620 '                       <tr>' +
9621 '                               <td>' +
9622 '                                       <div style="margin:5px;">' +
9623 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9624 '                                               <tr>' +
9625 '                                                       <td class="emailUILabel" NOWRAP >' +
9626 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9627 '                                                       </td>' +
9628 '                                                       <td class="emailUIField" NOWRAP>' +
9629 '                                                               <div>' +
9630 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9631 '                                                               </div>' +
9632 '                                                       </td>' +
9633 '                                               </tr>' +
9634 '                                               <tr>' +
9635 '                                                       <td class="emailUILabel" NOWRAP>' +
9636 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9637 '                                   {app_strings.LBL_EMAIL_TO}:' +
9638 '                               </button>' + 
9639 '                                                       </td>' +
9640 '                                                       <td class="emailUIField" NOWRAP>' +
9641 '                                                               <div class="ac_autocomplete">' +
9642 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9643 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9644 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9645 '                                                               </div>' +
9646 '                                                       </td>' +
9647 '                                               </tr>' +
9648 '                                               <tr id="add_addr_options_tr{idx}">' +
9649 '                                                       <td class="emailUILabel" NOWRAP>&nbsp;</td><td class="emailUIField" valign="top" NOWRAP>&nbsp;&nbsp;<span id="cc_span{idx}"><a href="#" onclick="SE.composeLayout.showHiddenAddress(\'cc\',\'{idx}\');">{mod_strings.LBL_ADD_CC}</a></span><span id="bcc_cc_sep{idx}">&nbsp;{mod_strings.LBL_ADD_CC_BCC_SEP}&nbsp;</span><span id="bcc_span{idx}"><a href="#" onclick="SE.composeLayout.showHiddenAddress(\'bcc\',\'{idx}\');">{mod_strings.LBL_ADD_BCC}</a></span></td>'+
9650 '                                               </tr>'+
9651 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9652 '                                                       <td class="emailUILabel" NOWRAP>' +
9653 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9654 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9655 '                               </button>' + 
9656 '                                                       </td>' +
9657 '                                                       <td class="emailUIField" NOWRAP>' +
9658 '                                                               <div class="ac_autocomplete">' +
9659 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9660 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9661 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9662 '                                                               </div>' +
9663 '                                                       </td>' +
9664 '                                               </tr>' +
9665 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9666 '                                                       <td class="emailUILabel" NOWRAP>' +
9667 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9668 '                               {app_strings.LBL_EMAIL_BCC}:' +
9669 '                               </button>' + 
9670 '                                                       </td>' +
9671 '                                                       <td class="emailUIField" NOWRAP>' +
9672 '                                                               <div class="ac_autocomplete">' +
9673 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9674 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9675 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9676 '                                                               </div>' +
9677 '                                                       </td>' +
9678 '                                               </tr>' +
9679 '                                               <tr>' +
9680 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9681 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9682 '                                                       </td>' +
9683 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9684 '                                                               <div class="ac_autocomplete">' +
9685 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9686 '                                                               </div>' +
9687 '                                                       </td>' +
9688 '                                               </tr>' +
9689 '                                       </table>' +
9690 '                                       </div>' +
9691 '                               </td>'   +
9692 '                       </tr>' +
9693 '               </table>' +
9694 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9695 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9696 '                       <div style="padding:5px;">' +
9697 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9698 '                                       <tr>' +
9699 '                                               <th>' +
9700 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9701 '                                                       <br />' +
9702 '                                                       &nbsp;' +
9703 '                                               </th>' +
9704 '                                       </tr>' +
9705 '                                       <tr>' +
9706 '                                               <td>' +
9707 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9708 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9709 '                                               </td>' +
9710 '                                       </tr>' +
9711 '                                       <tr>' +
9712 '                                               <td>' +
9713 '                                                       &nbsp;' +
9714 '                                                       <br />' +
9715 '                                                       &nbsp;' +
9716 '                                               </td>' +
9717 '                                       </tr>' +
9718 '                                       <tr>' +
9719 '                                               <th>' +
9720 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9721 '                                                       <br />' +
9722 '                                                       &nbsp;' +
9723 '                                               </th>' +
9724 '                                       </tr>' +
9725 '                                       <tr>' +
9726 '                                               <td>' +
9727 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9728 '                                                       <div id="addedDocuments{idx}"></div>' + //<input name="document{idx}0" id="document{idx}0" type="hidden" /><input name="documentId{idx}0" id="documentId{idx}0" type="hidden" /><input name="documentName{idx}0" id="documentName{idx}0" disabled size="30" type="text" /><input type="button" id="documentSelect{idx}0" onclick="SUGAR.email2.selectDocument({idx}0, this);" class="button" value="{app_strings.LBL_EMAIL_SELECT}" /><input type="button" id="documentRemove{idx}0" onclick="SUGAR.email2.deleteDocumentField({idx}0, this);" class="button" value="{app_strings.LBL_EMAIL_REMOVE}" /><br /></div>' +
9729 '                                               </td>' +
9730 '                                       </tr>' +
9731 '                                       <tr>' +
9732 '                                               <td>' +
9733 '                                                       &nbsp;' +
9734 '                                                       <br />' +
9735 '                                                       &nbsp;' +
9736 '                                               </td>' +
9737 '                                       </tr>' +
9738 '                                       <tr>' +
9739 '                                               <th>' +
9740 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9741 '                                                       <br />' +
9742 '                                                       &nbsp;' +
9743 '                                               </th>' +
9744 '                                       </tr>' +
9745 '                                       <tr>' +
9746 '                                               <td>' +
9747 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9748 '                                               </td>' +
9749 '                                       </tr>' +
9750 '                               </table>' +
9751 '                       </div>' +
9752 '               </div>' +
9753 '       </form>' +
9754 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9755 '             <div style="padding:5px;">' +
9756 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9757 '                               <table border="0" width="100%">' +
9758 '                                       <tr>' +
9759 '                                               <td NOWRAP style="padding:2px;">' +
9760 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9761 '                                               </td>' +
9762 '                                       </tr>' +
9763 '                                       <tr>' +
9764 '                                               <td NOWRAP style="padding:2px;">' +
9765 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9766 '                                               </td>' +
9767 '                                       </tr>' +
9768 '                               </table>' +
9769 '                               <br />' +
9770 '                               <table border="0" width="100%">' +
9771 '                                       <tr>' +
9772 '                                               <td NOWRAP style="padding:2px;">' +
9773 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9774 '                                               </td>' +
9775 '                                       </tr>' +
9776 '                                       <tr>' +
9777 '                                               <td NOWRAP style="padding:2px;">' +
9778 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9779 '                                               </td>' +
9780 '                                       </tr>' +
9781 '                               </table>' +
9782 '                               <table border="0" width="100%">' +
9783 '                                       <tr>' +
9784 '                                               <td NOWRAP style="padding:2px;">' +
9785 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9786 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9787 '                                               </td>' +
9788 '                                       </tr>' +
9789 '                               </table>' +
9790 '         </form>' +
9791 '                       </div> ' +
9792 '               </div>' +
9793 '</div>';
9794 // End of File modules/Emails/javascript/composeEmailTemplate.js
9795                                 
9796 /*********************************************************************************
9797  * SugarCRM Community Edition is a customer relationship management program developed by
9798  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9799  * 
9800  * This program is free software; you can redistribute it and/or modify it under
9801  * the terms of the GNU Affero General Public License version 3 as published by the
9802  * Free Software Foundation with the addition of the following permission added
9803  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9804  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9805  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9806  * 
9807  * This program is distributed in the hope that it will be useful, but WITHOUT
9808  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9809  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9810  * details.
9811  * 
9812  * You should have received a copy of the GNU Affero General Public License along with
9813  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9814  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9815  * 02110-1301 USA.
9816  * 
9817  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9818  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9819  * 
9820  * The interactive user interfaces in modified source and object code versions
9821  * of this program must display Appropriate Legal Notices, as required under
9822  * Section 5 of the GNU Affero General Public License version 3.
9823  * 
9824  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9825  * these Appropriate Legal Notices must retain the display of the "Powered by
9826  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9827  * technical reasons, the Appropriate Legal Notices must display the words
9828  * "Powered by SugarCRM".
9829  ********************************************************************************/
9830
9831 SUGAR.email2.templates['displayOneEmail'] = 
9832 '<div class="emailDetailTable" style="height:100%">' +
9833 '<div id="viewMenuDiv{idx}"></div>' + 
9834 '<div width="100%" class="displayEmailValue">' +
9835 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.c0_replyForwardEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\', \'reply\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_reply.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_REPLY}</button>' +
9836 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.c0_replyForwardEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\', \'replyAll\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_replyall.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_REPLY_ALL}</button>' +
9837 '                                       <button type="button" class="button" onclick="SUGAR.email2.composeLayout.c0_replyForwardEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\', \'forward\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_forward.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_FORWARD}</button>' +
9838 '                                       <button type="button" class="button" onclick="SUGAR.email2.detailView.emailDeleteSingle(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_delete.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_DELETE}</button>' +
9839 '                                       <button type="button" class="button" onclick="SUGAR.email2.detailView.viewPrintable(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=Print_Email.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_PRINT}</button>' +
9840 '                                       <button id="btnEmailView{idx}" type="button" class="button" onclick="SUGAR.email2.detailView.showViewMenu(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=icon_email_view.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_VIEW} <img src="themes/default/images/more.gif" align="absmiddle" border="0"></button>' +
9841 '                                       <button id="archiveEmail{idx}" type="button" class="button" onclick="SUGAR.email2.detailView.importEmail(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="themes/default/images/icon_email_archive.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_IMPORT_EMAIL}</button>' +
9842 '                                       <button id="quickCreateSpan{meta.panelId}" type="button" class="button" onclick="SUGAR.email2.detailView.showQuickCreate(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="themes/default/images/icon_email_create.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_QUICK_CREATE} <img src="themes/default/images/more.gif" align="absmiddle" border="0"></button>' +
9843 '                                       <button type="button" id="showDeialViewForEmail{meta.panelId}" class="button" onclick="SUGAR.email2.contextMenus.showEmailDetailViewInPopup(\'{meta.ieId}\', \'{meta.uid}\', \'{meta.mbox}\');"><img src="themes/default/images/icon_email_relate.gif" align="absmiddle" border="0"> {app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS}</button>' +
9844 '</div>' +
9845 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9846 '                               <tr>' +
9847 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9848 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9849 '                                       </td>' +
9850 '                                       <td width="99%" class="displayEmailValue">' +
9851 '                                               {email.from_addr}' +
9852 '                                       </td>' +
9853 '                               </tr>' +
9854 '                               <tr>' +
9855 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9856 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9857 '                                       </td>' +
9858 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9859 '                                               <b>{email.name}</b>' +
9860 '                                       </td>' +
9861 '                               </tr>' +
9862 '                               <tr>' +
9863 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9864 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9865 '                                       </td>' +
9866 '                                       <td class="displayEmailValue">' +
9867 '                                               {email.date_start} {email.time_start}' +
9868 '                                       </td>' +
9869 '                               </tr>' +
9870 '                               <tr>' +
9871 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9872 '                                               {app_strings.LBL_EMAIL_TO}:' +
9873 '                                       </td>' +
9874 '                                       <td class="displayEmailValue">' +
9875 '                                               {email.toaddrs}' +
9876 '                                       </td>' +
9877 '                               </tr>' +
9878 '                               <tr>{meta.cc}</tr>' +
9879 '                               <tr>{email.attachments}</tr>' +
9880 '                       </table>' +
9881 '                       <div id="displayEmailFrameDiv{idx}" name="displayEmailFrameDiv{idx}"><iframe id="displayEmailFrame{idx}" src="modules/Emails/templates/_blank.html" width="100%" height="100%" frameborder="0"></iframe></div>' +
9882 //'                           {email.description}' +
9883 '</div>'
9884 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9885                                 
9886 /*********************************************************************************
9887  * SugarCRM Community Edition is a customer relationship management program developed by
9888  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9889  * 
9890  * This program is free software; you can redistribute it and/or modify it under
9891  * the terms of the GNU Affero General Public License version 3 as published by the
9892  * Free Software Foundation with the addition of the following permission added
9893  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9894  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9895  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9896  * 
9897  * This program is distributed in the hope that it will be useful, but WITHOUT
9898  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9899  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9900  * details.
9901  * 
9902  * You should have received a copy of the GNU Affero General Public License along with
9903  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9904  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9905  * 02110-1301 USA.
9906  * 
9907  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9908  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9909  * 
9910  * The interactive user interfaces in modified source and object code versions
9911  * of this program must display Appropriate Legal Notices, as required under
9912  * Section 5 of the GNU Affero General Public License version 3.
9913  * 
9914  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9915  * these Appropriate Legal Notices must retain the display of the "Powered by
9916  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9917  * technical reasons, the Appropriate Legal Notices must display the words
9918  * "Powered by SugarCRM".
9919  ********************************************************************************/
9920
9921 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9922 '<body onload="javascript:window.print();">' + 
9923 '<style>' + 
9924 'body {' + 
9925 '       margin: 0px;' + 
9926 '       font-family: helvetica, impact, sans-serif;' +
9927 '       font-size : 12pt;' +
9928 '} ' +
9929 'table {' +
9930 '       padding:10px;' +
9931 '}' +
9932 '</style>' +
9933 '<div>' +
9934 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9935 '       <tr>' +
9936 '               <td>' +
9937 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9938 '                               <tr>' +
9939 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9940 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9941 '                                       </td>' +
9942 '                                       <td width="99%" class="displayEmailValue">' +
9943 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9944 '                                       </td>' +
9945 '                               </tr>' +
9946 '                               <tr>' +
9947 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9948 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9949 '                                       </td>' +
9950 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9951 '                                               <b>{email.name}</b>' +
9952 '                                       </td>' +
9953 '                               </tr>' +
9954 '                               <tr>' +
9955 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9956 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9957 '                                       </td>' +
9958 '                                       <td class="displayEmailValue">' +
9959 '                                               {email.date_start} {email.time_start}' +
9960 '                                       </td>' +
9961 '                               </tr>' +
9962 '                               <tr>' +
9963 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9964 '                                               {app_strings.LBL_EMAIL_TO}:' +
9965 '                                       </td>' +
9966 '                                       <td class="displayEmailValue">' +
9967 '                                               {email.toaddrs}' +
9968 '                                       </td>' +
9969 '                               </tr>' +
9970 '                               {email.cc}' +
9971 '                               {email.attachments}' +
9972 '                       </table>' +
9973 '               </td>' +
9974 '       </tr>' +
9975 '       <tr>' +
9976 '               <td>' +
9977 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9978 '                               <tr>' +
9979 '                                       <td style="border-top: 1px solid #333;">' +
9980 '                                               <div style="padding:5px;">' +
9981                                                         '{email.description}' +
9982 '                                               </div>' +
9983 '                                       </td>' +
9984 '                               </tr>' +
9985 '                       </table>' +
9986 '               </td>' +
9987 '       </tr>' +
9988 '</table>' +
9989 '</div>' +
9990 '</body></html>';
9991 // End of File modules/Emails/javascript/viewPrintable.js
9992                                 
9993 /*********************************************************************************
9994  * SugarCRM Community Edition is a customer relationship management program developed by
9995  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9996  *
9997  * This program is free software; you can redistribute it and/or modify it under
9998  * the terms of the GNU Affero General Public License version 3 as published by the
9999  * Free Software Foundation with the addition of the following permission added
10000  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10001  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10002  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
10003  *
10004  * This program is distributed in the hope that it will be useful, but WITHOUT
10005  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10006  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
10007  * details.
10008  *
10009  * You should have received a copy of the GNU Affero General Public License along with
10010  * this program; if not, see http://www.gnu.org/licenses or write to the Free
10011  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
10012  * 02110-1301 USA.
10013  *
10014  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
10015  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
10016  *
10017  * The interactive user interfaces in modified source and object code versions
10018  * of this program must display Appropriate Legal Notices, as required under
10019  * Section 5 of the GNU Affero General Public License version 3.
10020  *
10021  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
10022  * these Appropriate Legal Notices must retain the display of the "Powered by
10023  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
10024  * technical reasons, the Appropriate Legal Notices must display the words
10025  * "Powered by SugarCRM".
10026  ********************************************************************************/
10027 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10028 var Dom=YAHOO.util.Dom;var qsFields=Dom.getElementsByClassName('sqsEnabled');for(var qsField in qsFields){if(typeof qsFields[qsField]=='function'||typeof qsFields[qsField].id=='undefined'){continue;}
10029 var form_id=qsFields[qsField].form.getAttribute('id');if(typeof form_id=='object'&&qsFields[qsField].form.getAttribute('real_id')){form_id=qsFields[qsField].form.getAttribute('real_id');}
10030 var qs_index_id=form_id+'_'+qsFields[qsField].name;if(typeof sqs_objects[qs_index_id]=='undefined'){qs_index_id=qsFields[qsField].name;if(typeof sqs_objects[qs_index_id]=='undefined'){continue;}}
10031 if(QSProcessedFieldsArray[qs_index_id]){skipSTR='collection_0';if(qs_index_id.lastIndexOf(skipSTR)!=(qs_index_id.length-skipSTR.length)){continue;}}
10032 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10033 if(!document.forms[qs_obj.form].elements[qsFields[qsField].id].readOnly&&qs_obj['disable']!=true){var combo_id=qs_obj.form+'_'+qsFields[qsField].id;if(Dom.get(combo_id+"_results")){loaded=true}
10034 if(!loaded){QSProcessedFieldsArray[qs_index_id]=true;qsFields[qsField].form_id=form_id;var sqs=sqs_objects[qs_index_id];var resultDiv=document.createElement('div');resultDiv.id=combo_id+"_results";Dom.insertAfter(resultDiv,qsFields[qsField]);var fields=qs_obj.field_list.slice();fields[fields.length]="module";var ds=new YAHOO.util.DataSource("index.php?",{responseType:YAHOO.util.XHRDataSource.TYPE_JSON,responseSchema:{resultsList:'fields',total:'totalCount',fields:fields,metaNode:"fields",metaFields:{total:'totalCount',fields:"fields"}},connMethodPost:true});var forceSelect=!((qsFields[qsField].form&&typeof(qsFields[qsField].form)=='object'&&qsFields[qsField].form.name=='search_form')||qsFields[qsField].className.match('sqsNoAutofill')!=null);var search=new YAHOO.widget.AutoComplete(qsFields[qsField],resultDiv,ds,{typeAhead:forceSelect,forceSelection:forceSelect,fields:fields,sqs:sqs,animSpeed:0.25,qs_obj:qs_obj,inputElement:qsFields[qsField],generateRequest:function(sQuery){var out=SUGAR.util.paramsToUrl({to_pdf:'true',module:'Home',action:'quicksearchQuery',data:encodeURIComponent(YAHOO.lang.JSON.stringify(this.sqs)),query:sQuery});return out;},setFields:function(data,filter){this.updateFields(data,filter);},updateFields:function(data,filter){for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=displayValue;SUGAR.util.callOnChangeListers(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]);}}}
10035 SUGAR.util.callOnChangeListers(this._elTextbox);},clearFields:function(){for(var key in this.qs_obj.field_list){if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";SUGAR.util.callOnChangeListers(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]);}}
10036 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10037 {search.clearFields=function(){for(var i in{name:0,id:1}){for(var key in this.qs_obj.field_list){if(i==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]])
10038 {document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}}};search.setFields=function(data,filter)
10039 {var label_str='';var label_data_str='';var current_label_data_str='';var label_data_hash=new Array();for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&document.getElementById(this.qs_obj.populate_list[key]+'_label')&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');var data_label=document.getElementById(this.qs_obj.populate_list[key]+'_label').innerHTML.replace(/\n/gi,'');label_and_data=data_label+' '+displayValue;if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&!label_data_hash[data_label])
10040 {label_str+=data_label+' \n';label_data_str+=label_and_data+'\n';label_data_hash[data_label]=true;current_label_data_str+=data_label+' '+document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value+'\n';}}}}
10041 if(label_str!=current_label_data_str&&current_label_data_str!=label_data_str){module_key=(typeof document.forms[form_id].elements['module']!='undefined')?document.forms[form_id].elements['module'].value:'app_strings';warning_label=SUGAR.language.translate(module_key,'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM')+'\n\n'+label_data_str;if(!confirm(warning_label))
10042 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10043 {if(this.inputElement.id=='shipping_account_name')
10044 {filter=Dom.get('shipping_checkbox').checked?/(account_id|office_phone)/:filter;}else if(this.inputElement.id=='billing_account_name'){filter=Dom.get('shipping_checkbox').checked?filter:/(account_id|office_phone|billing)/;}}else if(Dom.get('alt_checkbox')){filter=Dom.get('alt_checkbox').checked?filter:/^(?!alt)/;}
10045 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10046 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10047 search.itemSelectEvent.subscribe(function(e,args){var data=args[2];var fields=this.fields;this.setFields(data,/\S/);if(typeof(this.qs_obj['post_onblur_function'])!='undefined'){collection_extended=new Array();for(var i in fields){for(var key in this.qs_obj.field_list){if(fields[i]==this.qs_obj.field_list[key]){collection_extended[this.qs_obj.field_list[key]]=data[i];}}}
10048 eval(this.qs_obj['post_onblur_function']+'(collection_extended, this.qs_obj.id)');}});search.textboxFocusEvent.subscribe(function(){this.oldValue=this.getInputEl().value;});search.selectionEnforceEvent.subscribe(function(e,args){if(this.oldValue!=args[1]){this.clearFields();}else{this.getInputEl().value=this.oldValue;}});search.dataReturnEvent.subscribe(function(e,args){if(this.getInputEl().value.length==0&&args[2].length>0){var data=[];for(var key in this.qs_obj.field_list){data[data.length]=args[2][0][this.qs_obj.field_list[key]];}
10049 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});search.typeAheadEvent.subscribe(function(e,args){this.getInputEl().value=this.getInputEl().value.replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
10050 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10051 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10052 // End of File include/javascript/quicksearch.js
10053