]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.3.0RC3
[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 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
359 +'module='+module_name
360 +'&to_pdf=1'
361 +'&action='+action
362 +'&target='+pageTarget
363 +'&target1='+pageTarget
364 +'&server_url='+mail_server
365 +'&email_user='+words[0]
366 +'&protocol='+protocol
367 +'&port='+port
368 +'&email_password='+words[1]
369 +'&mailbox='+words[2]
370 +'&ssl='+ssl
371 +'&ie_id='+ie_id
372 +'&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)
373 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
374 this.body.style.width=w}}
375 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
376 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();}
377 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'));}
378 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
379 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
380 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
381 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
382 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";}
383 out+=errors[i];}
384 alert(out);return false;}else{return true;}}
385 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?'
386 +'module='+module_name
387 +'&to_pdf=1'
388 +'&action='+action
389 +'&target='+pageTarget
390 +'&target1='+pageTarget
391 +'&server_url='+mail_server
392 +'&email_user='+words[0]
393 +'&protocol='+protocol
394 +'&port='+port
395 +'&email_password='+words[1]
396 +'&mailbox='+words[2]
397 +'&ssl='+ssl
398 +'&personal='+isPersonal
399 +'&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)
400 this.body.style.width=w}}
401 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();}
402 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;}}}
403 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';}}}
404 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='';}
405 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";}}
406 // End of File modules/InboundEmail/InboundEmail.js
407                                 
408 /*********************************************************************************
409  * SugarCRM Community Edition is a customer relationship management program developed by
410  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
411  * 
412  * This program is free software; you can redistribute it and/or modify it under
413  * the terms of the GNU Affero General Public License version 3 as published by the
414  * Free Software Foundation with the addition of the following permission added
415  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
416  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
417  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
418  * 
419  * This program is distributed in the hope that it will be useful, but WITHOUT
420  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
421  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
422  * details.
423  * 
424  * You should have received a copy of the GNU Affero General Public License along with
425  * this program; if not, see http://www.gnu.org/licenses or write to the Free
426  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
427  * 02110-1301 USA.
428  * 
429  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
430  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
431  * 
432  * The interactive user interfaces in modified source and object code versions
433  * of this program must display Appropriate Legal Notices, as required under
434  * Section 5 of the GNU Affero General Public License version 3.
435  * 
436  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
437  * these Appropriate Legal Notices must retain the display of the "Powered by
438  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
439  * technical reasons, the Appropriate Legal Notices must display the words
440  * "Powered by SugarCRM".
441  ********************************************************************************/
442
443 SUGAR.email2 = {
444     cache : new Object(),
445     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
446     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
447     templates : {},
448     tinyInstances : {
449         currentHtmleditor : ''
450     },
451
452     /**
453      * preserves hits from email server
454      */ 
455     _setDetailCache : function(ret) {
456         if(ret.meta) {
457             var compKey = ret.meta.mbox + ret.meta.uid;
458
459             if(!SUGAR.email2.cache[compKey]) {
460                 SUGAR.email2.cache[compKey] = ret;
461             }
462         }
463     },
464
465     autoSetLayout : function() {
466         var c = document.getElementById('container');
467         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
468         //Ensure a minimum height.
469         tHeight = Math.max(tHeight, 550);
470         c.style.height = tHeight + "px";
471         SUGAR.email2.complexLayout.set('height', tHeight);
472         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
473         SUGAR.email2.complexLayout.render();
474         SUGAR.email2.listViewLayout.resizePreview();        
475     }
476 };
477
478
479 /**
480  * Shows overlay progress message
481  */
482
483 //overlayModal
484 SUGAR.showMessageBoxModal = function(title, body) {
485     SUGAR.showMessageBox(title, body);
486 }
487
488 //overlay
489 SUGAR.showMessageBox = function(reqtitle, body, type, additconfig) {
490     var config = { };
491     if (typeof(additconfig) == "object") {
492         var config = additconfig;
493     }
494     config.type = type;
495     config.title = reqtitle;
496     config.msg = body;
497     YAHOO.SUGAR.MessageBox.show(config);
498 }
499
500 //hideOverlay
501 SUGAR.hideMessageBox = function() {
502         YAHOO.SUGAR.MessageBox.hide();
503 };
504 // End of File modules/Emails/javascript/EmailUIShared.js
505                                 
506 /*********************************************************************************
507  * SugarCRM Community Edition is a customer relationship management program developed by
508  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
509  * 
510  * This program is free software; you can redistribute it and/or modify it under
511  * the terms of the GNU Affero General Public License version 3 as published by the
512  * Free Software Foundation with the addition of the following permission added
513  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
514  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
515  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
516  * 
517  * This program is distributed in the hope that it will be useful, but WITHOUT
518  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
519  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
520  * details.
521  * 
522  * You should have received a copy of the GNU Affero General Public License along with
523  * this program; if not, see http://www.gnu.org/licenses or write to the Free
524  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
525  * 02110-1301 USA.
526  * 
527  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
528  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
529  * 
530  * The interactive user interfaces in modified source and object code versions
531  * of this program must display Appropriate Legal Notices, as required under
532  * Section 5 of the GNU Affero General Public License version 3.
533  * 
534  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
535  * these Appropriate Legal Notices must retain the display of the "Powered by
536  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
537  * technical reasons, the Appropriate Legal Notices must display the words
538  * "Powered by SugarCRM".
539  ********************************************************************************/
540
541
542 (function() {
543         var sw = YAHOO.SUGAR,
544                 Event = YAHOO.util.Event,
545                 Connect = YAHOO.util.Connect,
546             Dom = YAHOO.util.Dom
547             SE = SUGAR.email2;
548
549 ///////////////////////////////////////////////////////////////////////////////
550 ////    EMAIL ACCOUNTS
551 SE.accounts = {
552     outboundDialog : null,
553     inboundAccountEditDialog : null,
554     inboundAccountsSettingsTable : null,
555     outboundAccountsSettingsTable : null,
556     testOutboundDialog : null,
557     errorStyle : 'input-error',
558     normalStyle : '',
559     newAddedOutboundId : '',
560
561     /**
562      * makes async call to retrieve an outbound instance for editting
563      */
564      //EXT111
565     editOutbound : function(obi) {
566
567             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
568
569     },
570     deleteOutbound : function(obi) {
571
572         if(obi.match(/^(add|line|sendmail)+/)) {
573             alert('Invalid Operation');
574         } else {
575                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
576             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
577         }
578     },
579     //EXT111
580     getReplyAddress : function() {
581         var primary = '';
582
583         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
584             var addy = SE.userPrefs.current_user.emailAddresses[i];
585
586             if(addy.primary_address == "1") {
587                 primary = addy.email_address;
588             }
589
590             if(addy.reply_to == "1") {
591                 return addy.email_address;
592             }
593         }
594
595         return primary;
596     },
597
598     /**
599      * Called on "Accounts" tab activation event
600      */
601     lazyLoad : function() {
602
603         this._setupInboundAccountTable();
604         this._setupOutboundAccountTable();
605
606     },
607
608     _setupInboundAccountTable: function()
609     {
610         //Setup the inbound mail settings
611         if(!this.inboundAccountsSettingsTable)
612         {
613                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
614                                         var clckEvent = oColumn.key;
615                                         var imgSrc = "";
616                                         var is_group = oRecord.getData("is_group");
617                                         if(!is_group)
618                                         {
619                                         if(oColumn.key == 'edit')
620                                         {
621                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
622                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
623                                         }
624                                         else if(oColumn.key == 'delete')
625                                         {
626                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
627                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
628                                         }
629                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
630                                         }
631                    };
632
633                    this.showBoolean = function(el, oRecord, oColumn, oData)
634                    {
635                        var is_group = oRecord.getData("is_group");
636                        var bChecked = oData;
637                        bChecked = (bChecked) ? " checked" : "";
638                        if(!is_group)
639                        {
640                        el.innerHTML = "<input type=\"radio\"" + bChecked +
641                            " name=\"col" + oColumn.getId() + "-radio\"" +
642                            " class=\"yui-dt-radio\">";
643                        }
644                    };
645
646
647                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
648                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
649
650                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
651                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
652                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
653
654
655                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
656                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
657                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
658                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
659                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
660                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
661                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
662                 this.ieDataSource = new YAHOO.util.DataSource(query);
663                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
664                         this.ieDataSource.responseSchema = {
665                                 resultsList: "account_list",
666                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
667                         };
668                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
669                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
670
671                     var elCheckbox = oArgs.target;
672                     var oColumn = this.getColumn(elCheckbox);
673                         if(oColumn.key == 'is_active')
674                         {
675                                 var oRecord = this.getRecord(elCheckbox);
676                                 oRecord.setData("is_active",elCheckbox.checked);
677                                 var t_id = oRecord.getData('id');
678                         var isGroupFolder = oRecord.getData('has_groupfolder');
679
680                         if(isGroupFolder)
681                             SUGAR.email2.folders.updateSubscriptions();
682                         else
683                         SUGAR.email2.folders.setFolderSelection();
684
685                         }
686                 });
687                         var lastDefaultSelectedId = "";
688                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
689
690                     var elRadio = oArgs.target;
691                     var oColumn = this.getColumn(elRadio);
692                         if(oColumn.key == 'is_default')
693                         {
694                                 var oRecord = this.getRecord(elRadio);
695                                 var t_id = oRecord.getData('id');
696                                 var t_isGroup = oRecord.getData('is_group');
697                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
698                                 {
699                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
700                                         lastDefaultSelectedId = t_id;
701                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
702                                 }
703                                 else if(t_isGroup)
704                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
705
706                         }
707                 });
708
709                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
710                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
711         }
712     },
713      _setupOutboundAccountTable: function()
714     {
715         if(!this.outboundAccountsSettingsTable)
716         {
717                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
718                                         var clckEvent = oColumn.key;
719                                         var imgSrc = "";
720                                         var isEditable = oRecord.getData("is_editable");
721                                         var type = oRecord.getData("type");
722                                         if(isEditable)
723                                         {
724                                         if(oColumn.key == 'edit')
725                                         {
726                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
727                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
728                                         }
729                                         else if(oColumn.key == 'delete' && type == 'user')
730                                         {
731                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
732                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
733                                         }
734                                         if(imgSrc != '')
735                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
736                                         }
737                 };
738
739                 //Custom formatter to display any error messages.
740                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
741
742                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
743                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
744
745                         var id = oRecord.getData('id');
746                                         var message = oRecord.getData("errors");
747                                         if(message != '')
748                                         {
749                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
750                                         //Add the id and message for all outbound accounts.
751                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
752                                         }
753                                         else
754                                         {
755                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
756                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
757                                         }
758                 };
759                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
760                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
761
762                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
763                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
764                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
765                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
766
767                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
768                 this.obDataSource = new YAHOO.util.DataSource(query);
769                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
770                         this.obDataSource.responseSchema = {
771
772                                 resultsList: "outbound_account_list",
773                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
774                         };
775
776                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
777
778
779                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
780                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
781                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
782         }
783     },
784     /**
785      * Displays a modal diaglogue to edit outbound account settings
786      */
787     showEditInboundAccountDialogue : function(clear) {
788
789         if(!this.inboundAccountEditDialog) {
790                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
791                 modal:true,
792                                 visible:true,
793                 fixedcenter:true,
794                 constraintoviewport: true,
795                 width   : "600px",
796                 shadow  : true
797             });
798                         EAD.showEvent.subscribe(function() {
799                 var el = this.element;
800                 var viewH = YAHOO.util.Dom.getViewportHeight();
801                 if (this.header && el && viewH - 50 < el.clientHeight) {
802                     var body = this.header.nextElementSibling;
803                                         body.style.overflow = "hidden";
804                     body.style.height = "100%";
805                 }
806             }, EAD);
807             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
808                         Dom.removeClass("editAccountDialogue", "yui-hidden");
809
810         } // end lazy load
811
812         if(clear == undefined || clear == true)
813         {
814                 SE.accounts.clearInboundAccountEditScreen();
815                 //Set default protocol to IMAP when creating new records
816                 document.forms['ieAccount'].elements['protocol'].value = "imap";
817                 SE.accounts.setPortDefault();
818         }
819
820         //Check if we should display username/password fields for outbound account if errors were detected.
821         this.checkOutBoundSelection();
822
823         this.inboundAccountEditDialog.render();
824         this.inboundAccountEditDialog.show();
825         SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
826     },
827
828     /**
829     *  Set all fields on the outbound edit form to either enabled/disabled
830     *  except for the username/password.
831     *
832     */
833     toggleOutboundAccountDisabledFields: function(disable)
834     {
835         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
836         for(var i=0;i<fields.length;i++)
837         {
838             document.getElementById(fields[i]).disabled = disable;
839         }
840         if(disable)
841             Dom.addClass("mail_smtpssl_row", "yui-hidden");
842         else
843             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
844
845     },
846     /**
847     * Refresh the inbound accounts table.
848     */
849     refreshInboundAccountTable : function()
850     {
851             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
852                 {
853                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
854                                 scope: this.inboundAccountsSettingsTable }
855                         );
856     },
857     /**
858     * Refresh the outbound accounts table.
859     */
860     refreshOuboundAccountTable : function()
861     {
862             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
863                 {
864                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
865                                 scope: this.outboundAccountsSettingsTable }
866                         );
867     },
868     /**
869      * Displays a modal diaglogue to add a SMTP server
870      */
871     showAddSmtp : function() {
872         // lazy load dialogue
873         if(!this.outboundDialog) {
874                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
875                 modal:true,
876                                 visible:true,
877                 fixedcenter:true,
878                 constraintoviewport: true,
879                 width   : "750px",
880                 shadow  : true
881             });
882             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
883             this.outboundDialog.hideEvent.subscribe(function(){
884                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
885                 var out = Dom.get("outbound_email");
886                 if (out && out.value == "SYSTEM_ADD")
887                 {
888                         out.value = out.options[0].value;
889                 }
890                 //Check if we should display username/password for system account.
891                 SE.accounts.checkOutBoundSelection();
892                 return true;
893             });
894
895             Dom.removeClass("outboundDialog", "yui-hidden");
896         } // end lazy load
897
898         // clear out form
899         var form = document.getElementById('outboundEmailForm');
900         for(i=0; i<form.elements.length; i++) {
901             if(form.elements[i].name == 'mail_smtpport') {
902                 form.elements[i].value = 25;
903             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
904                 form.elements[i].value = '';
905             } else if(form.elements[i].type == 'checkbox') {
906                 form.elements[i].checked = false;
907             }
908         }
909         //Render the SMTP buttons
910         if ( !SUGAR.smtpButtonGroup ) {
911             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
912             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
913             {
914                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
915                 document.getElementById('smtp_settings').style.display = '';
916                 form.mail_smtptype.value = e.newValue.get('value');
917             });
918             YAHOO.widget.Button.addHiddenFieldsToForm(form);
919         }
920         //Hide Username/Password
921         SUGAR.email2.accounts.smtp_authenticate_field_display();
922         //Unset readonly fields
923         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
924         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
925                 this.outboundDialog.render();
926         this.outboundDialog.show();
927     },
928
929     /**
930      * Accounts' Advanced Settings view toggle
931      */
932     toggleAdv : function() {
933         var adv = document.getElementById("ie_adv");
934         if(adv.style.display == 'none') {
935             adv.style.display = "";
936         } else {
937             adv.style.display = 'none';
938         }
939     },
940
941         smtp_authenticate_field_display : function() {
942                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
943                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
944                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
945         },
946         
947         smtp_setDefaultSMTPPort : function() {
948                 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
949     
950         if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
951             document.getElementById("mail_smtpport").value = '465';
952         }
953         if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
954             document.getElementById("mail_smtpport").value = '25';
955         }
956         },
957
958     /**
959      * Changes the display used in the outbound email SMTP dialog to match the
960      */
961     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
962     {
963         document.getElementById("smtpButtonGroupTD").style.display = '';
964         document.getElementById("chooseEmailProviderTD").style.display = '';
965         document.getElementById("mailsettings1").style.display = '';
966         document.getElementById("mailsettings2").style.display = '';
967         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
968         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
969         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
970         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
971
972         switch (smtptype) {
973         case "yahoomail":
974             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
975             document.getElementById("mail_smtpport").value = '465';
976             document.getElementById("mail_smtpauth_req").checked = true;
977             var ssl = document.getElementById("mail_smtpssl");
978             for(var j=0;j<ssl.options.length;j++) {
979                 if(ssl.options[j].text == 'SSL') {
980                     ssl.options[j].selected = true;
981                     break;
982                 }
983             }
984             document.getElementById("mailsettings1").style.display = 'none';
985             document.getElementById("mailsettings2").style.display = 'none';
986             document.getElementById("mail_smtppass_label").innerHTML =
987             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
988             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
989             break;
990         case "gmail":
991             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
992             document.getElementById("mail_smtpport").value = '587';
993             document.getElementById("mail_smtpauth_req").checked = true;
994             var ssl = document.getElementById("mail_smtpssl");
995             for(var j=0;j<ssl.options.length;j++) {
996                 if(ssl.options[j].text == 'TLS') {
997                     ssl.options[j].selected = true;
998                     break;
999                 }
1000             }
1001             document.getElementById("mailsettings1").style.display = 'none';
1002             document.getElementById("mailsettings2").style.display = 'none';
1003             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
1004             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
1005             break;
1006         case "exchange":
1007             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1008                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1009                 document.getElementById("mail_smtpserver").value = '';
1010             }
1011             document.getElementById("mail_smtpport").value = '25';
1012             document.getElementById("mail_smtpauth_req").checked = true;
1013             document.getElementById("mailsettings1").style.display = '';
1014             document.getElementById("mailsettings2").style.display = '';
1015             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1016             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1017             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1018             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1019             break;
1020         }
1021         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1022         {
1023             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1024             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1025             document.getElementById("mailsettings2").style.display = 'none';
1026         }
1027
1028         SUGAR.email2.accounts.smtp_authenticate_field_display();
1029         SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1030     },
1031
1032     /**
1033     * Fill the gmail default values for inbound accounts.
1034     */
1035     fillInboundGmailDefaults: function () {
1036
1037         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1038         document.forms['ieAccount'].elements['ssl'].checked = true;
1039         document.forms['ieAccount'].elements['protocol'].value = "imap";
1040         SUGAR.email2.accounts.setPortDefault();
1041         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1042     },
1043     /**
1044      * Sets Port field to selected protocol and SSL settings defaults
1045      */
1046     setPortDefault : function() {
1047         var prot = document.getElementById('protocol');
1048         var ssl  = document.getElementById('ssl');
1049         var port = document.getElementById('port');
1050         var stdPorts= new Array("110", "143", "993", "995");
1051         var stdBool    = new Boolean(false);
1052         var mailboxdiv = document.getElementById("mailboxdiv");
1053         var trashFolderdiv = document.getElementById("trashFolderdiv");
1054         var sentFolderdiv = document.getElementById("sentFolderdiv");
1055                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1056         if(port.value == '') {
1057             stdBool.value = true;
1058         } else {
1059             for(i=0; i<stdPorts.length; i++) {
1060                 if(stdPorts[i] == port.value) {
1061                     stdBool.value = true;
1062                 }
1063             }
1064         }
1065
1066         if(stdBool.value == true) {
1067             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1068                 port.value = "143";
1069             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1070                 port.value = '993';
1071             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1072                 port.value = '110';
1073             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1074                 port.value = '995';
1075             }
1076         }
1077
1078         if (prot.value == 'imap') {
1079                 mailboxdiv.style.display = "";
1080                 trashFolderdiv.style.display = "";
1081                 sentFolderdiv.style.display = "";
1082                 monitoredFolder.style.display = "";
1083                 if (document.getElementById('mailbox').value == "") {
1084                         document.getElementById('mailbox').value = "INBOX";
1085                 }
1086         } else {
1087                 mailboxdiv.style.display = "none";
1088                 trashFolderdiv.style.display = "none";
1089                 sentFolderdiv.style.display = "none";
1090                         monitoredFolder.style.display = "none";
1091                 document.getElementById('mailbox').value = "";
1092         } // else
1093     },
1094
1095     /**
1096      * Draws/removes red boxes around required fields.
1097      */
1098     ieAccountError : function(style) {
1099         document.getElementById('server_url').className = style;
1100         document.getElementById('email_user').className = style;
1101         document.getElementById('email_password').className = style;
1102         document.getElementById('protocol').className = style;
1103         document.getElementById('port').className = style;
1104     },
1105
1106     checkOutBoundSelection: function() {
1107         var select = Dom.get('outbound_email');
1108         if (!select || select.selectedIndex == -1) { return; }
1109
1110         var v = select.options[select.selectedIndex].value;
1111
1112         if(v == '')
1113         {
1114                 select.options[select.selectedIndex].selected = false;
1115                 v = select.options[0].value;
1116         }
1117         else if (v == 'SYSTEM_ADD')
1118                 SUGAR.email2.accounts.showAddSmtp();
1119
1120         var foundError = false;
1121         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1122                 for(i in errorAccounts)
1123                 {
1124                     if(v == i)
1125                     {
1126                         foundError = true;
1127                         break;
1128                     }
1129                 }
1130
1131                 //Should username/password fields for outbound account.
1132                 if(foundError)
1133                     this.toggleInboundOutboundFields(true);
1134                 else
1135                     this.toggleInboundOutboundFields(false);
1136
1137
1138
1139     },
1140     toggleInboundOutboundFields : function (display)
1141     {
1142         if(display)
1143         {
1144             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1145                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1146         }
1147         else
1148         {
1149             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1150                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1151         }
1152     },
1153     /**
1154      * rebuilds the select options for mailer options
1155      */
1156     rebuildMailerOptions : function() {
1157         var select = document.forms['ieAccount'].elements['outbound_email'];
1158         SE.util.emptySelectOptions(select);
1159
1160         //Get the available sugar mailers
1161         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1162
1163         for(i=0;i<a_outbound.length;i++)
1164         {
1165                 var t_record = a_outbound[i];
1166                 var key = t_record.getData('id');
1167                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1168
1169                 var opt = new Option(display, key);
1170                 select.options.add(opt);
1171                 if (key == SE.accounts.newAddedOutboundId) {
1172                         select.options.selectedIndex = i;
1173                 }
1174         }
1175
1176         select.options.add(new Option('',''));
1177         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1178         //Hide/Show username password fields if necessary.
1179         SE.accounts.checkOutBoundSelection();
1180     },
1181     /**
1182      * Empties all the fields in the accounts edit view
1183      */
1184     clearInboundAccountEditScreen:function() {
1185
1186         document.getElementById('ie_id').value = '';
1187         document.getElementById('ie_name').value = '';
1188         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1189         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1190         document.getElementById('reply_to_addr').value = '';
1191         document.getElementById('server_url').value = '';
1192         document.getElementById('email_user').value = '';
1193         document.getElementById('email_password').value = '';
1194         document.getElementById('port').value = '';
1195         document.getElementById('inbound_mail_smtpuser').value = '';
1196         document.getElementById('inbound_mail_smtppass').value = '';
1197         document.ieAccount.protocol.options[0].selected = true;
1198         // handle SSL
1199         document.getElementById('ssl').checked = false;
1200         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1201     },
1202
1203     /**
1204      * Populates an account's fields in Settings->Accounts
1205      */
1206     fillIeAccount:function(jsonstr) {
1207         var o = YAHOO.lang.JSON.parse(jsonstr);
1208
1209         document.getElementById('ie_id').value = o.id;
1210         document.getElementById('ie_name').value = o.name;
1211         if (o.stored_options != null) {
1212                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1213                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1214                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1215                 if (o.stored_options.trashFolder != null) {
1216                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1217                 }
1218                 if (o.stored_options.sentFolder != null) {
1219                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1220                 }
1221         }
1222         document.getElementById('server_url').value = o.server_url;
1223         document.getElementById('email_user').value = o.email_user;
1224         document.getElementById('port').value = o.port;
1225         document.getElementById('group_id').value = o.group_id;
1226         document.getElementById('mailbox').value = o.mailbox;
1227
1228
1229         var i = 0;
1230
1231         // handle SSL
1232         if(typeof(o.service[2]) != 'undefined') {
1233             document.getElementById('ssl').checked = true;
1234         }
1235
1236         // handle protocol
1237         if(document.getElementById('protocol').value != o.protocol) {
1238             var prot = document.getElementById('protocol');
1239             for(i=0; i<prot.options.length; i++) {
1240                 if(prot.options[i].value == o.service[3]) {
1241                     prot.options[i].selected = true;
1242                     this.setPortDefault();
1243                 }
1244             }
1245         }
1246  // handle SMTP selection
1247         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1248             var opts = document.getElementById('outbound_email').options;
1249             for(i=0; i<opts.length; i++) {
1250                 if(opts[i].value == o.stored_options.outbound_email) {
1251                     opts[i].selected = true;
1252                 }
1253             }
1254         }
1255     },
1256
1257     deleteIeAccount : function(IeAccountID,IeGroupID) {
1258         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1259         {
1260             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1261
1262             AjaxObject.target = 'frameFlex';
1263             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1264             SUGAR.email2.accounts.refreshInboundAccountTable();
1265          }
1266      },
1267
1268        // Null check for Outbound Settings.
1269     checkOutboundSettings: function() {
1270         var errorMessage = '';
1271         var isError = false;
1272         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1273             var mailName = document.getElementById('mail_name').value;
1274             var smtpServer = document.getElementById('mail_smtpserver').value;
1275             var smtpPort = document.getElementById('mail_smtpport').value;
1276
1277             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1278             if(trim(mailName) == '') {
1279                 isError = true;
1280                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1281             }
1282             if(trim(smtpServer) == '') {
1283                 isError = true;
1284                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1285             }
1286             if(trim(smtpPort) == '') {
1287                 isError = true;
1288                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1289             }
1290             if(mailsmtpauthreq.checked) {
1291                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1292                     isError = true;
1293                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1294                 }
1295             }
1296         }
1297         if(isError) {
1298             SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1299             return false;
1300         } else {
1301             return true;
1302         }
1303     },
1304
1305     testOutboundSettings: function() {
1306         var errorMessage = '';
1307         var isError = false;
1308         var fromAddress = document.getElementById("outboundtest_from_address").value;
1309         if (trim(fromAddress) == "") {
1310             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1311             SUGAR.showMessageBox(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1312             return false;
1313
1314         }
1315         else if (!isValidEmail(fromAddress)) {
1316             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1317             SUGAR.showMessageBox(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1318             return false;
1319         }
1320
1321         //Hide the dialogue and show an in progress indicator.
1322         SE.accounts.testOutboundDialog.hide();
1323         SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1324
1325         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1326         //nothing is sent in the request.
1327         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1328         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1329
1330         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1331         if(outboundType == 'system-override')
1332             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1333
1334         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1335         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1336
1337     },
1338
1339     testOutboundSettingsDialog: function() {
1340         //Ensure that all settings are correct before proceeding to send test email.
1341         if(!SE.accounts.checkOutboundSettings())
1342             return;
1343
1344         // lazy load dialogue
1345         if(!SE.accounts.testOutboundDialog) {
1346                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1347                 modal:true,
1348                                 visible:true,
1349                 fixedcenter:true,
1350                 constraintoviewport: true,
1351                 width   : 600,
1352                 shadow  : true
1353             });
1354             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1355             Dom.removeClass("testOutboundDialog", "yui-hidden");
1356         } // end lazy load
1357         SE.accounts.testOutboundDialog.render();
1358         SE.accounts.testOutboundDialog.show();
1359     },
1360
1361     /**
1362      * Saves Outbound email settings
1363      */
1364     saveOutboundSettings : function() {
1365         if(SE.accounts.checkOutboundSettings()) {
1366             //Enable the form fields for the post.
1367             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1368             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1369             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1370         } else {
1371             return false;
1372         }
1373     },
1374
1375     saveIeAccount : function() {
1376
1377         //Before saving check if there are any error messages associated with the outbound account.
1378         var outboundID = document.getElementById('outbound_email').value;
1379
1380         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1381             'validateSMTPCreds':true}) )
1382         {
1383             document.getElementById('saveButton').disabled = true;
1384
1385             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1386
1387             var formObject = document.getElementById('ieAccount');
1388             YAHOO.util.Connect.setForm(formObject);
1389
1390             AjaxObject._reset();
1391             AjaxObject.target = 'frameFlex';
1392             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1393         }
1394     },
1395
1396     testSettings : function() {
1397         form = document.getElementById('ieAccount');
1398
1399         if(SE.accounts.checkIeCreds()) {
1400             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);
1401         }
1402     },
1403
1404     getFoldersListForInboundAccountForEmail2 : function() {
1405         form = document.getElementById('ieAccount');
1406         if(SE.accounts.checkIeCreds()) {
1407                 var mailBoxValue = form.mailbox.value;
1408                 if (form.searchField.value.length > 0) {
1409                         mailBoxValue = "";
1410                 } // if
1411             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 );
1412         } // if
1413
1414     },
1415
1416     checkIeCreds : function(validateRules) {
1417         if(typeof(validateRules) == 'undefined')
1418             validateRules = {};
1419
1420         var errors = new Array();
1421         var out = new String();
1422
1423         var ie_name = Dom.get('ie_name').value;
1424         var fromAddress = Dom.get('ie_from_addr').value;
1425         var server_url = Dom.get('server_url').value;
1426         var email_user = Dom.get('email_user').value;
1427         var email_password = Dom.get('email_password').value;
1428         var protocol = Dom.get('protocol').value;
1429         var port = Dom.get('port').value;
1430         var oe = Dom.get('outbound_email');
1431
1432         // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1433         // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1434         // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1435         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;
1436
1437         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1438         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1439
1440         //If the username and password were provided then ignore the error messge
1441
1442         var outboundCredentialsFound = false;
1443
1444         if(outboundUserName != "" && outboundPass != "")
1445             outboundCredentialsFound = true;
1446
1447         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1448
1449         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1450              && validateSMTPCreds)
1451         {
1452             if(trim(outboundUserName) == "") {
1453                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1454             }
1455             if(trim(outboundPass) == "") {
1456                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1457             }
1458         }
1459
1460         if(trim(ie_name) == "") {
1461             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1462         }
1463
1464         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1465         {
1466             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1467                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1468             }
1469         }
1470
1471
1472         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1473              || trim(oe_value) == "SYSTEM_ADD") ) {
1474             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1475         }
1476         if(trim(server_url) == "") {
1477             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1478         }
1479         if(trim(email_user) == "") {
1480             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1481         }
1482         if(protocol == "") {
1483             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1484         }
1485         if (protocol == 'imap') {
1486                 var mailbox = document.getElementById('mailbox').value;
1487                 if (trim(mailbox) == "") {
1488                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1489                 } // if
1490                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1491                         var trashFolder = document.getElementById('trashFolder').value;
1492                         if (trim(trashFolder) == "") {
1493                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1494                         } // if
1495                         } // if
1496         }
1497         if(port == "") {
1498             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1499         }
1500
1501         if(errors.length > 0) {
1502             out = app_strings.LBL_EMAIL_ERROR_DESC;
1503             for(i=0; i<errors.length; i++) {
1504                 if(out != "") {
1505                     out += "\n";
1506                 }
1507                 out += errors[i];
1508             }
1509
1510             alert(out);
1511             return false;
1512         } else {
1513
1514             return true;
1515         }
1516     },
1517
1518     getIeAccount : function(ieId) {
1519         if(ieId == '')
1520             return;
1521
1522         SUGAR.showMessageBox(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1523                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1524
1525         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1526     },
1527
1528     /**
1529      * Iterates through TreeView nodes to apply styles dependent nature of node
1530      */
1531     renderTree:function() {
1532         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1533         SE.tree.render();
1534     },
1535
1536     //Sets the style for any nodes that need it.
1537     setNodeStyle : function(node) {
1538         if (!node.data.origText) {
1539             node.data.origText = node.data.text;
1540         }
1541         //Set unread
1542         if (typeof(node.data.unseen) != 'undefined') {
1543                 if (node.data.unseen > 0) {
1544                                 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1545                 // Add bold style to label, kinda hacky
1546                 node.labelStyle += " ygtvlabelbold";
1547                         }
1548                         else {
1549                                 node.setUpLabel(node.data.origText);
1550                         }
1551         } else {
1552                 node.setUpLabel(node.data.origText);
1553         }
1554         SE.accounts.setupDDTarget(node);
1555     },
1556
1557     setupDDTarget : function(node) {
1558         if (node.ddTarget) {
1559                 node.ddTarget.removeFromGroup();
1560                 delete node.ddTarget;
1561         }
1562         var id = node.getElId();
1563         var num = id.substring(4);
1564         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1565                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1566                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1567
1568                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1569         }
1570         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1571                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1572         }
1573     },
1574
1575     /**
1576      * Async call to rebuild the folder list.  After a folder delete or account delete
1577      */
1578     rebuildFolderList : function() {
1579         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1580         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1581     },
1582
1583     /**
1584      * Returns the number of remote accounts the user has active.
1585      */
1586     getAccountCount : function() {
1587         var tree = SE.tree;
1588         var count = 0;
1589         for(i=0; i<tree._nodes.length; i++) {
1590             var node = tree._nodes[i];
1591
1592             if(typeof(node) != 'undefined' && node.data.ieId) {
1593                 count++;
1594             }
1595         }
1596         return count;
1597     }
1598 };
1599 ////    END ACCOUNTS
1600 ///////////////////////////////////////////////////////////////////////////////
1601
1602
1603
1604
1605 ///////////////////////////////////////////////////////////////////////////////
1606 ////    CONTEXT MENU CALLS
1607 SE.contextMenus = {
1608
1609     assignToDialogue : null,
1610     /**
1611      * Archives from context menu
1612      * @param Array uids
1613      * @param string ieId
1614      * @param string folder
1615      */
1616     _archiveToSugar : function(uids, ieId, folder) {
1617         var ser = '';
1618
1619         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1620             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1621             ser += uids[i];
1622         }
1623         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1624     },
1625
1626     /**
1627      * Archives from context menu
1628      */
1629     archiveToSugar : function(menuItem) {
1630         SE.contextMenus.emailListContextMenu.hide();
1631
1632         var rows = SE.grid.getSelectedRows();
1633         var uids = [];
1634         /* iterate through available rows JIC a row is deleted - use first available */
1635         for(var i=0; i<rows.length; i++) {
1636             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1637         }
1638         var data = SE.grid.getRecord(rows[0]).getData();
1639         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1640     },
1641
1642     /**
1643      * Popup the printable version and start system's print function.
1644      */
1645     viewPrintable : function(menuItem) {
1646         var rows = SE.grid.getSelectedRows();
1647         var data = SE.grid.getRecord(rows[0]).getData();
1648         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1649     },
1650
1651     /**
1652      * Marks email flagged on mail server
1653      */
1654     markRead : function(type, contextMenuId) {
1655         SE.contextMenus.markEmail('read');
1656     },
1657
1658     /**
1659      * Assign this emails to people based on assignment rules
1660      */
1661     assignEmailsTo : function(type, contextMenuId) {
1662         if(!SE.contextMenus.assignToDialogue)
1663         {
1664                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1665                 modal:true,
1666                                 visible:false,
1667                 fixedcenter:true,
1668                 constraintoviewport: true,
1669                 width   : "600px",
1670                 shadow  : true
1671             });
1672             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1673             enableQS(true);
1674         }
1675
1676         Dom.removeClass("assignToDiv", "yui-hidden");
1677         SE.contextMenus.assignToDialogue.render();
1678         SE.contextMenus.assignToDialogue.show();
1679     },
1680
1681     /**
1682      * Marks email flagged on mail server
1683      */
1684     markFlagged : function(contextMenuId) {
1685         SE.contextMenus.markEmail('flagged');
1686     },
1687
1688     /**
1689      * Marks email unflagged on mail server
1690      */
1691     markUnflagged : function(contextMenuId) {
1692         SE.contextMenus.markEmail('unflagged');
1693     },
1694
1695     /**
1696      * Marks email unread on mail server
1697      */
1698     markUnread : function() {
1699         SE.contextMenus.markEmail('unread');
1700     },
1701
1702     /**
1703      * Deletes an email from context menu
1704      */
1705     markDeleted : function() {
1706         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1707                 document.getElementById('_blank').innerHTML = "";
1708                 SE.contextMenus.markEmail('deleted');
1709         }
1710     },
1711
1712     /**
1713      * generic call API to apply a flag to emails on the server and on sugar
1714      * @param string type "read" | "unread" | "flagged" | "deleted"
1715      */
1716     markEmail : function(type) {
1717         SE.contextMenus.emailListContextMenu.hide();
1718
1719         //var dm = SE.grid.getStore();
1720         //var uids = SE.grid.getSelectedRowIds();
1721         //var indexes = SE.grid.getSelectedRowIndexes();
1722         var rows = SE.grid.getSelectedRows();
1723         if (rows.length == 0)
1724                 rows = [SE.contextMenus.currentRow];
1725         var ser = [ ];
1726
1727         for(var i=0; i<rows.length; i++) {
1728             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1729         }
1730
1731         ser = YAHOO.lang.JSON.stringify(ser);
1732
1733         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1734         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1735
1736
1737         var count = 0;
1738
1739
1740         if(type == 'read' || type == 'deleted') {
1741             // mark read
1742             for(var j=0; j<rows.length; j++) {
1743                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1744                     count = count + 1;
1745                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1746                 }
1747             }
1748            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1749             if(ieId){
1750             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1751             var unseenCount = node.data.unseen;
1752             if (isNaN(unseenCount)) {
1753                 unseenCount = 0;
1754             }
1755             var finalCount = parseInt(unseenCount) - count;
1756             node.data.unseen = finalCount;
1757
1758             SE.accounts.renderTree();
1759             }
1760         } else if(type == 'unread') {
1761             // mark unread
1762             for(var j=0; j<rows.length; j++) {
1763                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1764                     count = count + 1;
1765                 }
1766             }
1767
1768             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1769             var unseenCount = node.data.unseen;
1770             if (isNaN(unseenCount)) {
1771                 unseenCount = 0;
1772             }
1773             var finalCount = parseInt(unseenCount) + count;
1774             node.data.unseen = finalCount;
1775             SE.accounts.renderTree();
1776         }
1777
1778         if (type == 'unread') {
1779                 for(var i=0; i<rows.length; i++) {
1780                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1781                 } // for
1782         }
1783
1784                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1785         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1786     },
1787
1788     /**
1789      * refreshes the ListView to show changes to cache
1790      */
1791     markEmailCleanup : function() {
1792         SE.accounts.renderTree();
1793         SUGAR.hideMessageBox();
1794         SE.listView.refreshGrid();
1795     },
1796
1797         showAssignmentDialog : function() {
1798                 if (SE.contextMenus.assignmentDialog == null) {
1799                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1800                 } else {
1801                         SE.contextMenus.assignmentDialog.show();
1802                 } // else
1803         },
1804
1805         /**
1806      * shows the import dialog with only relate visible.
1807      */
1808     relateTo : function() {
1809         SE.contextMenus.emailListContextMenu.hide();
1810
1811         var rows = SE.grid.getSelectedRows();
1812         var data = SE.grid.getRecord(rows[0]).getData();
1813         var ieId = data.ieId;
1814         var folder = data.mbox;
1815         var uids = [];
1816         /* iterate through available rows JIC a row is deleted - use first available */
1817         for(var i=0; i<rows.length; i++) {
1818             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1819         }
1820         var ser = YAHOO.lang.JSON.stringify(uids);
1821         
1822         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1823     },
1824
1825         /**
1826      * shows the import dialog with only relate visible.
1827      */
1828     showDetailView : function() {
1829         SE.contextMenus.emailListContextMenu.hide();
1830         var rows = SE.grid.getSelectedRows();
1831         if (rows.length > 1) {
1832                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1833                 return;
1834         }
1835         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1836         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1837         /* iterate through available rows JIC a row is deleted - use first available */
1838         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1839         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1840     },
1841
1842     /**
1843      *
1844      */
1845     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1846         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1847         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1848     },
1849
1850     /**
1851      * Opens multiple messages from ListView context click
1852      */
1853     openMultiple : function() {
1854         SE.contextMenus.emailListContextMenu.hide();
1855
1856         var rows = SE.grid.getSelectedRows();
1857         var uids = SE.listView.getUidsFromSelection();
1858
1859         if(uids.length > 0) {
1860             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1861             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1862             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1863         }
1864     },
1865
1866     /**
1867      * Replies/forwards email
1868      */
1869     replyForwardEmailContext : function() {
1870         SE.contextMenus.emailListContextMenu.hide();
1871
1872         var indexes = SE.grid.getSelectedRows();
1873         //var dm = SE.grid.getDataModel();
1874         var type = this.id;
1875
1876         for(var i=0; i<indexes.length; i++) {
1877             var row = SE.grid.getRecord(indexes[i]).getData();
1878             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1879         }
1880     },
1881
1882     //show menu functions
1883     showEmailsListMenu : function(grid, row) {
1884
1885        var data = row.getData();
1886        var draft = (data.type == "draft");
1887        var menu = SE.contextMenus.emailListContextMenu;
1888        var folderNode;
1889
1890        if (SE.tree)
1891        {
1892                if (data.mbox == 'sugar::Emails')
1893                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1894                else
1895                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1896
1897                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1898                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1899                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1900                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1901                else
1902                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1903        }
1904        else
1905            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1906
1907        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1908        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1909        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1910        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1911        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1912
1913
1914        if (data.mbox == "sugar::Emails")
1915        {
1916            //Allow users to reassign imported emails
1917            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1918            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1919            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1920            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1921        }
1922        else
1923        {
1924            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1925            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1926        }
1927     },
1928
1929     showFolderMenu : function(grid, rowIndex, event) {
1930        event.stopEvent();
1931        var coords = event.getXY();
1932        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1933     }
1934 };
1935
1936 SE.contextMenus.dv = {
1937     archiveToSugar : function(contextMenuId) {
1938
1939         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1940     },
1941
1942     replyForwardEmailContext : function(all) {
1943         SE.contextMenus.detailViewContextMenu.hide();
1944     }
1945
1946 };
1947
1948
1949
1950
1951
1952 ////    END SE.contextMenus
1953 ///////////////////////////////////////////////////////////////////////////////
1954
1955
1956
1957 ///////////////////////////////////////////////////////////////////////////////
1958 ////    DETAIL VIEW
1959 SE.detailView = {
1960     consumeMetaDetail : function(ret) {
1961         // handling if the Email drafts
1962         if(ret.type == 'draft') {
1963             SE.composeLayout.c0_composeDraft();
1964             return;
1965         }
1966
1967
1968         // cache contents browser-side
1969         SE._setDetailCache(ret);
1970
1971         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1972         // 2 below must be in global context
1973         meta = ret.meta;
1974         meta['panelId'] = SE.util.getPanelId();
1975
1976         email = ret.meta.email;
1977         var out = displayTemplate.exec({
1978             'app_strings' : app_strings,
1979             'theme' : theme,
1980             'idx' : targetDiv.id,
1981             'meta' : meta,
1982             'email' : meta.email,
1983             'linkBeans' : linkBeans
1984         });
1985         var tabLabel = meta.email.name;
1986         if (tabLabel != null && tabLabel.length > 25) {
1987                 tabLabel = tabLabel.substring(0, 25) + "...";
1988         } // if
1989         targetDiv.set("label", tabLabel);
1990         targetDiv.set("content", out);
1991
1992         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1993         if (SUGAR.email2.util.isIe()) {
1994                 displayEmailFrameDiv.style.height = "390px";
1995         } else {
1996                 displayEmailFrameDiv.style.height = "410px";
1997         }
1998
1999         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
2000         displayFrame.contentWindow.document.write(email.description);
2001         displayFrame.contentWindow.document.close();
2002
2003         // hide archive links
2004         if(ret.meta.is_sugarEmail) {
2005                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
2006             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2007         } else {
2008             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2009                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2010         } // else
2011
2012     },
2013
2014     consumeMetaPreview : function(ret) {
2015         // cache contents browser-side
2016         SE._setDetailCache(ret);
2017
2018
2019
2020         var currrow = SE.grid.getLastSelectedRecord();
2021         currrow = SE.grid.getRecord(currrow);
2022         if (!currrow) {
2023             document.getElementById('_blank').innerHTML = '';
2024             return;
2025         }
2026         // handling if the Email drafts
2027         if(ret.type == 'draft'){
2028             if (currrow.getData().uid == ret.uid) {
2029                 SE.composeLayout.c0_composeDraft();
2030             }
2031             return;
2032         }
2033
2034         if (currrow.getData().uid != ret.meta.uid) {
2035            return;
2036         }
2037
2038         // remove loading sprite
2039         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2040         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2041         meta = ret.meta;
2042         meta['panelId'] = SE.util.getPanelId();
2043         email = ret.meta.email;
2044
2045         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2046             'app_strings' : app_strings,
2047             'theme' : theme,
2048             'idx' : 'Preview',
2049             'meta' : meta,
2050             'email' :meta.email,
2051             'linkBeans' : linkBeans
2052         });
2053        // document.getElementById('_blank').innerHTML = meta.email;
2054        /* displayTemplate.append('_blank', {
2055             'app_strings' : app_strings,
2056             'theme' : theme,
2057             'idx' : 'Preview',
2058             'meta' : meta,
2059             'email' :meta.email,
2060             'linkBeans' : linkBeans
2061         });*/
2062
2063         var displayFrame = document.getElementById('displayEmailFramePreview');
2064         displayFrame.contentWindow.document.write(email.description);
2065         displayFrame.contentWindow.document.close();
2066
2067         SE.listViewLayout.resizePreview();
2068
2069         // hide archive links
2070         if(ret.meta.is_sugarEmail) {
2071             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2072             document.getElementById("btnEmailViewPreview").style.display = "none";
2073             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2074         } else {
2075           //hide view relationship link
2076                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2077         }
2078     },
2079
2080     /**
2081      * wraps emailDelete() for single messages, comes from preview or tab
2082      */
2083     emailDeleteSingle : function(ieId, uid, mbox) {
2084         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2085             // find active panel and close if the user double clicked the email to view.
2086             var activeTabId = SE.util.getPanelId();
2087             if(activeTabId != 'Preview')
2088                 SE.innerLayout.get("activeTab").close();
2089
2090             document.getElementById('_blank').innerHTML = "";
2091                 var ser = [ ];
2092                         ser.push(uid);
2093                 uid = YAHOO.lang.JSON.stringify(ser);
2094             this.emailDelete(ieId, uid, mbox);
2095         }
2096     },
2097
2098     /**
2099      * Sends async call to delete a given message
2100      * @param
2101      */
2102     emailDelete : function(ieId, uid, mbox) {
2103        SUGAR.showMessageBox(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2104        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2105            uid + "&ieId=" + ieId + "&folder=" + mbox);
2106     },
2107
2108     /**
2109      * retrieves one email to display in the preview pane.
2110      */
2111     getEmailPreview : function() {
2112         var row = SUGAR.email2.listView.currentRow;
2113         var data = row.getData();
2114             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2115                var setRead = (data['seen'] == 0) ? true : false;
2116                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2117                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2118             }
2119     },
2120
2121     /**
2122      * Imports one email into Sugar
2123      */
2124     importEmail : function(ieId, uid, mbox) {
2125         SE.util.clearHiddenFieldValues('emailUIForm');
2126
2127         SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2128
2129         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2130         AjaxObject.target = '';
2131         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2132     },
2133
2134     /**
2135      * Populates the frameFlex div with the contents of an email
2136      */
2137     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2138         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2139
2140         var mboxStr = new String(mbox);
2141         var compKey = mbox + uid;
2142
2143         if(setRead == true) {
2144                 SE.listView.boldUnreadRows()
2145                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2146         }
2147
2148         if(destination == SE.innerLayout) {
2149                 /*
2150              * loading email into a tab, peer with ListView
2151              * targetDiv must remain in the global namespace as it is used by AjaxObject
2152              */
2153                 //Check if we already have a tab of the email open
2154                 var tabs = SE.innerLayout.get("tabs");
2155                 for (var t in tabs) {
2156                         if (tabs[t].id && tabs[t].id == uid) {
2157                                 SE.innerLayout.set("activeTab", tabs[t]);
2158                                 return;
2159                         }
2160                 }
2161
2162                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2163                                 label: loadingSprite,
2164                                         scroll : true,
2165                                         content : "",
2166                                         active : true
2167                 }, SE.innerLayout);
2168                 targetDiv.id = uid;
2169                 SE.innerLayout.addTab(targetDiv);
2170
2171             // use cache if available
2172             if(SE.cache[compKey]) {
2173                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2174             } else {
2175                 // open email as peer-tab to listView
2176                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2177                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2178             }
2179         } else {
2180             // loading email into preview pane
2181             document.getElementById('_blank').innerHTML = loadingSprite;
2182
2183             // use cache if available
2184             if(SE.cache[compKey]) {
2185                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2186             } else {
2187                 AjaxObject.forceAbort = true;
2188                 // open in preview window
2189                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2190                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2191             }
2192         }
2193     },
2194
2195     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2196     {
2197         if(mboxStr.substring(0,7) == 'sugar::') {
2198             // display an email from Sugar
2199             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2200         } else {
2201             // display an email from an email server
2202             document.getElementById('emailUIAction').value = 'getSingleMessage';
2203         }
2204         document.getElementById('mbox').value = mbox;
2205         document.getElementById('ieId').value = ieId;
2206         document.getElementById('uid').value = uid;
2207
2208         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2209
2210         AjaxObject.forceAbort = true;
2211         AjaxObject.target = '_blank';
2212         AjaxObject.startRequest(callback, null);
2213     },
2214
2215     /**
2216      * Retrieves multiple emails for DetailView
2217      */
2218     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2219         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2220         SE.util.clearHiddenFieldValues('emailUIForm');
2221
2222         var mboxStr = new String(mbox);
2223
2224         uids = SE.util.cleanUids(uids);
2225
2226         if(mboxStr.substring(0,7) == 'sugar::') {
2227             // display an email from Sugar
2228             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2229             document.getElementById('uid').value = uids;
2230         } else {
2231             // display an email from an email server
2232             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2233             document.getElementById('mbox').value = mbox;
2234             document.getElementById('ieId').value = ieId;
2235             document.getElementById('uid').value = uids;
2236         }
2237
2238         var formObject = document.getElementById('emailUIForm');
2239         YAHOO.util.Connect.setForm(formObject);
2240
2241         AjaxObject.target = 'frameFlex';
2242         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2243
2244         if(setRead == true) {
2245             var c = uids.split(",");
2246             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2247         }
2248     },
2249
2250     /**
2251      * Makes async call to get QuickCreate form
2252      * Renders a modal edit view for a given module
2253      */
2254     quickCreate : function(module, ieId, uid, mailbox) {
2255         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2256
2257         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2258             get += "&sugarEmail=true";
2259         }
2260
2261         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2262     },
2263
2264     /**
2265      * Makes async call to save a quick create
2266      * @param bool
2267      */
2268     saveQuickCreate : function(action) {
2269         var qcd = SE.detailView.quickCreateDialog;
2270         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2271                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2272                 var theCallback = callbackQuickCreateSave;
2273                 var accountType = '&sugarEmail=true';
2274                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2275                    accountType = '&ieId=' + qcd.ieId;
2276                 }
2277
2278             if (action == 'reply') {
2279                    theCallback = callbackQuickCreateSaveAndReply;
2280                 } else if (action == true) {
2281                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2282                 }
2283                 formObject.action.value = 'EmailUIAjax';
2284                 YAHOO.util.Connect.setForm(formObject);
2285                 SUGAR.showMessageBox('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2286                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2287                                        accountType + '&mbox=' + qcd.mbox);
2288         }
2289     },
2290
2291     /**
2292      * Code to show/hide long list of email address in DetailView
2293      */
2294     showCroppedEmailList : function(el) {
2295         el.style.display = 'none';
2296         el.previousSibling.style.display = 'inline'
2297     },
2298     showFullEmailList : function(el) {
2299         el.style.display = 'none';
2300         el.nextSibling.style.display = 'inline';
2301     },
2302
2303     /**
2304      * Shows the QuickCreate overlay
2305      * @param string ieId
2306      * @param string uid
2307      * @param string mailbox
2308      */
2309     showQuickCreate : function(ieId, uid, mailbox) {
2310         var panelId = SE.util.getPanelId();
2311         var context = document.getElementById("quickCreateSpan" + panelId);
2312
2313         if (!SE.detailView.cqMenus)
2314                 SE.detailView.cqMenus = {};
2315
2316         if (SE.detailView.cqMenus[context])
2317                 SE.detailView.cqMenus[context].destroy();
2318
2319             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2320                 lazyload:true,
2321                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2322         });
2323
2324             for (var i=0; i < this.qcmodules.length; i++) {
2325             var module = this.qcmodules[i];
2326             menu.addItem({
2327                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2328                 modulename: module,
2329                 value: module,
2330                 onclick: { fn: function() {
2331                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2332                         }
2333                 }
2334             });
2335         }
2336
2337                 menu.render(document.body);
2338                 menu.show();
2339     },
2340
2341     /**
2342      * Displays the "View" submenu in the detailView
2343      * @param string ieId
2344      * @param string uid
2345      * @param string mailbox
2346      */
2347     showViewMenu : function(ieId, uid, mailbox) {
2348         var panelId = SE.util.getPanelId();
2349         var context = "btnEmailView" + panelId;
2350         if (!SE.detailView.viewMenus)
2351                 SE.detailView.viewMenus = {};
2352
2353         if (SE.detailView.viewMenus[context])
2354                 SE.detailView.viewMenus[context].destroy();
2355
2356             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2357                 lazyload:true,
2358                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2359                 clicktohide: true
2360         });
2361                 menu.addItems(
2362                                 (ieId == 'null' || ieId == null) ?
2363                         //No ieId - Sugar Email
2364                         [{
2365                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2366                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2367             }]
2368                         :
2369                         //IeID exists, on a remote server
2370                         [{
2371                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2372                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2373             },{
2374                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2375                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2376             }]
2377         );
2378                 menu.render(document.body);
2379                 menu.show();
2380
2381
2382         /*
2383         //#23108 jchi@07/17/2008
2384         menu.render('quickCreateSpan'+ panelId);*/
2385         //this.viewMenu = menu;
2386         //this.viewMenu.show(context);
2387     },
2388     /**
2389      * Makes async call to get an email's headers
2390      */
2391     viewHeaders : function(ieId, uid, mailbox) {
2392         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2393         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2394     },
2395
2396     /**
2397      * Makes async call to get a printable version
2398      */
2399     viewPrintable : function(ieId, uid, mailbox) {
2400         if(mailbox == 'sugar::Emails') {
2401             // display an email from Sugar
2402             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2403         } else {
2404             // display an email from an email server
2405             var emailUIAction = '&emailUIAction=getSingleMessage';
2406         }
2407
2408         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2409         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2410     },
2411
2412     /**
2413      * Makes async call to get an email's raw source
2414      */
2415     viewRaw : function(ieId, uid, mailbox) {
2416         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2417         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2418     },
2419
2420     /**
2421      * Display all email addresses in detailview.
2422      */
2423     displayAllAddrs : function(el) {
2424         el.style.display = 'none';
2425         Dom.getNextSibling(el).style.display = 'inline';
2426     }
2427 };
2428 ////    END SE.detailView
2429 ///////////////////////////////////////////////////////////////////////////////
2430
2431
2432
2433 ///////////////////////////////////////////////////////////////////////////////
2434 ////    SE.folders
2435 SE.folders = {
2436     contextMenuFocus : new Object(),
2437
2438     /**
2439      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2440      * SugarFolder ID - folder strings
2441      */
2442     _createFolderId : function(node) {
2443         var ret = '';
2444
2445         if(!node.data.id)
2446             return ret;
2447
2448         if(node.data.ieId) {
2449             /* we have a local Sugar folder */
2450             if(node.data.ieId == 'folder') {
2451                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2452             } else if(node.data.ieId.match(SE.reGUID)) {
2453                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2454             }
2455         } else {
2456             ret = node.data.id;
2457         }
2458
2459         return ret;
2460     },
2461
2462     addChildNode : function(parentNode, childNode) {
2463         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2464         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2465         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2466
2467         if(childNode.nodes) {
2468             if(childNode.nodes.length > 0) {
2469                 for(j=0; j<childNode.nodes.length; j++) {
2470                     var newChildNode = childNode.nodes[j];
2471                     this.addChildNode(node, newChildNode);
2472                 }
2473             }
2474         }
2475     },
2476
2477     /**
2478      * Builds and returns a new TreeView Node
2479      * @param string name
2480      * @param string id
2481      * @param int is_group
2482      * @return object
2483      */
2484     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2485         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2486
2487         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2488         node.expanded = expanded;
2489         node.data = new Object;
2490         node.data['id'] = id;
2491         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2492         node.data['label'] = name;
2493         node.data['ieId'] = 'folder';
2494         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2495         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2496         node.data['unseen'] = unseen;
2497         return node;
2498     },
2499
2500     /**
2501      * ensures that a new folder has a valid name
2502      */
2503     checkFolderName : function(name) {
2504         if(name == "")
2505             return false;
2506
2507         this.folderAdd(name);
2508     },
2509
2510     /**
2511      * Pings email servers for new email - forces refresh of folder pane
2512      */
2513     checkEmailAccounts : function() {
2514         this.checkEmailAccountsSilent(true);
2515     },
2516
2517     checkEmailAccountsSilent : function(showOverlay) {
2518         if(typeof(SE.folders.checkingMail)) {
2519             clearTimeout(SE.folders.checkingMail);
2520         }
2521
2522         // don't stomp an on-going request
2523         if(AjaxObject.currentRequestObject.conn == null) {
2524             if(showOverlay) {
2525                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW,
2526                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2527             }
2528             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2529         } else {
2530             // wait 5 secs before trying again.
2531             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2532         }
2533     },
2534
2535     /**
2536      * Starts check of all email Accounts using a loading bar for large POP accounts
2537      */
2538     startEmailAccountCheck : function() {
2539         // don't do two checks at the same time
2540        if(!AjaxObject.requestInProgress()) {
2541             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2542             SE.accounts.ieIds = SE.folders.getIeIds();
2543             if (SE.accounts.ieIds.length > 0) {
2544                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2545                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2546             } else {
2547                SUGAR.hideMessageBox();
2548             }
2549         } else {
2550             // wait 5 secs before trying again.
2551             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2552         }
2553     },
2554
2555     /**
2556      * Checks a single Account check based on passed ieId
2557      */
2558      startEmailCheckOneAccount : function(ieId, synch) {
2559             if (synch) {
2560                 synch = true;
2561             } else {
2562                 synch = false;
2563             }
2564             var mbox = "";
2565             var node = SE.clickedFolderNode;
2566             if (node && !synch) {
2567                 mbox = node.data.mbox;
2568             } // if
2569             SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2570             SE.accounts.ieIds = [ieId];
2571             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2572                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2573       },
2574
2575
2576     /**
2577      * Empties trash for subscribed accounts
2578      */
2579     emptyTrash : function() {
2580         SE.contextMenus.frameFoldersContextMenu.hide();
2581         SUGAR.showMessageBox(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2582         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2583     },
2584
2585     /**
2586      * Clears Cache files of the inboundemail account
2587      */
2588     clearCacheFiles : function(ieId) {
2589         SE.contextMenus.frameFoldersContextMenu.hide();
2590         SUGAR.showMessageBox(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2591         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2592     },
2593
2594
2595     /**
2596      * Returns an array of all the active accounts in the folder view
2597      */
2598     getIeIds : function() {
2599          var ieIds = [];
2600          var root = SE.tree.getRoot();
2601          for(i=0; i < root.children.length; i++) {
2602            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2603                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2604                ieIds.push(root.children[i].children[0].data.ieId);
2605            }
2606          }
2607          return ieIds;
2608      },
2609
2610     /**
2611      * loads folder lists in Settings->Folders
2612      */
2613     lazyLoadSettings : function() {
2614         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2615         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2616     },
2617
2618     /**
2619      * After the add new folder is done via folders tab on seetings, this function should get called
2620      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2621      */
2622     loadSettingFolder : function() {
2623         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2624         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2625     },
2626
2627     /**
2628      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2629      */
2630     removeSugarFolders : function() {
2631         var tree = SE.tree;
2632         var root = tree.getRoot();
2633         var folder = SE.util.findChildNode(root, "ieId", "folder");
2634         while(folder) {
2635             tree.removeNode(folder);
2636             folder = SE.util.findChildNode(root, "ieId", "folder");
2637         }
2638         if (!root.childrenRendered) {
2639                 root.childrenRendered = true;
2640         }
2641     },
2642
2643     rebuildFolders : function(silent) {
2644       if (!silent) SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2645        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2646     },
2647
2648
2649
2650     /**
2651      * Updates TreeView with Sugar Folders
2652      */
2653     setSugarFolders : function(delay) {
2654         this.removeSugarFolders();
2655                 //AjaxObject.forceAbort = true;
2656                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2657     },
2658
2659     /**
2660      * Takes async data object and creates the sugar folders in TreeView
2661      */
2662     setSugarFoldersEnd : function(o) {
2663         var root = SE.tree.getRoot();
2664         addChildNodes(root, {nodes: o});
2665         SE.accounts.renderTree();
2666         //If nothing is loaded in the grid, load "My Inbox"
2667         if (SE.grid.params.ieId == "undefined") {
2668                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2669         }
2670     },
2671
2672     startCheckTimer : function() {
2673         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2674             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2675
2676             if(typeof(SE.folders.checkTimer) != 'undefined') {
2677                 clearTimeout(SE.folders.checkTimer);
2678             }
2679
2680             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2681             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2682             {
2683                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2684                 SE.folders.checkEmailAccountsSilent(false);
2685             }
2686         }
2687     },
2688
2689     /**
2690      * makes an async call to save user preference and refresh folder view
2691      * @param object SELECT list object
2692      */
2693     setFolderSelection : function() {
2694         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2695
2696         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2697         var a_active_accnts = "";
2698         for(i=0;i<a_rs.length;i++)
2699         {
2700                 var t_record = a_rs[i];
2701                 var is_active = t_record.getData('is_active');
2702                 if(is_active)
2703                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2704         }
2705
2706         if(a_active_accnts == "")
2707                 a_active_accnts = "&ieIdShow[]=";
2708
2709         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2710
2711         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2712     },
2713
2714     /**
2715      * makes async call to save user preference for a given node's open state
2716      * @param object node YUI TextNode object
2717      */
2718     setOpenState : function(node) {
2719         SE.util.clearHiddenFieldValues('emailUIForm');
2720         var nodePath = node.data.id;
2721         var nodeParent = node.parent;
2722
2723         while(nodeParent != null) {
2724             // root node has no ID param
2725             if(nodeParent.data != null) {
2726                 nodePath = nodeParent.data.id + "::" + nodePath;
2727             }
2728
2729             var nodeParent = nodeParent.parent;
2730         }
2731
2732         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2733         document.getElementById('focusFolder').value = nodePath;
2734
2735         if(node.expanded == true) {
2736             document.getElementById('focusFolderOpen').value = 'open';
2737         } else {
2738             document.getElementById('focusFolderOpen').value = 'closed';
2739         }
2740
2741         var formObject = document.getElementById('emailUIForm');
2742         YAHOO.util.Connect.setForm(formObject);
2743
2744         AjaxObject.startRequest(null, null);
2745     },
2746
2747     getNodeFromMboxPath : function(path) {
2748         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2749         var a = YAHOO.lang.JSON.parse(path);
2750
2751         var node = tree.getRoot();
2752
2753         var i = 0;
2754         while(i < a.length) {
2755             node = this.getChildNodeFromLabel(node, a[i]);
2756             i++;
2757         }
2758
2759         return node;
2760     },
2761
2762     getChildNodeFromLabel : function(node, nodeLabel) {
2763         for(i=0; i<node.children.length; i++) {
2764             if(node.children[i].data.id == nodeLabel) {
2765                 return node.children[i];
2766             }
2767         }
2768     },
2769
2770     /**
2771      * returns the node that presumably under the user's right-click
2772      */
2773     getNodeFromContextMenuFocus : function() {
2774         //// get the target(parent) node
2775         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2776         var index = -1;
2777         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2778
2779         // filter local folders
2780         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2781             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2782                 if(target.id == '') {
2783                     target = target.parentNode;
2784                 } else {
2785                     break;
2786                 }
2787             }
2788         }
2789
2790         var targetNode = document.getElementById(target.id);
2791         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2792
2793         try {
2794             var matches = re.exec(targetNode.id);
2795         } catch(ex) {
2796             return document.getElementById(ygtvlabelel1);
2797         }
2798
2799         if(matches) {
2800             index = matches[1];
2801         } else {
2802             // usually parent node
2803             matches = re.exec(targetNode.parentNode.id);
2804
2805             if(matches) {
2806                 index = matches[1];
2807             }
2808         }
2809
2810         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2811         parentNode.expand();
2812
2813         return parentNode;
2814     },
2815
2816     /**
2817      * Decrements the Unread Email count in folder text
2818      * @param string ieId ID to look for
2819      * @param string mailbox name
2820      * @param count how many to decrement
2821      */
2822     decrementUnreadCount : function(ieId, mbox, count) {
2823
2824         if(mbox == null)
2825             return;
2826
2827         if(mbox.indexOf("sugar::") === 0) {
2828             var node = this.getNodeFromId(ieId);
2829         } else {
2830             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2831         }
2832         if(node) {
2833             var unseen = node.data.unseen;
2834             if(unseen > 0) {
2835                 var check = unseen - count;
2836                 var finalCount = (check >= 0) ? check : 0;
2837                 node.data.unseen = finalCount;
2838             }
2839             SE.accounts.renderTree();
2840         }
2841     },
2842
2843     /**
2844      * gets the TreeView node with a given ID/ieId
2845      * @param string id ID to look for
2846      * @return object Node
2847      */
2848     getNodeFromId : function(id) {
2849         SE.folders.focusNode = null;
2850         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2851             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2852                 SE.folders.focusNode = this;
2853                 return false;
2854             }
2855         }, null, [id]);
2856         return SE.folders.focusNode;
2857     },
2858
2859     /**
2860      * Uses ieId and mailbox to try to find a node in the tree
2861      */
2862     getNodeFromIeIdAndMailbox : function(id, mbox) {
2863                 SE.folders.focusNode = null;
2864         if (mbox == "sugar::Emails") {
2865                 mbox = id;
2866                 id = "folder";
2867         } // if
2868         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2869                 if (varsarray instanceof Array) {
2870             if (this.data.ieId && this.data.ieId == varsarray[0]
2871                     && this.data.mbox == varsarray[1]) {
2872                 SE.folders.focusNode = this;
2873                 return false;
2874             } }
2875                 else {
2876                         if (this.data.ieId && this.data.ieId == varsarray) {
2877                                 SE.folders.focusNode = this;
2878                     return false;
2879                         }
2880                 }
2881         }, null, [id, mbox]);
2882         return SE.folders.focusNode;
2883     },
2884
2885     unhighliteAll : function() {
2886         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2887     },
2888
2889     /**
2890      * Displays a short form
2891      */
2892     folderAdd : function() {
2893         SE.contextMenus.frameFoldersContextMenu.hide();
2894
2895         var node = SE.clickedFolderNode;
2896
2897         if(node != null && node.data) {
2898             SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2899                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2900                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2901         } else {
2902             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2903         }
2904     },
2905
2906     folderAddRegisterEnter : function() {
2907         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2908                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2909                                                                                                                         this.buttons[1].handler);
2910
2911                 this.enterKeyListener.enable();
2912     },
2913
2914     folderRemoveRegisterEnter : function() {
2915         this.enterKeyListener.disable();
2916     },
2917
2918     folderAddXmlCall : function(name) {
2919         if (trim(name) == "") {
2920                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2921                 return false;
2922         }
2923         name = escape(name);
2924         var post = '';
2925         var type = 'sugar';
2926
2927         var parentNode = SE.clickedFolderNode;
2928
2929         this.contextMenuFocus = parentNode;
2930
2931         if(parentNode.data.ieId) {
2932             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2933                 type = 'imap';
2934             }
2935         }
2936         if(type == 'imap') {
2937                 // make an IMAP folder
2938             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2939             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2940         } else if(type == 'sugar') {
2941             // make a Sugar folder
2942             if(SE.folders.isUniqueFolderName(name)) {
2943                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2944                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2945             } else {
2946                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2947                 SE.folders.folderAdd();
2948                 return;
2949             }
2950         } else {
2951             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2952         }
2953
2954         // hide add-folder diaglogue
2955         SE.e2overlay.hide();
2956     },
2957
2958     /**
2959      * Removes either an IMAP folder or a Sugar Folder
2960      */
2961     folderDelete : function() {
2962         SE.contextMenus.frameFoldersContextMenu.hide();
2963
2964         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2965             var post = '';
2966             var parentNode = SE.clickedFolderNode;
2967
2968             if(parentNode != null && parentNode.data) {
2969                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2970                     SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2971                     return;
2972                 }
2973
2974                 AjaxObject.target = 'frameFlex';
2975
2976                 if(parentNode.data.ieId != 'folder') {
2977                     // delete an IMAP folder
2978                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2979                 } else {
2980                     // delete a sugar folder
2981                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2982                 }
2983                 SUGAR.showMessageBox("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2984                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2985             } else {
2986                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2987             }
2988         }
2989     },
2990
2991     /**
2992      * Rename folder form
2993      */
2994      //EXT111
2995     folderRename : function() {
2996         SE.contextMenus.frameFoldersContextMenu.hide();
2997         var node = SE.clickedFolderNode;
2998
2999         if(node != null) {
3000             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
3001                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
3002                 return;
3003             }
3004
3005                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
3006                     app_strings.LBL_EMAIL_SETTINGS_NAME,
3007                     'prompt',
3008                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3009         } else {
3010             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3011         }
3012     },
3013
3014     /**
3015      * fills an Object with key-value pairs of available folders
3016      */
3017     getAvailableFoldersObject : function() {
3018         var ret = new Object();
3019         var tree = SE.tree.root;
3020
3021         if(tree.children) {
3022             for(var i=0; i<tree.children.length; i++) {
3023                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3024             }
3025         } else {
3026             ret['none'] = app_strings.LBL_NONE;
3027         }
3028
3029         return ret;
3030     },
3031
3032     /**
3033      * Fills in key-value pairs for dependent dropdowns
3034      * @param object ret Associative array
3035      * @param object node TreeView node in focus
3036      * @param string currentPath Built up path thus far
3037      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3038      */
3039     getFolderFromChild : function(ret, node, currentPath, spacer) {
3040         if(node.data != null && node.depth > 0) {
3041             /* handle visual separtors differentiating b/t mailserver and local */
3042             if(node.data.ieId && node.data.ieId == 'folder') {
3043                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3044             }
3045
3046             if(!ret.spacer0) {
3047                 ret['spacer0'] = spacer;
3048             } else if(ret.spacer0 != spacer) {
3049                 ret['spacer1'] = spacer
3050             }
3051
3052             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3053             var depthMarker = currentPath;
3054             var retIndex = SE.folders._createFolderId(node);
3055             ret[retIndex] = depthMarker + theLabel;
3056         }
3057
3058         if(node.children != null) {
3059             if(theLabel) {
3060                 currentPath += theLabel + "/";
3061             }
3062
3063             for(var i=0; i<node.children.length; i++) {
3064                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3065             }
3066         }
3067
3068         return ret;
3069     },
3070
3071     /**
3072      * Wrapper to refresh folders tree
3073      */
3074     getFolders : function() {
3075         SE.accounts.rebuildFolderList();
3076     },
3077
3078     /**
3079      * handles events around folder-rename input field changes
3080      * @param object YUI event object
3081      */
3082     handleEnter : function(e) {
3083         switch(e.browserEvent.type) {
3084             case 'click':
3085                 e.preventDefault(); // click in text field
3086             break;
3087
3088             case 'blur':
3089                 SE.folders.submitFolderRename(e);
3090             break;
3091
3092             case 'keypress':
3093                 var kc = e.browserEvent.keyCode;
3094                 switch(kc) {
3095                     case 13: // enter
3096                         e.preventDefault();
3097                         SE.folders.submitFolderRename(e);
3098                     break;
3099
3100                     case 27: // esc
3101                         e.preventDefault(e);
3102                         SE.folders.cancelFolderRename(e);
3103                     break;
3104                 }
3105             break;
3106         }
3107     },
3108     /**
3109     * Called when a node is clicked on in the folder tree
3110     * @param node, The node clicked on
3111     * @param e, The click event
3112     */
3113     handleClick : function(o) {
3114         var node = o.node;
3115         //If the click was on a sugar folder
3116         if (node.data.ieId == "folder") {
3117             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3118         }
3119         else {
3120             SE.listView.populateListFrame(node, node.data.ieId, false);
3121         }
3122        //eval(node.data.click);
3123        //debugger;
3124     },
3125
3126     /**
3127     * Called when a node is right-clicked on in the folder tree
3128     */
3129     handleRightClick : function(e) {
3130         YAHOO.util.Event.preventDefault(e);
3131                 //Get the Tree Node
3132                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3133                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3134
3135                 //If the click was on a sugar folder
3136         SE.clickedFolderNode = node;
3137         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3138                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3139                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3140                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3141                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3142                 menu.getItem(3).cfg.setProperty("disabled", false);
3143                 menu.getItem(4).cfg.setProperty("disabled", false);
3144                 menu.getItem(5).cfg.setProperty("disabled", false);
3145                 menu.getItem(6).cfg.setProperty("disabled", true);
3146                 //Group folder
3147                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3148                         menu.getItem(0).cfg.setProperty("disabled", true);
3149                         menu.getItem(1).cfg.setProperty("disabled", true);
3150                         menu.getItem(2).cfg.setProperty("disabled", true);
3151                         menu.getItem(3).cfg.setProperty("disabled", true);
3152                         menu.getItem(4).cfg.setProperty("disabled", true);
3153                 }
3154         if (node.data.protocol != null) {
3155                 menu.getItem(6).cfg.setProperty("disabled", false);
3156         }
3157                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3158                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3159                         //Sent or Draft folders
3160                         menu.getItem(3).cfg.setProperty("disabled", true);
3161                         menu.getItem(4).cfg.setProperty("disabled", true);
3162                         menu.getItem(5).cfg.setProperty("disabled", true);
3163                 }
3164
3165                 //For group with auto inbound, disable everything.
3166                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3167                 {
3168                     menu.getItem(0).cfg.setProperty("disabled", true);
3169                 menu.getItem(1).cfg.setProperty("disabled", true);
3170                 menu.getItem(2).cfg.setProperty("disabled", true);
3171                 menu.getItem(3).cfg.setProperty("disabled", true);
3172                 menu.getItem(4).cfg.setProperty("disabled", true);
3173                 menu.getItem(5).cfg.setProperty("disabled", true);
3174                 menu.getItem(6).cfg.setProperty("disabled", true);
3175                 }
3176
3177                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3178                 menu.show();
3179     },
3180
3181     /**
3182     * Called when a row is dropped on a node
3183     */
3184     handleDrop : function(rows, targetFolder) {
3185         var rowData = rows[0].getData();
3186         if (rowData.mbox != targetFolder.data.mbox) {
3187             var srcIeId = rowData.ieId;
3188             var srcFolder = rowData.mbox;
3189             var destIeId = targetFolder.data.ieId;
3190             var destFolder = targetFolder.data.mbox;
3191             var uids = [];
3192             for(var i=0; i<rows.length; i++) {
3193                 uids[i] = rows[i].getData().uid;
3194             }
3195             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3196         }
3197     },
3198
3199     /**
3200     * Called when something is dragged over a Folder Node
3201     */
3202     dragOver : function(dragObject) {
3203        return true;
3204     },
3205
3206     /**
3207      * Determines if a folder name is unique to the folder tree
3208      * @param string name
3209      */
3210     isUniqueFolderName : function(name) {
3211         uniqueFolder = true;
3212         var root = SE.tree.getRoot();
3213         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3214             if (this.attributes && this.attributes.ieId == "folder") {
3215                 if (this.attributes.text == name) {
3216                     uniqueFolder = false;
3217                     return false;
3218                 }
3219             }
3220         }, null, [name]);
3221         return uniqueFolder;
3222     },
3223
3224     /**
3225      * Makes async call to rename folder in focus
3226      * @param object e Event Object
3227      */
3228     submitFolderRename : function(newName) {
3229         if (trim(newName) == "") {
3230                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3231                 return false;
3232         }
3233                 newName = escape(newName);
3234         var node = SE.clickedFolderNode;
3235         var origName = node.data.text
3236         //Ignore no change
3237         if (newName == origName) {
3238             return true;
3239         }
3240         if(SE.folders.isUniqueFolderName(newName)) {
3241             SUGAR.showMessageBox(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3242             if (node.data.ieId == "folder") {
3243                 //Sugar Folder
3244                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3245             }
3246             else {
3247                 //IMAP folder or POP mailbox
3248                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3249                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3250                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3251             }
3252             return true;
3253         } else {
3254             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3255             return false;
3256         }
3257     },
3258
3259     moveFolder : function(folderId, parentFolderId) {
3260         if (folderId != parentFolderId)
3261         {
3262                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3263                     + folderId + "&newParentId=" + parentFolderId);
3264         }
3265     },
3266
3267     /**
3268      * makes async call to do a full synchronization of all accounts
3269      */
3270     synchronizeAccounts : function() {
3271         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3272             SUGAR.showMessageBoxModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3273             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3274         }
3275     },
3276
3277     /**
3278      * Updates user's folder subscriptsion (Sugar only)
3279      * @param object SELECT DOM object in focus
3280      * @param string type of Folder selection
3281      */
3282     updateSubscriptions : function() {
3283         SUGAR.showMessageBox(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3284
3285         var active = "";
3286
3287         select = document.getElementById('userFolders');
3288
3289         for(i=0; i<select.options.length; i++) {
3290             var opt = select.options[i];
3291              if(opt.selected && opt.value != "") {
3292                  if(active != "") {
3293                      active += "::";
3294                  }
3295                  active += opt.value;
3296              }
3297         }
3298
3299         //Add the group folder ids.
3300         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3301         for(i=0; i<group_folders.length; i++)
3302         {
3303             active += ("::" + group_folders[i]);
3304         }
3305
3306         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3307     },
3308     /**
3309      * Updates user's group folder subscriptsion (Sugar only)
3310      * @param ieID The group folder to add to the tree view
3311      */
3312     retrieveGroupFolderSubscriptions : function() {
3313
3314         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3315         var activeGroupFolders = "";
3316         var activeGroupIds = [];
3317         for(i=0;i<a_rs.length;i++)
3318         {
3319                 var t_record = a_rs[i];
3320                 var is_active = t_record.getData('is_active');
3321                 var isGroupFolder = t_record.getData('has_groupfolder');
3322                 var ieID = t_record.getData('id');
3323                 if( isGroupFolder )
3324                 {
3325                     if(is_active)
3326                       activeGroupIds.push(ieID);
3327                 }
3328         }
3329
3330         return activeGroupIds;
3331     }
3332
3333 };
3334
3335 SE.folders.checkEmail2 = function() {
3336     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3337 }
3338 ////    END FOLDERS OBJECT
3339 ///////////////////////////////////////////////////////////////////////////////
3340
3341
3342 ///////////////////////////////////////////////////////////////////////////////
3343 ////    SE.keys
3344 /**
3345  * Keypress Event capture and processing
3346  */
3347 SE.keys = {
3348     overall : function(e) {
3349         switch(e.charCode) {
3350             case 119: // "w"
3351                 if(e.ctrlKey || e.altKey) {
3352                     var focusRegion = SE.innerLayout.regions.center;
3353                     if(focusRegion.activePanel.closable == true) {
3354                         focusRegion.remove(focusRegion.activePanel);
3355                     }
3356                 }
3357             break;
3358         }
3359     }
3360 };
3361 ////    END SE.keys
3362 ///////////////////////////////////////////////////////////////////////////////
3363
3364
3365 ///////////////////////////////////////////////////////////////////////////////
3366 ////    SE.listView
3367 /**
3368  * ListView object methods and attributes
3369  */
3370 SE.listView = {
3371     currentRowId : -1,
3372
3373     /**
3374      * Fills the ListView pane with detected messages.
3375      */
3376     populateListFrame : function(node, ieId, forceRefresh) {
3377         SE.innerLayout.selectTab(0);
3378                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3379
3380         Dom.get('_blank').innerHTML = "";
3381         SE.grid.params['emailUIAction'] = 'getMessageList';
3382         SE.grid.params['mbox'] = node.data.mbox;
3383         SE.grid.params['ieId'] = ieId;
3384         forcePreview = true; // loads the preview pane with first item in grid
3385         SE.listView.refreshGrid();
3386     },
3387
3388     /**
3389      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3390      */
3391     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3392         SE.innerLayout.selectTab(0);
3393         Dom.get('_blank').innerHTML = "";
3394         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3395         SE.grid.params['ieId'] = node.data.id;
3396         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3397         SE.listView.refreshGrid();
3398     },
3399
3400     /**Mac
3401      * Sets sort order as user preference
3402      * @param
3403      */
3404     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3405         ieId = ieIdPassed;
3406         ieName = ieNamePassed;
3407         focusFolder = focusFolderPassed;
3408
3409         SE.util.clearHiddenFieldValues('emailUIForm');
3410         var previousSort = document.getElementById('sortBy').value;
3411
3412         document.getElementById('sortBy').value = sortBy;
3413         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3414         document.getElementById('focusFolder').value = focusFolder;
3415         document.getElementById('ieId').value = ieId;
3416
3417         if(sortBy == previousSort) {
3418             document.getElementById('reverse').value = '1';
3419         }
3420
3421         var formObject = document.getElementById('emailUIForm');
3422         YAHOO.util.Connect.setForm(formObject);
3423
3424         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3425     },
3426
3427
3428     /**
3429      * Enables click/arrow select of grid items which then populate the preview pane.
3430      */
3431     selectFirstRow : function() {
3432         SE.grid.selModel.selectFirstRow();
3433     },
3434
3435     selectLastRow : function() {
3436         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3437     },
3438
3439     setEmailListStyles : function() {
3440         SE.listView.boldUnreadRows();
3441         return;
3442         var ds = SE.grid.getStore();
3443         if (SE.grid.getSelections().length == 0) {
3444             document.getElementById('_blank').innerHTML = '';
3445         }
3446
3447         var acctMbox = '';
3448         if(typeof(ds.baseParams.mbox) != 'undefined') {
3449             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3450             var cm = SE.grid.getColumnModel();
3451             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3452                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3453                 //SE.grid.render();
3454             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3455                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3456                 //SE.grid.render();
3457             }
3458         }
3459         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3460         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3461
3462         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3463             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3464             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3465             if (node) node.data.unseen = unread;
3466         }
3467         SE.accounts.renderTree();
3468
3469
3470         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3471         if(forcePreview && ds.totalCount > 0) {
3472             SE.detailView.getEmailPreview();
3473             forcePreview = false;
3474         }
3475     },
3476
3477     /**
3478      * Removes a row if found via its UID
3479      */
3480     removeRowByUid : function(uid) {
3481         uid = new String(uid);
3482         uids = uid.split(',');
3483         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3484
3485         for(j=0; j<uids.length; j++) {
3486             var theUid = uids[j];
3487             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3488                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3489                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3490                 }
3491             } // for
3492         }
3493     },
3494
3495     displaySelectedEmails : function(rows) {
3496         var dm = SE.grid.getDataModel();
3497         var uids = '';
3498
3499         for(i=0; i<rows.length; i++) {
3500             var rowIndex = rows[i].rowIndex;
3501             var metadata = dm.data[rowIndex];
3502
3503             if(uids != "") {
3504                 uids += ",";
3505             }
3506             uids += metadata[5];
3507
3508             // unbold unseen email
3509             this.unboldRow(rowIndex);
3510         }
3511
3512         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3513     },
3514
3515     /**
3516      * exception handler for data load failures
3517      */
3518     loadException : function(dataModel, ex, response) {
3519         //debugger;
3520     },
3521
3522     /**
3523      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3524      * @param string sourceIeId Email's source I-E id
3525      * @param string sourceFolder Email's current folder
3526      * @param destinationIeId Destination I-E id
3527      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3528      *
3529      * @param array emailUids Array of email's UIDs
3530      */
3531     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3532         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3533             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3534         } else {
3535             SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3536             // remove rows from visibility
3537             for(row in selectedRows) {
3538                 //SE.grid.getStore().remove(row);
3539             }
3540
3541             var baseUrl =    '&sourceIeId=' + sourceIeId +
3542                             '&sourceFolder=' + sourceFolder +
3543                             '&destinationIeId=' + destinationIeId +
3544                             '&destinationFolder=' + destinationFolder;
3545             var uids = '';
3546
3547             for(i=0; i<emailUids.length; i++) {
3548                 if(uids != '') {
3549                     uids += app_strings.LBL_EMAIL_DELIMITER;
3550                 }
3551                 uids += emailUids[i];
3552             }
3553             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3554                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3555             } else {
3556                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3557             }
3558         }
3559     },
3560
3561     /**
3562      * Unbolds text in the grid view to denote read status
3563      */
3564     markRead : function(index, record) {
3565         // unbold unseen email
3566         var row = SE.grid.getRecord(record);
3567         row.getData().seen = 1;
3568         SE.grid.getTrEl(record).style.fontWeight = "normal";
3569     },
3570
3571     /**
3572      * grid row output, bolding unread emails
3573      */
3574     boldUnreadRows : function() {
3575         // bold unread emails
3576         var trEl = SE.grid.getFirstTrEl();
3577         while(trEl != null) {
3578                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3579                         trEl.style.fontWeight = "bold";
3580                 else
3581                         trEl.style.fontWeight = "";
3582                 trEl = SE.grid.getNextTrEl(trEl);
3583         }
3584     },
3585
3586     /**
3587      * Show preview for an email if 1 and only 1 is selected
3588      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3589      */
3590     handleRowSelect : function(e) {
3591         if(e.selectedRows.length == 1) {
3592             SE.detailView.getEmailPreview();
3593         }
3594     },
3595
3596     handleDrop : function(e, dd, targetId, e2) {
3597         switch(targetId) {
3598             case 'htmleditordiv':
3599                 var rows = SE.grid.getSelectedRows();
3600                 if(rows.length > 0) {
3601                     SE.listView.displaySelectedEmails(rows);
3602                 }
3603             break;
3604
3605             default:
3606                 var targetElId = new String(targetId);
3607                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3608                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3609                 var dm = SE.grid.getDataModel();
3610                 var emailUids = new Array();
3611                 var destinationIeId = targetNode.data.ieId;
3612                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3613
3614
3615                 var rows = SE.grid.getSelectedRows();
3616                 // iterate through dragged rows
3617                 for(i=0; i<rows.length; i++) {
3618                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3619                     var rowIndex = rows[i].rowIndex;
3620                     var dataModelRow = dm.data[rowIndex];
3621                     var sourceIeId = dataModelRow[7];
3622                     var sourceFolder = dataModelRow[6];
3623                     emailUids[i] = dataModelRow[5];
3624                 }
3625
3626                 // event wrapped call - need FQ
3627                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3628                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3629             break;
3630         }
3631     },
3632
3633     /**
3634      * Hack-around to get double-click and single clicks to work on the grid
3635      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3636      */
3637     handleClick : function(o) {
3638         SUGAR.email2.grid.clearTextSelection();
3639
3640         var el = SUGAR.email2.grid.getSelectedRows();
3641
3642         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3643         if ( el.length == 1)
3644         {
3645            var rowId = el[0];
3646            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3647            SUGAR.email2.listView.currentRowIndex = rowId;
3648            clearTimeout(SUGAR.email2.detailView.previewTimer);
3649            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3650         }
3651     },
3652
3653     /**
3654      * Custom handler for double-click/enter
3655      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3656      */
3657     getEmail : function(e) {
3658         var rows = SE.grid.getSelectedRows();
3659         var row = SE.grid.getRecord(rows[0]).getData();
3660
3661         clearTimeout(SE.detailView.previewTimer);
3662         document.getElementById("_blank").innerHTML = "";
3663
3664         if(row.type != "draft") {
3665             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3666         } else {
3667             // circumventing yui-ext tab generation, let callback handler build new view
3668             SE.util.clearHiddenFieldValues('emailUIForm');
3669             //function(uid, mbox, ieId, setRead, destination) {
3670             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3671             document.getElementById('uid').value = row.uid; // uid;
3672             document.getElementById('mbox').value = row.mbox; // mbox;
3673             document.getElementById('ieId').value = row.ieId; // ieId;
3674
3675             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3676             AjaxObject.target = '_blank';
3677             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3678         }
3679     },
3680
3681     /**
3682      * Retrieves a row if found via its UID
3683      * @param string
3684      * @return int
3685      */
3686     getRowIndexByUid : function(uid) {
3687         uid = new String(uid);
3688         uids = uid.split(',');
3689
3690         for(j=0; j<uids.length; j++) {
3691             var theUid = uids[j];
3692
3693             for(i=0; i<SE.grid.getStore().data.length; i++) {
3694                 if(SE.grid.getStore().data[i].id == theUid) {
3695                     return i;
3696                 }
3697             }
3698         }
3699     },
3700
3701     /**
3702      * Returns the UID's of the seleted rows
3703      *
3704      */
3705      getUidsFromSelection : function() {
3706          var rows = SE.grid.getSelectedRows();
3707          var uids = [];
3708          /* iterate through available rows JIC a row is deleted - use first available */
3709          for(var i=0; i<rows.length; i++) {
3710                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3711          }
3712          return uids;
3713      },
3714
3715     refreshGrid : function() {
3716         SE.grid.getDataSource().sendRequest(
3717             SUGAR.util.paramsToUrl(SE.grid.params),
3718                 SE.grid.onDataReturnInitializeTable,
3719                 SE.grid
3720         );
3721     }
3722
3723 };
3724 ////    END SE.listView
3725 ///////////////////////////////////////////////////////////////////////////////
3726
3727 ///////////////////////////////////////////////////////////////////////////////
3728 ////    SEARCH
3729 SE.search = {
3730     /**
3731      * sends search criteria
3732      * @param reference element search field
3733      */
3734     search : function(el) {
3735         var searchCriteria = new String(el.value);
3736
3737         if(searchCriteria == '') {
3738             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3739             return false;
3740         }
3741
3742         var safeCriteria = escape(searchCriteria);
3743
3744         var accountListSearch = document.getElementById('accountListSearch');
3745
3746         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3747         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3748         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3749         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3750         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3751
3752     },
3753
3754     /**
3755      * sends advanced search criteria
3756      */
3757     searchAdvanced : function() {
3758         var formObject = document.getElementById('advancedSearchForm');
3759         var search = false;
3760
3761         //Set assigned user id to blank if name is not present.
3762         if (formObject.elements['assigned_user_name'].value == "")
3763             formObject.elements['assigned_user_id'].value = "";
3764
3765         for(i=0; i<formObject.elements.length; i++) {
3766             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3767                 search = true;
3768             }
3769             if(formObject.elements[i].type == 'text') {
3770                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3771             }
3772             if(formObject.elements[i].type == 'hidden') {
3773                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3774             }
3775              if(formObject.elements[i].type == 'select-one') {
3776                 var el = formObject.elements[i];
3777                 var v = el.options[el.selectedIndex].value;
3778
3779                 if(v != "")
3780                     SE.grid.params[el.name] = v;
3781                 else
3782                 {
3783                     //Clear previous search results if necessary
3784                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3785                         delete SE.grid.params[el.name]
3786                 }
3787              }
3788         }
3789
3790         if (search)
3791         {
3792             if(! this.validateSearchFormInput() )
3793                 return;
3794
3795                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3796                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3797                 var accountListSearch = document.getElementById('accountListSearch');
3798                 SE.listView.refreshGrid();
3799         } else {
3800             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3801         }
3802     },
3803
3804     /**
3805     *  Validates the search form inputs to ensure all parameters are valid
3806     *  @return bool
3807     */
3808     validateSearchFormInput: function()
3809     {
3810         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3811         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3812         var dateCheck = check_form('advancedSearchForm');
3813
3814         //If the parent type is selected ensure the user selected a parent_id.
3815         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3816             return true;
3817         else
3818             return false;
3819     },
3820     /**
3821     *   Toggles the advanced options, either hidding or showing the selection.
3822     */
3823     toggleAdvancedOptions: function()
3824     {
3825         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3826
3827         for(var i=0;i<el.length;i++)
3828         {
3829             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3830                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3831             else
3832                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3833         }
3834     },
3835     /**
3836      * clears adv search form fields
3837      */
3838     searchClearAdvanced : function() {
3839         var form = document.getElementById('advancedSearchForm');
3840
3841         for(i=0; i<form.elements.length; i++) {
3842             if(form.elements[i].type != 'button') {
3843                 form.elements[i].value = '';
3844             }
3845         }
3846     }
3847 };
3848 ////    END SE.search
3849 //////////////////////////////////////////////////////////////////////////////
3850
3851
3852 //////////////////////////////////////////////////////////////////////////////
3853 ////    SE.settings
3854 SE.settings = {
3855     /******************************************************************************
3856      * USER SIGNATURES calls stolen from Users module
3857      *****************************************************************************/
3858     createSignature : function(record, the_user_id) {
3859         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3860         if(record != "") {
3861             URL += "&record="+record;
3862         }
3863         if(the_user_id != "") {
3864             URL += "&the_user_id="+the_user_id;
3865         }
3866         var windowName = 'email_signature';
3867         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3868
3869         var win = window.open(URL, windowName, windowFeatures);
3870         if(win && win.focus) {
3871             // put the focus on the popup if the browser supports the focus() method
3872             win.focus();
3873         }
3874     },
3875
3876     deleteSignature : function() {
3877         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3878             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3879                 var singature_id = document.getElementById('signature_id').value;
3880                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3881         } // if
3882     },
3883
3884     saveOptionsGeneral :  function(displayMessage) {
3885         var formObject = document.getElementById('formEmailSettingsGeneral');
3886         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3887                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3888                 return false;
3889         } // if
3890         YAHOO.util.Connect.setForm(formObject);
3891         SE.composeLayout.emailTemplates = null;
3892
3893         AjaxObject.target = 'frameFlex';
3894         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3895
3896         if(displayMessage)
3897             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3898
3899         SE.settings.settingsDialog.hide();
3900     },
3901
3902     /**
3903      * Shows settings container screen
3904      */
3905     showSettings : function() {
3906         if(!SE.settings.settingsDialog) {
3907                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3908                 modal:true,
3909                 visible:false,
3910                 fixedcenter:true,
3911                 draggable: false,
3912                 width:"800px",
3913                                 constraintoviewport: true
3914             });
3915                         dlg.showEvent.subscribe( function (){
3916                                 var el = this.element;
3917                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3918                 if (this.header && el && viewH - 50 < el.clientHeight) {
3919                     var body = this.header.nextElementSibling;
3920                                         body.style.overflow = "auto";
3921                     body.style.height = (viewH - 50) + "px";
3922                 }
3923             }, dlg);
3924                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3925                 dlg.setBody('<div id="settingsTabDiv"/>');
3926                 dlg.beforeRenderEvent.subscribe(function() {
3927                         var dd = new YAHOO.util.DDProxy(dlg.element);
3928                         dd.setHandleElId(dlg.header);
3929                         dd.on('endDragEvent', function() {
3930                                 dlg.show();
3931                         });
3932                 }, dlg, true);
3933                 dlg.render();
3934
3935                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3936                         var tabContent = Dom.get("tab_general");
3937                 tp.addTab(new YAHOO.widget.Tab({
3938                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3939                                 scroll : true,
3940                                 content :  tabContent.innerHTML,
3941                                 id : "generalSettings",
3942                                 active : true
3943                         }));
3944                 tabContent.parentNode.removeChild(tabContent);
3945                 tabContent = Dom.get("tab_accounts");
3946                 var accountTab = new YAHOO.widget.Tab({
3947                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3948                                 scroll : true,
3949                                 content : tabContent.innerHTML,
3950                                 id : "accountSettings"
3951                         });
3952                 tp.addTab(accountTab);
3953                 tabContent.parentNode.removeChild(tabContent);
3954
3955                         tp.appendTo(dlg.body);
3956         }
3957
3958         SE.settings.settingsDialog.show();
3959         SE.folders.lazyLoadSettings();
3960         SE.accounts.lazyLoad();
3961     },
3962
3963
3964     lazyLoadRules : function() {
3965         if(false/*!SE.settings.rules*/) {
3966             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3967         }
3968
3969     }
3970 };
3971 ////    END SE.settings
3972 ///////////////////////////////////////////////////////////////////////////////
3973 })();
3974
3975 /******************************************************************************
3976  * UTILITIES
3977  *****************************************************************************/
3978 function removeHiddenNodes(nodes, grid) {
3979     var el;
3980         for(var i = nodes.length - 1; i > -1; i--) {
3981         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3982         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3983                 nodes.splice(i,1);
3984        }
3985     }
3986 }
3987
3988 function strpad(val) {
3989     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3990 };
3991
3992 function refreshTodos() {
3993     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3994     AjaxObject.target = 'todo';
3995     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3996 };
3997
3998 /******************************************************************************
3999  * MUST STAY IN GLOBAL NAMESPACE
4000  *****************************************************************************/
4001 function refresh_signature_list(signature_id, signature_name) {
4002     var field=document.getElementById('signature_id');
4003     var bfound=0;
4004     for (var i=0; i < field.options.length; i++) {
4005             if (field.options[i].value == signature_id) {
4006                 if (field.options[i].selected==false) {
4007                     field.options[i].selected=true;
4008                 }
4009                 bfound=1;
4010             }
4011     }
4012     //add item to selection list.
4013     if (bfound == 0) {
4014         var newElement=document.createElement('option');
4015         newElement.text=signature_name;
4016         newElement.value=signature_id;
4017         field.options.add(newElement);
4018         newElement.selected=true;
4019     }
4020
4021     //enable the edit button.
4022     var field1=document.getElementById('edit_sig');
4023     field1.style.visibility="inherit";
4024     var deleteButt = document.getElementById('delete_sig');
4025     deleteButt.style.visibility="inherit";
4026 };
4027
4028 function setDefaultSigId(id) {
4029     var checkbox = document.getElementById("signature_default");
4030     var default_sig = document.getElementById("signatureDefault");
4031
4032     if(checkbox.checked) {
4033         default_sig.value = id;
4034     } else {
4035         default_sig.value = "";
4036     }
4037 };
4038
4039 function setSigEditButtonVisibility() {
4040     var field = document.getElementById('signature_id');
4041     var editButt = document.getElementById('edit_sig');
4042     var deleteButt = document.getElementById('delete_sig');
4043     if(field.value != '') {
4044         editButt.style.visibility = "inherit";
4045         deleteButt.style.visibility = "inherit";
4046     } else {
4047         editButt.style.visibility = "hidden";
4048         deleteButt.style.visibility = "hidden";
4049     }
4050 }// End of File modules/Emails/javascript/EmailUI.js
4051                                 
4052 /*********************************************************************************
4053  * SugarCRM Community Edition is a customer relationship management program developed by
4054  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4055  * 
4056  * This program is free software; you can redistribute it and/or modify it under
4057  * the terms of the GNU Affero General Public License version 3 as published by the
4058  * Free Software Foundation with the addition of the following permission added
4059  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4060  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4061  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4062  * 
4063  * This program is distributed in the hope that it will be useful, but WITHOUT
4064  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4065  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4066  * details.
4067  * 
4068  * You should have received a copy of the GNU Affero General Public License along with
4069  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4070  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4071  * 02110-1301 USA.
4072  * 
4073  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4074  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4075  * 
4076  * The interactive user interfaces in modified source and object code versions
4077  * of this program must display Appropriate Legal Notices, as required under
4078  * Section 5 of the GNU Affero General Public License version 3.
4079  * 
4080  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4081  * these Appropriate Legal Notices must retain the display of the "Powered by
4082  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4083  * technical reasons, the Appropriate Legal Notices must display the words
4084  * "Powered by SugarCRM".
4085  ********************************************************************************/
4086
4087  (function() {
4088         var sw = YAHOO.SUGAR,
4089                 Event = YAHOO.util.Event,
4090                 Connect = YAHOO.util.Connect,
4091             Dom = YAHOO.util.Dom
4092             SE = SUGAR.email2;
4093
4094 ///////////////////////////////////////////////////////////////////////////////
4095 ////    ADDRESS BOOK
4096 SE.addressBook = {
4097     _contactCache : new Array(), // cache of contacts
4098     _dd : new Array(), // filtered list, same format as _contactCache
4099     _ddLists : new Array(), // list of Lists
4100     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4101     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4102     clickBubble : true, // hack to get around onclick event bubbling
4103         relatedBeanId : '',
4104         relatedBeanType : '',
4105         idx : 0,
4106
4107     itemSpacing : 'white-space:nowrap; padding:2px;',
4108     reGUID : SE.reGUID,
4109
4110
4111
4112     /**
4113     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4114     */
4115     initFixForDatatableSort: function () {
4116         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4117         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4118             var oColumn = this._oColumnSet.getColumn(column);
4119
4120             if(!oColumn) {
4121                 // Validate TD element
4122                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4123                 if(elCell) {
4124                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4125                 }
4126                 // Validate TH element
4127                 else {
4128                     elCell = this.getThEl(column);
4129                     if(elCell) {
4130                         // Find by TH el ID
4131                         var allColumns = this._oColumnSet.flat;
4132                         for(var i=0, len=allColumns.length; i<len; i++) {
4133                             if(allColumns[i].getThEl().id === elCell.id) {
4134                                 oColumn = allColumns[i];
4135                             }
4136                         }
4137                     }
4138                 }
4139             }
4140
4141             return oColumn;
4142         };
4143     },
4144
4145     cancelEdit : function() {
4146         if(this.editContactDialog)
4147             this.editContactDialog.hide();
4148         if(this.editMailingListDialog)
4149             this.editMailingListDialog.hide();
4150     },
4151
4152     /**
4153      * Clears filter form
4154      */
4155     clear : function() {
4156         var t = document.getElementById('contactsFilter');
4157         t.value = '';
4158         this.filter(t);
4159     },
4160
4161     /**
4162      * handle context-menu Compose-to call
4163      * @param string type 'contacts' or 'lists'
4164      */
4165     composeTo : function(type, waited) {
4166         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4167         if (activePanel.substring(0, 10) != "composeTab") {
4168             SE.composeLayout.c0_composeNewEmail();
4169             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4170                 SE.contextMenus.contactsContextMenu.hide();
4171             return;
4172         }
4173         var idx = activePanel.substring(10);
4174         var rows = [ ];
4175         var id = '';
4176         // determine if we have a selection to work with
4177         if(type == 'contacts') {
4178             var ids = SE.contactView.getSelectedRows();
4179             for (var i in ids) {
4180                 rows[i] = SE.contactView.getRecord(ids[i]);
4181             }
4182             removeHiddenNodes(rows, SE.contactView);
4183         }
4184                 else { return; }
4185
4186         if(rows.length > 0) {
4187             SE.composeLayout.handleDrop(
4188                 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4189                 null, rows, 'addressTO' + idx );
4190         } else {
4191             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4192         }
4193     },
4194
4195     editContact : function() {
4196         SE.contextMenus.contactsContextMenu.hide();
4197         var element = SE.contactView.getSelectedNodes()[0];
4198         var elementId = "";
4199         if (element.className.indexOf('address-contact') > -1) {
4200             elementId = element.id;
4201         } else if (element.className.indexOf('address-exp-contact') > -1) {
4202             elementId = element.id.substring(2);
4203         }
4204     },
4205
4206
4207     /**
4208      * Filters contact entries based on user input
4209      */
4210     filter : function(inputEl) {
4211         var ret = new Object();
4212         var re = new RegExp(inputEl.value, "gi");
4213
4214         for(var i in this._contactCache) {
4215             if(this._contactCache[i].name.match(re)) {
4216                 ret[i] = this._contactCache[i];
4217             }
4218         }
4219
4220         this.buildContactList(ret);
4221     },
4222
4223     fullForm : function(id, module) {
4224         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4225     },
4226
4227     /**
4228      * returns a formatted email address from the addressBook cache
4229      */
4230     getFormattedAddress : function(id) {
4231         var o = this._contactCache[id];
4232         var primaryEmail = '';
4233
4234         for(var i=0; i<o.email.length; i++) {
4235             var currentEmail = o.email[i].email_address;
4236
4237             if(o.email[i].primary_address == 1) {
4238                 primaryEmail = o.email[i].email_address;
4239             }
4240         }
4241
4242         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4243         var name = new String(o.name);
4244         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4245         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4246
4247         return ret;
4248     },
4249
4250     /**
4251      * Sets up async call to query for matching contacts, users, etc.
4252      */
4253     searchContacts : function() {
4254         var fn = document.getElementById('input_searchField').value;
4255         var pe = document.getElementById('input_searchPerson').value;
4256
4257         var rb = document.getElementById('hasRelatedBean').checked;
4258         if (rb) {
4259                         var idx = this.idx;
4260                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4261                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4262                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4263                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4264         } else {
4265                 this.addressBookDataModel.params['related_bean_id'] = '';
4266         }
4267
4268         this.addressBookDataModel.params['search_field'] = fn;
4269         this.addressBookDataModel.params['person'] = pe;
4270         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4271         this.grid._oDataSource = this.addressBookDataModel;
4272         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4273     },
4274
4275     /**
4276      * Clear Search Crieteria For Addressbook
4277      */
4278     clearAddressBookSearch : function() {
4279         document.getElementById('input_searchField').value = "";
4280         document.getElementById('input_searchPerson').selectedIndex = 0;
4281     },
4282
4283     /**
4284      * Opens modal select window to add contacts to addressbook
4285      */
4286     selectContactsDialogue : function(destId) {
4287         if(!this.contactsDialogue) {
4288                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4289                 modal:true,
4290                 visible:false,
4291                 draggable: false,
4292                 constraintoviewport: true,
4293                 width   : 980,
4294                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4295                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4296             });
4297                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4298
4299                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4300                 dlg.setBody(body.innerHTML);
4301                 dlg.renderEvent.subscribe(function() {
4302                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4303                 if (iev && !SUGAR.isIE) {
4304                         this.body.style.width = "950px";
4305                 }
4306             }, dlg);
4307
4308
4309                 dlg.beforeRenderEvent.subscribe(function() {
4310                         var dd = new YAHOO.util.DDProxy(dlg.element);
4311                         dd.setHandleElId(dlg.header);
4312                         dd.on('endDragEvent', function() {
4313                                 dlg.show();
4314                         });
4315                 }, dlg, true);
4316                 dlg.render();
4317
4318                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4319
4320                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4321                 tp.addTab(new YAHOO.widget.Tab({
4322                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4323                                 scroll : true,
4324                                 content : tabContent.innerHTML,
4325                                 id : "addressSearchTab",
4326                                 active : true
4327                         }));
4328
4329                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4330                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4331                         if (e.keyCode == 13) {
4332                                 YAHOO.util.Event.stopEvent(e);
4333                                 SUGAR.email2.addressBook.searchContacts();
4334                         }
4335                 });
4336
4337                 this.contactsDialogue.render();
4338                 dlg.center();
4339         }
4340         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4341         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4342             var idx = 0;
4343         else
4344         {
4345             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4346             var idx = activePanel.substring(10);
4347         }
4348         SE.addressBook.idx = idx;
4349
4350                 var relatedBeanId;
4351         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4352                 document.getElementById('relatedBeanColumn').style.display = '';
4353                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4354                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4355                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4356                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4357                         SE.addressBook.relatedBeanType = relatedBeanType;
4358             } else {
4359                 document.getElementById('relatedBeanColumn').style.display = 'none';
4360                 document.getElementById('hasRelatedBean').checked = false;
4361             }
4362
4363             if (!SE.addressBook.grid)
4364             {
4365                 if (hasRelatedBeanId) {
4366                         document.getElementById('hasRelatedBean').checked = true;
4367                 }
4368                 AddressSearchGridInit();
4369                         SE.addressBook.relatedBeanId = relatedBeanId;
4370             }
4371             else
4372             {
4373                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4374                 {
4375                         SE.addressBook.relatedBeanId = relatedBeanId;
4376                         document.getElementById('hasRelatedBean').checked = true;
4377                 }
4378                 if (document.getElementById('hasRelatedBean').checked == true)
4379                 {
4380                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4381                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4382                 } else {
4383                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4384                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4385                 }
4386                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4387                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4388                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4389             }
4390
4391             //Remove any lingering rows in the result set table if the module was closed.
4392             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4393             //Repopulate
4394             SE.addressBook.populateResulstTableEmailAddresses();
4395
4396         this.contactsDialogue.show();
4397     },
4398     /**
4399     *  Clear all email addresses from result table.
4400     *
4401     */
4402     clearAllEmailAddressFieldsFromResultTable: function () {
4403         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4404         //Unhighlight any rows currently selected if the emails were cleared.
4405         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4406         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4407     },
4408     /**
4409     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4410     *  results table.  This function is called when the address book is displayed.
4411     */
4412     populateResulstTableEmailAddresses: function () {
4413
4414         var idx = SE.addressBook.idx;
4415         var emailFields = ['to','cc','bcc'];
4416
4417         for(var k=0;k<emailFields.length;k++)
4418         {
4419             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4420             var allEmails = document.getElementById(elKey).value;
4421             if(allEmails == '')
4422                 continue;
4423
4424             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4425
4426                 for (var i=0; i<formatedEmails.length; i++)
4427                 {
4428                     var t_name = formatedEmails[i].name;
4429                     var t_emailAddr = formatedEmails[i].email_address;
4430                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4431                     if(t_name == '')
4432                         t_name = displayEmail = t_emailAddr;
4433
4434                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4435                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4436                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4437                 }
4438         }
4439     },
4440
4441     /**
4442     * Checks all entries in the result table against a particular email address, returning true
4443     * if the email address is found, false otherwise.
4444     */
4445     doesEmailAdddressExistInResultTable: function(emailAddress)
4446     {
4447         if(trim(emailAddress) == '')
4448             return false;
4449
4450         var emailAddressFound = false;
4451         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4452         for (var i=0; i < contacts.length; i++)
4453         {
4454             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4455             //If we are adding to cc or bcc fields, make them visible.
4456             if(data.email_address == emailAddress)
4457             {
4458                 emailAddressFound = true;
4459                 break;
4460             }
4461         }
4462
4463         return emailAddressFound;
4464     },
4465     /**
4466     *  Takes all email addresses that the users wishes to add from the address book and populates the To
4467     *  fields on the compose tab.
4468     */
4469     populateEmailAddressFieldsFromResultTable: function()
4470     {
4471         //Clear the fields first, all email addresses are stored in the address book
4472         var idx = SE.addressBook.idx;
4473         var emailFields = ['to','cc','bcc'];
4474         for(var k=0;k<emailFields.length;k++)
4475         {
4476             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4477             document.getElementById(elKey).value = "";
4478         }
4479
4480         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4481         for (var i=0; i < contacts.length; i++)
4482         {
4483             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4484
4485             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4486             //If we are adding to cc or bcc fields, make them visible.
4487             if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4488                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4489             //Construct the target id
4490             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4491
4492             var target = document.getElementById(target_id);
4493             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4494         }
4495
4496         //Delete all rows from the result set table
4497         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4498
4499         //Hide the dialogue
4500         SE.addressBook.contactsDialogue.hide()
4501     },
4502     /**
4503     *  Insert contacts into the result table.
4504     */
4505     insertContactToResultTable : function(event,address_type) {
4506
4507         var contactsDialogue = SE.addressBook.contactsDialogue;
4508         var contacts = SE.addressBook.grid.getSelectedRows();
4509
4510         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4511         for (var i = 0; i < rows.length; i++)
4512         {
4513                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4514                         {
4515                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4516                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4517                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4518                 rows[i].setData("selected",true);
4519                         }
4520         }
4521         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4522         for (var i = 0; i < checkBoxes.length; i++) {
4523             checkBoxes[i].checked = false;
4524         }
4525     },
4526     /**
4527     *
4528     */
4529     insertContactRowToResultTable : function(rowId, addressType) {
4530         var data = SE.addressBook.grid.getRecord(rowId).getData();
4531         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4532                 return;
4533         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4534         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4535         if(addressType == null)
4536             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4537         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});
4538     },
4539     /**
4540     * Remove a row from the gridsResult table.
4541     */
4542     removeRowFromGridResults : function(rowId,emailAddress)
4543     {
4544         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4545         for (var i=0; i < contacts.length; i++)
4546         {
4547             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4548             var data = rec.getData();
4549             if(data.email_address == emailAddress)
4550             {
4551                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4552                 break;
4553             }
4554         }
4555
4556        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4557     },
4558     /**
4559     * Translates between the addressType To|Cc|Bcc labels/keys.
4560     */
4561     translateAddresType: function(addressType,fromKey)
4562     {
4563         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4564         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4565         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4566         var mappingObject = {};
4567
4568         if(fromKey)
4569             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4570         else
4571         {
4572             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4573             mappingObject[displayCc] = 'cc';
4574             mappingObject[displayBcc] = 'bcc';
4575         }
4576
4577         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4578
4579     },
4580     /**
4581     *
4582     */
4583     toggleSearchRowIcon : function(rowId,show)
4584     {
4585         if(show)
4586         {
4587             var idToShow = rowId + '_add_img';
4588             var idToHide = rowId + '_rm_img';
4589         }
4590         else
4591         {
4592             var idToShow = rowId + '_rm_img';
4593             var idToHide = rowId + '_add_img';
4594         }
4595
4596
4597         Dom.addClass(idToHide, "yui-hidden");
4598         Dom.removeClass(idToShow, "yui-hidden");
4599     },
4600     /**
4601     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4602     */
4603     doesGridResultsEntryExist: function(emailAddrs)
4604     {
4605
4606         var contactExists = false;
4607         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4608         for (var i=0; i < contacts.length; i++)
4609         {
4610             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4611             if(data.email_address == emailAddrs)
4612             {
4613                 contactExists = true;
4614                 break;
4615             }
4616         }
4617         return contactExists;
4618     },
4619
4620     /**
4621      * adds an email address to a string, but first checks if it exists
4622      * @param string concat The string we are appending email addresses to
4623      * @param string addr Email address to add
4624      * @return string
4625      */
4626     smartAddEmailAddressToComposeField : function(concat, addr) {
4627         var re = new RegExp(addr);
4628
4629         if(!concat.match(re)) {
4630             if(concat != "") {
4631                 concat += "; " + addr;
4632             } else {
4633                 concat = addr;
4634             }
4635         }
4636
4637         return concat;
4638     }
4639 };
4640 ////    END ADDRESS BOOK
4641 ///////////////////////////////////////////////////////////////////////////////
4642
4643
4644
4645 ///////////////////////////////////////////////////////////////////////////////
4646 ////    AUTOCOMPLETE
4647 /**
4648  * Auto-complete object
4649  */
4650 SE.autoComplete = {
4651     config : {
4652         delimChar : [";", ","],
4653         useShadow :    false,
4654         useIFrame : false,
4655         typeAhead : true,
4656         prehighlightClassName : "yui-ac-prehighlight",
4657         queryDelay : 0
4658     },
4659     instances : new Array(),
4660
4661     /**
4662      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4663      * @param object Contact from AddressBook
4664      * @return string
4665      */
4666     getPrimaryAddress : function(contact) {
4667         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4668
4669         for(var eIndex in contact.email) {
4670             address = contact.email[eIndex].email_address;
4671             if(contact.email[eIndex].primary_address == 1) {
4672                 return contact.email[eIndex].email_address;
4673             }
4674         }
4675         return address;
4676     },
4677
4678
4679     /**
4680      * initializes autocomplete widgets for a given compose view
4681      * @param int idx
4682      */
4683     init : function(idx) {
4684         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4685             "queryMatchContains" : false,
4686             "queryMatchSubset" : true
4687         });
4688
4689         this.instances[idx] = {
4690             to : null,
4691             cc : null,
4692             bcc : null
4693         };
4694
4695
4696         // instantiate the autoComplete widgets
4697         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4698         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4699         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4700
4701         // enable hiding of interfering textareas
4702         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4703         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4704         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4705
4706         // enable reshowing of hidden textareas
4707         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4708         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4709         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4710
4711         // enable refreshes of contact lists
4712         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4713         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4714         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4715     },
4716
4717     refreshDataSource : function(sType, aArgs) {
4718         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4719         var idx;
4720         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4721
4722         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4723             idx = textBoxId.substr(9);
4724         } else {
4725             idx = textBoxId.substr(10);
4726         }
4727
4728         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4729         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4730         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4731     },
4732
4733     /**
4734      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4735      */
4736     returnDataSource : function(contacts) {
4737         var ret = new Array();
4738         for(var id in contacts) {
4739             if (contacts[id].name) {
4740                     var primary = this.getPrimaryAddress(contacts[id]);
4741
4742                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4743                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4744
4745                     for(var emailIndex in contacts[id].email) {
4746                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4747                     }
4748             }
4749         }
4750
4751         return ret;
4752     },
4753
4754     /**
4755      * Hides address textareas to prevent autocomplete dropdown from being obscured
4756      */
4757     toggleTextareaHide : function(sType, aArgs) {
4758         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4759         var type = "";
4760         var idx = -1;
4761
4762         if(textBoxId.indexOf("addressTO") > -1) {
4763             type = "to";
4764         } else if(textBoxId.indexOf("addressCC") > -1) {
4765             type = "cc";
4766         }
4767         idx = textBoxId.substr(9);
4768
4769         // follow through if not BCC
4770         if(type != "") {
4771             var cc = document.getElementById("addressCC" + idx);
4772             var bcc = document.getElementById("addressBCC" + idx);
4773
4774             switch(type) {
4775                 case "to":
4776                     cc.style.visibility = 'hidden';
4777                 case "cc":
4778                     bcc.style.visibility = 'hidden';
4779                 break;
4780             }
4781         }
4782     },
4783
4784     /**
4785      * Redisplays the textareas after an address is commited
4786      */
4787     toggleTextareaShow : function(sType, aArgs) {
4788         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4789         var type = "";
4790         var idx = -1;
4791
4792         if(textBoxId.indexOf("addressTO") > -1) {
4793             type = "to";
4794         } else if(textBoxId.indexOf("addressCC") > -1) {
4795             type = "cc";
4796         }
4797         idx = textBoxId.substr(9);
4798
4799         // follow through if not BCC
4800         if(type != "") {
4801             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4802             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4803         }
4804     }
4805 };
4806
4807 ////    END AUTOCOMPLETE
4808 ///////////////////////////////////////////////////////////////////////////////
4809
4810 ///////////////////////////////////////////////////////////////////////////////
4811 ////    COMPOSE & SEND
4812 /**
4813  * expands the options sidebar
4814  */
4815 SE.composeLayout = {
4816     currentInstanceId : 0,
4817     ccHidden : true,
4818     bccHidden : true,
4819     outboundAccountErrors : null,
4820     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4821
4822     showAddressDetails : function(e) {
4823         var linkElement = document.getElementById("More"+e.id);
4824         var spanElement = document.getElementById("Detail"+e.id);
4825         var emailAddressList = e.value;
4826         if(e.value.length > 96)
4827         {
4828                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4829             var displayArray = [];
4830                 for (var i=0; i<resultArray.length; i++)
4831                 {
4832                     var t_name = resultArray[i].name;
4833                     var t_emailAddr = resultArray[i].email_address;
4834                     if(t_name == '')
4835                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4836                     else
4837                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');
4838                 }
4839
4840             var result = displayArray.join('<br/>');
4841                 // Display
4842             linkElement.style.display = "inline";
4843             linkElement.style.height="10px";
4844             linkElement.style.overflow="visible";
4845             spanElement.innerHTML = result;
4846         }
4847         else
4848                 linkElement.style.display = "none";
4849
4850         },
4851
4852    /**
4853     *  Given a string of email address, return an array containing the name portion (if available)
4854     *  and email portion.
4855     */
4856     _getEmailArrayFromString : function (emailAddressList){
4857
4858         var reg = /@.*?;/g;
4859         while ((results = reg.exec(emailAddressList)) != null)
4860         {
4861             orignial = results[0];
4862             parsedResult = results[0].replace(';', ':::::');
4863             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4864         }
4865
4866         reg = /@.*?,/g;
4867         while ((results = reg.exec(emailAddressList)) != null)
4868         {
4869             orignial = results[0];
4870             parsedResult = results[0].replace(',', ':::::');
4871             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4872         }
4873         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4874         var emailArr = emailAddressList.split(":::::");
4875         var resultsArray = [];
4876         var newArr = [];
4877         for (var i=0; i<emailArr.length; i++)
4878         {
4879             var rposition = emailArr[i].indexOf('<');
4880             var lposition = emailArr[i].indexOf('>');
4881
4882             if(trim(emailArr[i]) != '')
4883             {
4884                 if(rposition != -1 && lposition != -1)
4885                 {
4886                     var t_name = emailArr[i].substr(0, rposition-1);
4887                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4888                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4889                 }
4890                 else
4891                 {
4892                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4893                 }
4894             }
4895         }
4896         return resultsArray;
4897     },
4898     ///////////////////////////////////////////////////////////////////////////
4899     ////    COMPOSE FLOW
4900     /**
4901      * Prepare bucket DIV and yui-ext tab panels
4902      */
4903     _0_yui : function() {
4904         var idx = this.currentInstanceId;
4905
4906         var composeTab = new YAHOO.SUGAR.ClosableTab({
4907                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4908                                 scroll : true,
4909                                 content : "<div id='htmleditordiv" + idx + "'/>",
4910                                 id : "composeTab" + idx,
4911                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4912                                 active : true
4913         }, SE.innerLayout);
4914         SE.innerLayout.addTab(composeTab);
4915
4916         // get template engine with template
4917         if (!SE.composeLayout.composeTemplate) {
4918                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4919         }
4920
4921         // create Tab inner layout
4922         var composePanel =  this.getComposeLayout();
4923         composePanel.getUnitByPosition("right").collapse();
4924         composePanel.autoSize();
4925
4926     },
4927         /**
4928      * Generate the quick compose layout
4929          * @method getQuickComposeLayout
4930          * @param {Pannel} parentPanel Parent pannel
4931          * @param {Object} o Options
4932          * @return {} none
4933          **/
4934     getQuickComposeLayout : function (parentPanel,o) {
4935          var idx = SE.composeLayout.currentInstanceId;
4936
4937          //Before rendering the parent pannel we need to initalize the grid layout
4938          parentPanel.beforeRenderEvent.subscribe(function() {
4939
4940                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4941                         SE.composeLayout._createComposeLayout(idx);
4942                         SE.composeLayout[idx].set('height', 350);
4943                         SE.composeLayout[idx].render();
4944            });
4945         });
4946
4947          //Wait until the Compose Layout has rendered, then add the
4948          //options tab and perform the tiny initialization.
4949          parentPanel.renderEvent.subscribe(function() {
4950
4951                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4952                 SE.composeLayout._initComposeOptionTabs(idx);
4953                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4954                 //Initialize tinyMCE
4955             SE.composeLayout._1_tiny(false);
4956
4957                 //Init templates and address book
4958                 SE.composeLayout._2_final();
4959
4960             SE.composeLayout.quickCreateComposePackage(o);
4961
4962                 });
4963          });
4964
4965             //Check if we have the div override for the shortcut bar
4966         if(typeof o.menu_id != 'undefined') {
4967                    parentPanel.render(o.menu_id);
4968             } else {
4969                    parentPanel.render(document.body);
4970             }
4971
4972         return SE.composeLayout[idx];
4973     },
4974     /**
4975      * Fill in all fields into the quick compose layout.
4976          * @method quickCreateComposePackage
4977          * @param {Object} o Options
4978          * @return {} none
4979          **/
4980     quickCreateComposePackage: function(o)
4981     {
4982         //If we have a compose package fill in defaults.
4983         if (typeof(o.composePackage) != 'undefined')
4984         {
4985             composePackage = o.composePackage; //Set the compose data object
4986             //Hijack this method called by composePackage as it's not need for quick creates.
4987             SE.composeLayout.c0_composeNewEmail = function(){};
4988             SE.composeLayout.composePackage(); //Fill in defaults.
4989         }
4990     },
4991     getComposeLayout : function() {
4992         var idx = SE.composeLayout.currentInstanceId;
4993
4994         this._createComposeLayout(idx);
4995         SE.composeLayout[idx].render();
4996         this._initComposeOptionTabs(idx);
4997
4998         return SE.composeLayout[idx];
4999         },
5000
5001         /**
5002         *       Create the layout manager for the compose window.
5003         */
5004         _createComposeLayout : function(idx)
5005         {
5006                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5007                 parent: SE.complexLayout,
5008                 border:true,
5009             hideOnLayout: true,
5010             height: 400,
5011                         units: [{
5012                                         position: "center",
5013                         animate: false,
5014                         scroll: false,
5015                         split:true,
5016                         body:
5017                                 SE.composeLayout.composeTemplate.exec({
5018                                 'app_strings':app_strings,
5019                                 'mod_strings':mod_strings,
5020                                 'linkbeans_options' : linkBeans,
5021                                 'idx' : SE.composeLayout.currentInstanceId
5022                                 })
5023                     },{
5024                         position: "right",
5025                                     scroll:true,
5026                                     collapse: true,
5027                                     collapsed: true,
5028                                     resize: true,
5029                                     border:true,
5030                                     animate: false,
5031                                     width:'230',
5032                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5033                                     titlebar: true,
5034                                     split: true,
5035                                     header: app_strings.LBL_EMAIL_OPTIONS
5036                     }]
5037                 });
5038         },
5039
5040         /**
5041         *  Create compose tab which will populate the 'right' container in the compose window.
5042         */
5043         _initComposeOptionTabs : function(idx)
5044         {
5045                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5046                 var tab = new YAHOO.widget.Tab({
5047                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5048                                 scroll : true,
5049                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5050                                 id : "divAttachments" + idx,
5051                                 active : true
5052                         });
5053
5054                 tab.layout = SE.composeLayout[idx];
5055
5056            tab.on("activeChange", function(o){
5057                         if (o.newValue) {
5058                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5059                         }
5060                 });
5061
5062                 cTabs.addTab(tab);
5063
5064                 tab = new YAHOO.widget.Tab({
5065                                 label: app_strings.LBL_EMAIL_OPTIONS,
5066                                 scroll : true,
5067                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5068                                 id : "divOptions" + idx,
5069                                 active : false
5070                         });
5071
5072                 tab.layout = SE.composeLayout[idx];
5073                 tab.on("activeChange", function(o){
5074                         if (o.newValue) {
5075                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5076                         }
5077                 });
5078                 cTabs.addTab(tab);
5079
5080                 SE.composeLayout[idx].autoSize = function() {
5081                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5082                         this.set("height", pEl.clientHeight-30);
5083                         this.render();
5084                 }
5085
5086                 SE.composeLayout[idx].rightTabs = cTabs;
5087     },
5088     isParentTypeValid : function(idx) {
5089                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5090                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5091                 if (trim(parentTypeValue) == ""){
5092                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5093                         return false;
5094                 } // if
5095                 return true;
5096     },
5097
5098     isParentTypeAndNameValid : function(idx) {
5099                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5100                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5101                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5102                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5103                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5104                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5105                         return false;
5106                 } // if
5107                 return true;
5108     },
5109
5110     callopenpopupForEmail2 : function(idx,options) {
5111
5112         var formName = 'emailCompose' + idx;
5113
5114         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5115             formName = options.form_name;
5116
5117                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5118                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5119                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5120                         return;
5121                 } // if
5122                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5123                 {
5124                         call_back_function:"SE.composeLayout.popupAddEmail",
5125                         form_name:formName,
5126                         field_to_name_array:{
5127                                 id:'data_parent_id' + idx,
5128                                 name:'data_parent_name' + idx,
5129                                 email1:'email1'}
5130                 });
5131         },
5132
5133         popupAddEmail : function(o)
5134         {
5135                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5136                 var data = o.name_to_value_array;
5137                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5138                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5139         {
5140                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5141                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5142         }
5143                 set_return(o);
5144         },
5145     /**
5146      * Prepare TinyMCE
5147      */
5148     _1_tiny : function(isReplyForward) {
5149         var idx = SE.composeLayout.currentInstanceId;
5150         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5151         SE.tinyInstances[elId] = { };
5152         SE.tinyInstances[elId].ready = false;
5153
5154         if (!SUGAR.util.isTouchScreen()) {
5155             var t = tinyMCE.getInstanceById(elId);
5156         }
5157         if(typeof(t) == 'undefined')  {
5158             if (!SUGAR.util.isTouchScreen()) {
5159                 tinyMCE.execCommand('mceAddControl', false, elId);
5160             }
5161             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5162                 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5163                 }, this);
5164         }
5165     },
5166
5167     resizeEditorSetSignature : function(idx,setSignature)
5168     {
5169         var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5170
5171         if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5172             setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+setSignature+"');",500);
5173                     return;
5174                 }
5175
5176         SE.composeLayout.resizeEditor(idx);
5177         if(setSignature) {
5178             setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5179         }
5180
5181     },
5182
5183     resizeEditor : function(idx)
5184     {
5185         var cof = Dom.get('composeOverFrame' + idx);
5186         var head = Dom.get('composeHeaderTable' + idx);
5187         var targetHeight = cof.clientHeight - head.clientHeight;
5188         var instance = SE.util.getTiny('htmleditor' + idx);
5189
5190         try {
5191         var parentEl = Dom.get(instance.editorId + '_parent');
5192         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5193         var contentEl  = instance.contentAreaContainer;
5194         var iFrame = contentEl.firstChild;
5195         var tinMceToolbarOffset = 18;
5196         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5197
5198         } catch(e) {
5199             setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5200         }
5201     },
5202
5203     /**
5204      * Initializes d&d, auto-complete, email templates
5205      */
5206     _2_final : function() {
5207         var idx = SE.composeLayout.currentInstanceId;
5208
5209         if(this.emailTemplates) {
5210             this.setComposeOptions(idx);
5211         } else {
5212             //populate email template cache
5213             AjaxObject.target = '';
5214             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5215         }
5216
5217         // handle drop targets for addressBook
5218        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5219        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5220        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5221        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5222
5223         // auto-complete setup
5224         SE.autoComplete.init(idx);
5225
5226         // set focus on to:
5227         document.getElementById("addressTO" + idx).focus();
5228     },
5229
5230         /**
5231      * hide tinyMCE tool bar if send email as plaintext is checked
5232      */
5233     renderTinyMCEToolBar : function (idx, hide) {
5234         if (hide) {
5235                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5236         } else {
5237                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5238         }
5239     },
5240
5241     c1_composeEmail : function(isReplyForward, retry) {
5242         if (!retry) {
5243             this._0_yui();
5244         }
5245         if  (!SUGAR.util.isTouchScreen() && (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined')){
5246             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5247         } else {
5248                 this._1_tiny(isReplyForward);
5249                 this._2_final();
5250
5251                 if(isReplyForward) {
5252                     this.replyForwardEmailStage2();
5253                 }
5254         }
5255     },
5256
5257     /**
5258      * takes draft info and prepopulates
5259      */
5260     c0_composeDraft : function() {
5261         this.getNewInstanceId();
5262         inCompose = true;
5263         document.getElementById('_blank').innerHTML = '';
5264         var idx = SE.composeLayout.currentInstanceId;
5265                 SE.composeLayout.draftObject = new Object();
5266                 SE.composeLayout.draftObject.id = idx;
5267                 SE.composeLayout.draftObject.isDraft = true;
5268         SE.composeLayout.currentInstanceId = idx;
5269         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5270         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5271         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5272
5273         SE.composeLayout._0_yui();
5274         SE.composeLayout._1_tiny(true);
5275
5276         // final touches
5277         SE.composeLayout._2_final();
5278
5279         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5280         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5281     },
5282
5283     /**
5284      * Strip & Prep editor hidden fields
5285      */
5286     c0_composeNewEmail : function() {
5287         this.getNewInstanceId();
5288         this.c1_composeEmail(false);
5289     },
5290
5291     /**
5292      * Sends async request to get the compose view.
5293      * Requests come from "reply" or "forwards"
5294      */
5295     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5296         SE.composeLayout.replyForwardObj = new Object();
5297         SE.composeLayout.replyForwardObj.ieId = ieId;
5298         SE.composeLayout.replyForwardObj.uid = uid;
5299         SE.composeLayout.replyForwardObj.mbox = mbox;
5300         SE.composeLayout.replyForwardObj.type = type;
5301
5302         if(mbox == 'sugar::Emails') {
5303             SE.composeLayout.replyForwardObj.sugarEmail = true;
5304         }
5305
5306         SE.composeLayout.getNewInstanceId();
5307         SE.composeLayout.c1_composeEmail(true);
5308     },
5309     ////    END COMPOSE FLOW
5310     ///////////////////////////////////////////////////////////////////////////
5311
5312     /**
5313      * Called when a contact, email, or mailinglist is dropped
5314      * into one of the compose fields.
5315      */
5316     handleDrop : function (source, event, data, target) {
5317         var nodes;
5318         if (!target) {
5319             target = event.getTarget();
5320             if (data.single) {
5321                 data.nodes = [data.nodes];
5322             }
5323             nodes = data.nodes;
5324         } else {
5325             target = document.getElementById(target);
5326             nodes = data;
5327         }
5328
5329         if (target.id.indexOf('address') > -1) {
5330             // dropped onto email to/cc/bcc field
5331             for(var i in nodes) {
5332                 var node = nodes[i].getData();
5333                 var email = "";
5334                 if (node[1].indexOf('contact') > -1) {
5335                     email = SE.addressBook.getFormattedAddress(node[0]);
5336                 } else if (node[1].indexOf('address-email') > -1){
5337                     email = node[3].replace(/&nbsp;/gi, '');
5338                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5339                     var tr = source.getTrEl(nodes[i]);
5340                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5341                         tr = source.getPreviousTrEl(tr);
5342                     }
5343                     var CID = source.getRecord(tr).getData()[0];
5344                     var o = SE.addressBook._contactCache[CID];
5345                     var name = new String(o.name);
5346                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5347                     email = finalName + email;
5348                 }
5349                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5350             }
5351         }
5352     },
5353
5354
5355     /*/////////////////////////////////////////////////////////////////////////////
5356     ///    EMAIL TEMPLATE CODE
5357      */
5358     applyEmailTemplate : function (idx, id) {
5359
5360         //bug #20680
5361         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5362                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5363                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5364
5365                 //bug #6224
5366                 var to_addr = document.getElementById('addressTO'+idx);
5367                 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1)
5368                 {
5369                         box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5370                         box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5371                 }
5372
5373                 // id is selected index of email template drop-down
5374                 if(id == '' || id == "0") {
5375                         YAHOO.SUGAR.MessageBox.show({
5376                    title:box_title,
5377                    msg: box_none_msg,
5378                    type: 'confirm',
5379                    fn: function(btn){
5380                                 if(btn=='no'){return;};
5381                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5382                    modal:true,
5383                    scope:this
5384                });
5385                return;
5386                 }
5387
5388                 YAHOO.SUGAR.MessageBox.show({
5389            title:box_title,
5390            msg: box_msg,
5391            type: 'confirm',
5392            fn: function(btn){
5393                         if(btn=='no'){return;};
5394                         SUGAR.email2.composeLayout.processResult(idx, id);},
5395            modal:true,
5396            scope:this
5397        });
5398     },
5399
5400     processNoneResult : function(idx, id) {
5401         var tiny = SE.util.getTiny('htmleditor' + idx);
5402         var tinyHTML = tiny.getContent();
5403         var openTag = '<div><span><span>';
5404         var htmllow = tinyHTML.toLowerCase();
5405         var start = htmllow.indexOf(openTag);
5406                 if (start > -1) {
5407                 tinyHTML = tinyHTML.substr(start);
5408             tiny.setContent(tinyHTML);
5409                 } else {
5410             tiny.setContent('');
5411                 }
5412     },
5413
5414         processResult : function(idx , id){
5415                 var post_data = {"module":"EmailTemplates","record":id};
5416                 var global_rpcClient =  new SugarRPCClient();
5417
5418                 result = global_rpcClient.call_method('retrieve', post_data, true);
5419                 if(!result['record']) return;
5420                 json_objects['email_template_object'] = result['record'];
5421                 this.appendEmailTemplateJSON();
5422
5423         // get attachments if any
5424         AjaxObject.target = '';
5425         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5426     },
5427
5428     appendEmailTemplateJSON : function() {
5429         var idx = SE.composeLayout.currentInstanceId; // post increment
5430
5431         // query based on template, contact_id0,related_to
5432         //jchi 09/10/2008 refix #7743
5433         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5434             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5435         }
5436
5437         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,'"');
5438
5439         // cn: bug 14361 - text-only templates don't fill compose screen
5440         if(text == '') {
5441             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/>");
5442         }
5443
5444         var tiny = SE.util.getTiny('htmleditor' + idx);
5445         var tinyHTML = tiny.getContent();
5446         var openTag = '<div><span><span>';
5447         var closeTag = '</span></span></div>';
5448         var htmllow = tinyHTML.toLowerCase();
5449         var start = htmllow.indexOf(openTag);
5450                 if (start > -1) {
5451                 var htmlPart2 = tinyHTML.substr(start);
5452                 tinyHTML = text + htmlPart2;
5453                 tiny.setContent(tinyHTML);
5454                 } else {
5455                 tiny.setContent(text);
5456                 }
5457     },
5458
5459     /**
5460      * Writes out the signature in the email editor
5461      */
5462     setSignature : function(idx) {
5463         if (!tinyMCE)
5464             return false;
5465         var hide = document.getElementById('setEditor' + idx).checked;
5466         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5467         //wait for signatures to load before trying to set them
5468         if (!SE.composeLayout.signatures) {
5469             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5470                         return;
5471         }
5472
5473         if(idx) {
5474             var sel = document.getElementById('signatures' + idx);
5475         } else {
5476             var sel = document.getElementById('signature_id');
5477             idx = SE.tinyInstances.currentHtmleditor;
5478         }
5479
5480         //Ensure that the tinyMCE html has been rendered.
5481         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5482             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5483                     return;
5484                 }
5485
5486         var signature = '';
5487
5488         try {
5489             signature = sel.options[sel.selectedIndex].value;
5490         } catch(e) {
5491
5492         }
5493
5494         var openTag = '<div><span><span>';
5495         var closeTag = '</span></span></div>';
5496         var t = tinyMCE.getInstanceById('htmleditor' + idx);
5497         //IE 6 Hack
5498         if(typeof(t) != 'undefined')
5499         {
5500             t.contentDocument = t.contentWindow.document;
5501             var html = t.getContent();
5502         }
5503         else
5504         {
5505             var html = '';
5506         }
5507
5508         var htmllow = html.toLowerCase();
5509         var start = htmllow.indexOf(openTag);
5510         var end = htmllow.indexOf(closeTag) + closeTag.length;
5511
5512         // selected "none" - remove signature from email
5513         if(signature == '') {
5514             if (start > -1) {
5515                 var htmlPart1 = html.substr(0, start);
5516                 var htmlPart2 = html.substr(end, html.length);
5517
5518                 html = htmlPart1 + htmlPart2;
5519                 t.setContent(html);
5520             }
5521             SE.signatures.lastAttemptedLoad = '';
5522             return false;
5523         }
5524
5525         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5526             SE.signatures.lastAttemptedLoad = '';
5527
5528         SE.signatures.lastAttemptedLoad = signature;
5529
5530         if(typeof(SE.signatures[signature]) == 'undefined') {
5531             //lazy load
5532             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5533             SE.signatures.targetInstance = (idx) ? idx : "";
5534             AjaxObject.target = '';
5535             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5536         } else {
5537             var newSignature = this.prepareSignature(SE.signatures[signature]);
5538
5539             // clear out old signature
5540             if(SE.signatures.lastAttemptedLoad && start > -1) {
5541                 var htmlPart1 = html.substr(0, start);
5542                 var htmlPart2 = html.substr(end, html.length);
5543
5544                 html = htmlPart1 + htmlPart2;
5545             }
5546
5547             // [pre|ap]pend
5548                         start = html.indexOf('<div><hr></div>');
5549             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5550                                 var htmlPart1 = html.substr(0, start);
5551                                 var htmlPart2 = html.substr(start, html.length);
5552                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5553             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5554                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5555             } else {
5556                 var newHtml = html + openTag + newSignature + closeTag;
5557             }
5558             //tinyMCE.setContent(newHtml);
5559             t.setContent(newHtml);
5560         }
5561     },
5562
5563     prepareSignature : function(str) {
5564         var signature = new String(str);
5565
5566         signature = signature.replace(/&lt;/gi, '<');
5567         signature = signature.replace(/&gt;/gi, '>');
5568
5569         return signature;
5570     },
5571
5572
5573     showAttachmentPanel : function(idx) {
5574         var east = SE.composeLayout[idx].getUnitByPosition("right");
5575         var tabs = SE.composeLayout[idx].rightTabs;
5576         east.expand();
5577         tabs.set("activeTab", tabs.getTab(0));
5578     },
5579
5580     /**
5581      * expands sidebar and displays options panel
5582      */
5583     showOptionsPanel : function(idx) {
5584         var east = SE.composeLayout[idx].getUnitByPosition("right");
5585         var tabs = SE.composeLayout[idx].rightTabs;
5586         east.expand();
5587         tabs.set("activeTab", tabs.getTab(1));
5588     },
5589
5590     /**
5591      * Selects the Contacts tab
5592      */
5593     showContactsPanel : function() {
5594         SE.complexLayout.regions.west.showPanel("contactsTab");
5595     },
5596
5597     /**
5598      * Generates fields for Select Document
5599      */
5600     addDocumentField : function(idx) {
5601         var basket = document.getElementById('addedDocuments' + idx);
5602         if(basket) {
5603             var index = (basket.childNodes.length / 7) - 1;
5604             if(index < 0)
5605                 index = 0;
5606         } else {
5607             index = 0;
5608         }
5609
5610         var test = document.getElementById('documentId' + idx + index);
5611
5612         while(test != null) {
5613             index++;
5614             test = document.getElementById('documentId' + idx + index);
5615         }
5616
5617         var documentCup = document.createElement("div");
5618         documentCup.id = 'documentCup' + idx + index;
5619         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5620                 // document id field
5621                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5622                 // document name field
5623                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5624                 // select button
5625                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5626                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5627                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5628                 // remove button
5629                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5630                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5631                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5632                 "<br/>";
5633
5634         basket.appendChild(documentCup);
5635         //basket.innerHTML += out;
5636         return index;
5637     },
5638
5639     /**
5640      * Makes async call to save a draft of the email
5641      * @param int Instance index
5642      */
5643     saveDraft : function(tinyInstance) {
5644         this.sendEmail(tinyInstance, true);
5645     },
5646
5647     selectDocument : function(target) {
5648         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5649         windowName = 'selectDocument';
5650         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5651
5652         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5653         if(window.focus) {
5654             // put the focus on the popup if the browser supports the focus() method
5655             win.focus();
5656         }
5657     },
5658
5659     /**
5660      * Modal popup for file attachment dialogue
5661      */
5662     addFileField : function() {
5663         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5664             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5665                 modal:true,
5666                 visible:false,
5667                 fixedcenter:true,
5668                 constraintoviewport: true,
5669                 scroll: true,
5670                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5671                         fn:function(){SE.addFileDialog.hide();}
5672                 })
5673             });
5674             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5675             SE.addFileDialog.render();
5676            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5677         }
5678         Dom.removeClass("addFileDialog", "yui-hidden");
5679
5680         SE.addFileDialog.show();
5681     },
5682
5683     /**
5684      * Async upload of file to temp dir
5685      */
5686     uploadAttachment : function() {
5687         if(document.getElementById('email_attachment').value != "") {
5688             var formObject = document.getElementById('uploadAttachment');
5689             YAHOO.util.Connect.setForm(formObject, true, true);
5690             AjaxObject.target = '';
5691             AjaxObject.startRequest(callbackUploadAttachment, null);
5692         } else {
5693             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5694         }
5695     },
5696
5697     /**
5698      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5699      * @param string target in focus compose layout
5700      */
5701     setDocument : function(idx, target, documentId, documentName, docRevId) {
5702         // fields are named/id'd [fieldName][instanceId][index]
5703         var addedDocs = document.getElementById("addedDocuments" + idx);
5704         var docId = document.getElementById('documentId' + idx + target);
5705         var docName = document.getElementById('documentName' + idx + target);
5706         var docRevisionId = document.getElementById('document' + idx + target);
5707         docId.value = documentId;
5708         docName.value = documentName;
5709         docRevisionId.value = docRevId;
5710     },
5711
5712     /**
5713      * Removes the bucket div containing the document input fields
5714      */
5715     deleteDocumentField : function(documentCup) {
5716         var f0 = document.getElementById(documentCup);
5717         f0.parentNode.removeChild(f0);
5718     },
5719
5720     /**
5721      * Removes a Template Attachment field
5722      * @param int
5723      * @param int
5724      */
5725     deleteTemplateAttachmentField : function(idx, index) {
5726         // create not-in-array values for removal filtering
5727         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5728
5729         if(r != "") {
5730             r += "::";
5731         }
5732
5733         r += document.getElementById('templateAttachmentId' + idx + index).value;
5734         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5735
5736         var target = 'templateAttachmentCup' + idx + index;
5737         d =  document.getElementById(target);
5738         d.parentNode.removeChild(d);
5739     },
5740
5741     /**
5742      * Async removal of uploaded temp file
5743      * @param string index Should be a concatenation of idx and index
5744      * @param string
5745      */
5746     deleteUploadAttachment : function(index, file) {
5747         var d = document.getElementById('email_attachment_bucket' + index);
5748         d.parentNode.removeChild(d);
5749
5750         // make async call to delete cached file
5751         AjaxObject.target = '';
5752         AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5753     },
5754
5755     /**
5756      * Attaches files coming from Email Templates
5757      */
5758     addTemplateAttachmentField : function(idx) {
5759         // expose title
5760         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5761
5762         var basket = document.getElementById('addedTemplateAttachments' + idx);
5763
5764         if(basket) {
5765             var index = basket.childNodes.length;
5766             if(index < 0)
5767                 index = 0;
5768         } else {
5769             index = 0;
5770         }
5771
5772         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5773                                 // remove button
5774                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5775                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5776                                         idx + "\",\"" + index + "\");'/>" +
5777                                 // file icon
5778                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5779                                 // templateAttachment field
5780                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5781                                 // docId field
5782                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5783                                 // file name
5784                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
5785                                 "<br id='br" + index + "></br>" +
5786                                 "<br id='brdoc" + index + "></br>" +
5787                         "</div>";
5788                 basket.innerHTML = basket.innerHTML + out;
5789
5790         return index;
5791     },
5792
5793     /**
5794      * Sends one email via async call
5795      * @param int idx Editor instance ID
5796      * @param bool isDraft
5797      */
5798     sendEmail : function(idx, isDraft) {
5799
5800         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5801         var obAccountID = document.getElementById('addressFrom' + idx).value;
5802
5803         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5804         {
5805             SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5806             return false;
5807         }
5808
5809
5810         var form = document.getElementById('emailCompose' + idx);
5811         var composeOptionsFormName = "composeOptionsForm" + idx;
5812
5813
5814         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5815         if (t != null || typeof(t) != "undefined") {
5816             var html = t.getContent();
5817         } else {
5818             var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
5819         }
5820
5821             var subj = document.getElementById('emailSubject' + idx).value;
5822         var to = trim(document.getElementById('addressTO' + idx).value);
5823         var cc = trim(document.getElementById('addressCC' + idx).value);
5824         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5825         var email_id = document.getElementById('email_id' + idx).value;
5826         var composeType = document.getElementById('composeType').value;
5827         var parent_type = document.getElementById("parent_type").value;
5828         var parent_id = document.getElementById("parent_id").value;
5829
5830         var el_uid = document.getElementById("uid");
5831         var uid = (el_uid == null) ? '' : el_uid.value;
5832
5833         var el_ieId = document.getElementById("ieId");
5834         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5835
5836         var el_mbox = document.getElementById("mbox");
5837         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5838
5839         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5840                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5841                 return false;
5842         }
5843
5844         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5845                 return;
5846         } // if
5847                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5848                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5849         parent_id = parentIdValue;
5850         parent_type = parentTypeValue;
5851
5852         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5853         // baseline viability check
5854
5855         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5856             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5857             return false;
5858         } else if(subj == '' && !isDraft) {
5859             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5860                 return false;
5861             } else {
5862                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5863             }
5864         } else if(html == '' && !isDraft) {
5865             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5866                 return false;
5867             }
5868         }
5869
5870         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5871                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5872                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5873         SUGAR.showMessageBox(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5874         html = html.replace(/&lt;/ig, "sugarLessThan");
5875         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5876
5877         form.sendDescription.value = html;
5878         form.sendSubject.value = subj;
5879         form.sendTo.value = to;
5880         form.sendCc.value = cc;
5881         form.sendBcc.value = bcc;
5882         form.email_id.value = email_id;
5883         form.composeType.value = composeType;
5884         form.composeLayoutId.value = 'composeLayout' + idx;
5885         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5886         form.saveToSugar.value = 1;
5887         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5888         form.parent_type.value = parent_type;
5889         form.parent_id.value = parent_id;
5890         form.uid.value = uid;
5891         form.ieId.value = ieId;
5892         form.mbox.value = mbox;
5893
5894         // email attachments
5895         var addedFiles = document.getElementById('addedFiles' + idx);
5896         if(addedFiles) {
5897             for(i=0; i<addedFiles.childNodes.length; i++) {
5898                 var bucket = addedFiles.childNodes[i];
5899
5900                 for(j=0; j<bucket.childNodes.length; j++) {
5901                     var node = bucket.childNodes[j];
5902                     var nName = new String(node.name);
5903
5904                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5905                         if(form.attachments.value != '') {
5906                             form.attachments.value += "::";
5907                         }
5908                         form.attachments.value += node.value;
5909                     }
5910                 }
5911             }
5912         }
5913
5914         // sugar documents
5915         var addedDocs = document.getElementById('addedDocuments' + idx);
5916         if(addedDocs) {
5917             for(i=0; i<addedDocs.childNodes.length; i++) {
5918                 var cNode = addedDocs.childNodes[i];
5919                 for(j=0; j<cNode.childNodes.length; j++) {
5920                     var node = cNode.childNodes[j];
5921                     var nName = new String(node.name);
5922                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5923                         if(form.documents.value != '') {
5924                             form.documents.value += "::";
5925                         }
5926                         form.documents.value += node.value;
5927                     }
5928                 }
5929             }
5930         }
5931
5932         // template attachments
5933         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5934         if(addedTemplateAttachments) {
5935             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5936                 var cNode = addedTemplateAttachments.childNodes[i];
5937                 for(j=0; j<cNode.childNodes.length; j++) {
5938                     var node = cNode.childNodes[j];
5939                     var nName = new String(node.name);
5940                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5941                         if(form.templateAttachments.value != "") {
5942                             form.templateAttachments.value += "::";
5943                         }
5944                         form.templateAttachments.value += node.value;
5945                     }
5946                 }
5947             }
5948         }
5949
5950         // remove attachments
5951         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5952
5953         YAHOO.util.Connect.setForm(form);
5954
5955         AjaxObject.target = 'frameFlex';
5956
5957         // sending a draft email
5958         if(!isDraft && in_draft) {
5959             // remove row
5960             SE.listView.removeRowByUid(email_id);
5961         }
5962
5963         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5964         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5965
5966         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5967     },
5968
5969     /**
5970      * Handles clicking the email address link from a given view
5971      */
5972     composePackage : function() {
5973         if(composePackage != null) {
5974             SE.composeLayout.c0_composeNewEmail();
5975
5976
5977             if(composePackage.to_email_addrs) {
5978                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5979             } // if
5980             if (composePackage.subject != null && composePackage.subject.length > 0) {
5981                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5982             }
5983
5984             //If no parent fields are set in the composePackage, ensure they are cleared.
5985             var parentFields = ['parent_type','parent_name','parent_id'];
5986             for(var i=0;i<parentFields.length;i++)
5987             {
5988                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5989                     composePackage[parentFields[i]] = "";
5990             }
5991
5992             document.getElementById("parent_type").value = composePackage.parent_type;
5993             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5994             document.getElementById("parent_id").value = composePackage.parent_id;
5995             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5996             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5997
5998             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5999                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
6000             } // if
6001             if (composePackage.body != null && composePackage.body.length > 0) {
6002                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6003                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
6004                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
6005             } // if
6006             if (composePackage.attachments != null) {
6007                                 SE.composeLayout.loadAttachments(composePackage.attachments);
6008             } // if
6009
6010             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
6011                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
6012                         SE.util.emptySelectOptions(addressFrom);
6013                         var fromAccountOpts = composePackage.fromAccounts.data;
6014                         for(i=0; i<fromAccountOpts.length; i++) {
6015                               var key = fromAccountOpts[i].value;
6016                               var display = fromAccountOpts[i].text;
6017                               var opt = new Option(display, key);
6018                               if (fromAccountOpts[i].selected) {
6019                                 opt.selected = true;
6020                               }
6021                               addressFrom.options.add(opt);
6022                         }
6023
6024             } // if
6025         } // if
6026     },
6027
6028     setContentOnThisTiny : function() {
6029         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6030         var tinyHTML = tiny.getContent();
6031         composePackage.body = decodeURI(encodeURI(composePackage.body));
6032         // cn: bug 14361 - text-only templates don't fill compose screen
6033         if(composePackage.body == '') {
6034             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,'"');
6035         } // if
6036         //Flag determines if we should clear the tiny contents or just append
6037         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6038             SE.composeLayout.tinyHTML = '';
6039         else
6040             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6041
6042          tiny.setContent(SE.composeLayout.tinyHTML);
6043          //Indicate that the contents has been loaded successfully.
6044          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6045     },
6046     /**
6047      * Confirms closure of a compose screen if "x" is clicked
6048      */
6049     confirmClose : function(panel) {
6050         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6051             SE.composeLayout.closeCompose(panel.id);
6052             return true;
6053         } else {
6054             return false;
6055         }
6056     },
6057
6058     /**
6059      * forces close of a compose screen
6060      */
6061     forceCloseCompose : function(id) {
6062         SE.composeLayout.closeCompose(id);
6063
6064         // handle flow back to originating view
6065         if(composePackage) {
6066             // check if it's a module we need to return to
6067             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6068                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6069                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6070                     window.location = url;
6071                 }
6072             }
6073         }
6074     },
6075
6076     /**
6077      * closes the editor that just sent email
6078      * @param string id ID of composeLayout tab
6079      */
6080     closeCompose : function(id) {
6081         // destroy tinyMCE instance
6082         var idx = id.substr(13, id.length);
6083         var instanceId = "htmleditor" + idx;
6084         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6085
6086         // nullify DOM and namespace values.
6087         inCompose = false;
6088         SE.composeLayout[idx] = null;
6089         SE.tinyInstances[instanceId] = null;
6090         var tabsArray = SE.innerLayout.get("tabs");
6091         for (i = 0 ; i < tabsArray.length ; i++) {
6092                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6093                         tabsArray[i].close();
6094                         break;
6095                 }
6096         }
6097         //SE.innerLayout.getTab(idx).close();
6098     },
6099
6100     /**
6101     *  Enable the quick search for the compose relate field or search tab
6102     */
6103     enableQuickSearchRelate: function(idx,overides){
6104
6105         if(typeof overides != 'undefined')
6106         {
6107             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6108             var newModule = document.getElementById(newModuleID).value;
6109             var formName = overides['formName'];
6110             var fieldName = overides['fieldName'];
6111             var fieldId = overides['fieldId'];
6112             var fullName = formName + "_" + fieldName;
6113             var postBlurFunction = null;
6114         }
6115         else
6116         {
6117             var newModule = document.getElementById('data_parent_type'+idx).value;
6118             var formName = 'emailCompose'+idx;
6119             var fieldName = 'data_parent_name'+idx;
6120             var fieldId = 'data_parent_id'+idx;
6121             var fullName = formName + "_" + fieldName;
6122             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6123         }
6124
6125         if(typeof sqs_objects == 'undefined')
6126             window['sqs_objects'] = new Array;
6127
6128         window['sqs_objects'][fullName] = {
6129             form:formName,
6130                         method:"query",
6131                         modules:[newModule],
6132                         group:"or",
6133             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6134             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6135                         post_onblur_function: postBlurFunction,
6136             order:"name","limit":"30","no_match_text":"No Match"};
6137
6138
6139         if(typeof QSProcessedFieldsArray != 'undefined')
6140                 QSProcessedFieldsArray[fullName] = false;
6141         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6142                 QSFieldsArray[fullName].destroy();
6143                 delete QSFieldsArray[fullName];
6144         }
6145         if (Dom.get(fullName + "_results")) {
6146                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6147         }
6148
6149         enableQS(false);
6150     },
6151
6152         qsAddAddress : function(o) {
6153         if (o.name != "" && o.email1 != "")
6154         {
6155                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6156                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6157         }
6158     },
6159     /**
6160      * Returns a new instance ID, 0-index
6161      */
6162     getNewInstanceId : function() {
6163         this.currentInstanceId = this.currentInstanceId + 1;
6164         return this.currentInstanceId;
6165     },
6166
6167     /**
6168      * 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.
6169      */
6170     loadAttachments : function(result) {
6171         var idx = SE.composeLayout.currentInstanceId;
6172
6173         if(typeof(result) == 'object') {
6174                 //jchi #20680. Clean the former template attachments;
6175                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6176                         if(basket.innerHTML != ''){
6177                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6178                                         if (btn != 'yes'){
6179                                                 basket.innerHTML = '';
6180                                         }
6181                                 });
6182                         }
6183             for(i in result) {
6184                 if(typeof result[i] == 'object') {
6185                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6186                     var bean = result[i];
6187                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6188                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6189                 }
6190             }
6191         }
6192     },
6193
6194     /**
6195      * fills drop-down values for email templates and signatures
6196      */
6197     setComposeOptions : function(idx) {
6198         // send from accounts
6199         var addressFrom = document.getElementById('addressFrom' + idx);
6200
6201         if (addressFrom.options.length <= 0) {
6202                 SE.util.emptySelectOptions(addressFrom);
6203                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6204                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6205                       var key = fromAccountOpts[id].value;
6206                       var display = fromAccountOpts[id].text;
6207                       var is_default = false;
6208                       if(key == SUGAR.default_inbound_accnt_id)
6209                         is_default = true;
6210                       var opt = new Option(display, key);
6211                       addressFrom.options.add(opt);
6212                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6213                 }
6214         }
6215
6216         // email templates
6217         var et = document.getElementById('email_template' + idx);
6218         SE.util.emptySelectOptions(et);
6219
6220         for(var key in this.emailTemplates) { // iterate through assoc array
6221             var display = this.emailTemplates[key];
6222             var opt = new Option(display, key);
6223             et.options.add(opt);
6224         }
6225
6226         // signatures
6227         var sigs = document.getElementById('signatures' + idx);
6228         SE.util.emptySelectOptions(sigs);
6229
6230         for(var key in this.signatures) { // iterate through assoc array
6231             var display = this.signatures[key];
6232             var opt = new Option(display, key);
6233
6234             if(key == SE.userPrefs.signatures.signature_default) {
6235                 opt.selected = true;
6236             }
6237
6238             sigs.options.add(opt);
6239         }
6240
6241         // html/plain email?
6242         var htmlEmail = document.getElementById('setEditor' + idx);
6243         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6244             htmlEmail.checked = true;
6245         } else {
6246                 htmlEmail.checked = false;
6247         }
6248
6249         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6250     },
6251
6252     /**
6253      * After compose screen is rendered, async call to get email body from Sugar
6254      */
6255     replyForwardEmailStage2 : function() {
6256         SE.util.clearHiddenFieldValues('emailUIForm');
6257         SUGAR.showMessageBox(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6258
6259         var ieId = SE.composeLayout.replyForwardObj.ieId;
6260         var uid = SE.composeLayout.replyForwardObj.uid;
6261         var mbox = SE.composeLayout.replyForwardObj.mbox;
6262         var type = SE.composeLayout.replyForwardObj.type;
6263         var idx = SE.composeLayout.currentInstanceId;
6264
6265         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6266
6267         document.getElementById('emailSubject' + idx).value = type;
6268         document.getElementById('emailUIAction').value = 'composeEmail';
6269         document.getElementById('composeType').value = type;
6270         document.getElementById('ieId').value = ieId;
6271         document.getElementById('uid').value = uid;
6272         document.getElementById('mbox').value = mbox;
6273                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6274         var formObject = document.getElementById('emailUIForm');
6275         YAHOO.util.Connect.setForm(formObject);
6276
6277         var sendType = type;
6278         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6279     },
6280
6281     /**
6282     *  Show the hidden cc or bcc fields
6283     */
6284     showHiddenAddress: function(addrType,idx){
6285
6286         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6287         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6288                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6289                 this[addrType+'Hidden'+idx] = false;
6290
6291                 //After bcc or cc is added, move options below last addr field
6292                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6293
6294                 //If both cc and bcc hidden, remove the empty row containing text.
6295                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6296                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6297                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6298
6299                 // SE.composeLayout.resizeEditor(idx);
6300     },
6301     /**
6302     *  Hide the cc and bcc fields if they were shown.
6303     */
6304     hideHiddenAddresses: function(idx){
6305
6306         var addrTypes = ['cc','bcc'];
6307         for(var i = 0;i<addrTypes.length;i++)
6308         {
6309             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6310             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6311             this[addrTypes[i] + 'Hidden'+idx] = true
6312         }
6313
6314         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6315         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6316         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6317     }
6318 };
6319
6320 ////    END SE.composeLayout
6321 ///////////////////////////////////////////////////////////////////////////////
6322 ///////////////////////////////////////////////////////////////////////////////
6323 ////    SE.util
6324 SE.util = {
6325     /**
6326      * Cleans serialized UID lists of duplicates
6327      * @param string
6328      * @return string
6329      */
6330     cleanUids : function(str) {
6331         var seen = new Object();
6332         var clean = "";
6333         var arr = new String(str).split(",");
6334
6335         for(var i=0; i<arr.length; i++) {
6336             if(seen[arr[i]]) {
6337                 continue;
6338             }
6339
6340             clean += (clean != "") ? "," : "";
6341             clean += arr[i];
6342             seen[arr[i]] = true;
6343         }
6344
6345         return clean;
6346     },
6347
6348     /**
6349      * Clears hidden field values
6350      * @param string id ID of form element to clear
6351      */
6352     clearHiddenFieldValues : function(id) {
6353         var form = document.getElementById(id);
6354
6355         for(i=0; i<form.elements.length; i++) {
6356             if(form.elements[i].type == 'hidden') {
6357                 var e = form.elements[i];
6358                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6359                     e.value = '';
6360                 }
6361             }
6362         }
6363     },
6364
6365     /**
6366      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6367      */
6368     emptySelectOptions : function(el) {
6369         if(el) {
6370             for(i=el.childNodes.length - 1; i >= 0; i--) {
6371                 if(el.childNodes[i]) {
6372                     el.removeChild(el.childNodes[i]);
6373                 }
6374             }
6375         }
6376     },
6377
6378     /**
6379      * Returns the MBOX path in the manner php_imap expects:
6380      * ie: INBOX.DEBUG.test
6381      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6382      */
6383     generateMboxPath : function(str) {
6384         var ex = str.split("::");
6385
6386         /* we have a serialized MBOX path */
6387         if(ex.length > 1) {
6388             var start = false;
6389             var ret = '';
6390             for(var i=0; i<ex.length; i++) {
6391                 if(ex[i] == 'INBOX') {
6392                     start = true;
6393                 }
6394
6395                 if(start == true) {
6396                     if(ret != "") {
6397                         ret += ".";
6398                     }
6399                     ret += ex[i];
6400                 }
6401             }
6402         } else {
6403             /* we have a Sugar folder GUID - do nothing */
6404             return str;
6405         }
6406
6407         return ret;
6408     },
6409
6410     /**
6411      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6412      * @param HTMLElement el
6413      * @return string GUID of found element or empty on failure
6414      */
6415     getGuidFromElement : function(el) {
6416         var GUID = '';
6417         var iterations = 4;
6418         var passedEl = el;
6419
6420         // upwards
6421         for(var i=0; i<iterations; i++) {
6422             if(el) {
6423                 if(el.id.match(SE.reGUID)) {
6424                     return el.id;
6425                 } else {
6426                     el = el.parentNode;
6427                 }
6428             }
6429         }
6430
6431         return GUID;
6432     },
6433
6434     /**
6435      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6436      * @return string
6437      */
6438     getPanelId : function() {
6439         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6440     },
6441
6442     /**
6443      * wrapper to handle weirdness with IE
6444      * @param string instanceId
6445      * @return tinyMCE Controller object
6446      */
6447     getTiny : function(instanceId) {
6448         if(instanceId == '') {
6449             return null;
6450         }
6451
6452         var t = tinyMCE.getInstanceById(instanceId);
6453
6454         if(this.isIe()) {
6455             this.sleep(200);
6456             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6457         }
6458         return t;
6459     },
6460
6461     /**
6462      * Simple check for MSIE browser
6463      * @return bool
6464      */
6465     isIe : function() {
6466         var nav = new String(navigator.appVersion);
6467         if(nav.match(/MSIE/)) {
6468             return true;
6469         }
6470         return false;
6471     },
6472
6473     /**
6474      * Recursively removes an element from the DOM
6475      * @param HTMLElement
6476      */
6477     removeElementRecursive : function(el) {
6478         this.emptySelectOptions(el);
6479     },
6480
6481     /**
6482      * Fakes a sleep
6483      * @param int
6484      */
6485     sleep : function(secs) {
6486         setTimeout("void(0);", secs);
6487     },
6488
6489     /**
6490      * Converts a <select> element to an Ext.form.combobox
6491      */
6492      convertSelect : function(select) {
6493        alert('in convertSelect');
6494        if (typeof(select) == "string") {
6495            select = document.getElementById(select);
6496        }
6497      },
6498
6499      findChildNode : function (parent, property, value) {
6500          for (i in parent.children) {
6501                  var child = parent.children[i];
6502                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6503                          return child;
6504                  var searchChild = SE.util.findChildNode(child, property, value);
6505                  if (searchChild)
6506                          return searchChild;
6507          }
6508          return false;
6509      },
6510
6511      cascadeNodes : function (parent, fn, scope, args) {
6512          for (i in parent.children) {
6513                  var child = parent.children[i];
6514                  var s = scope ? scope : child;
6515                  var a = args ? args : child;
6516                  fn.call(s, a);
6517                  SE.util.cascadeNodes(child, fn, scope, args);
6518          }
6519      }
6520 };
6521
6522
6523 ////    END UTIL
6524 ///////////////////////////////////////////////////////////////////////////////
6525
6526
6527 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6528                                 
6529 /*********************************************************************************
6530  * SugarCRM Community Edition is a customer relationship management program developed by
6531  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6532  * 
6533  * This program is free software; you can redistribute it and/or modify it under
6534  * the terms of the GNU Affero General Public License version 3 as published by the
6535  * Free Software Foundation with the addition of the following permission added
6536  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6537  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6538  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6539  * 
6540  * This program is distributed in the hope that it will be useful, but WITHOUT
6541  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6542  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6543  * details.
6544  * 
6545  * You should have received a copy of the GNU Affero General Public License along with
6546  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6547  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6548  * 02110-1301 USA.
6549  * 
6550  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6551  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6552  * 
6553  * The interactive user interfaces in modified source and object code versions
6554  * of this program must display Appropriate Legal Notices, as required under
6555  * Section 5 of the GNU Affero General Public License version 3.
6556  * 
6557  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6558  * these Appropriate Legal Notices must retain the display of the "Powered by
6559  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6560  * technical reasons, the Appropriate Legal Notices must display the words
6561  * "Powered by SugarCRM".
6562  ********************************************************************************/
6563
6564
6565 if (typeof console == "undefined")
6566         console = { log: function(o) {alert(o)} };
6567
6568 var AjaxObject = {
6569         ret : '',
6570         currentRequestObject : null,
6571         //timeout : 30000, // 30 second timeout default
6572         timeout : 9999999999, // 30 second timeout default
6573         forceAbort : false,
6574         trail : new Array(),
6575
6576         /**
6577          */
6578         _reset : function() {
6579                 this.timeout = 30000;
6580                 this.forceAbort = false;
6581         },
6582
6583         folderRenameCleanup : function() {
6584                 SUGAR.email2.folders.setSugarFolders();
6585         },
6586
6587         fullSyncCleanup : function(o) {
6588                 this.folders.checkMailCleanup(o);
6589                 SUGAR.email2.settings.settingsDialog.hide();
6590         },
6591
6592         /**
6593          */
6594         composeCache : function(o) {
6595                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6596                 // get email templates and user signatures
6597                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6598
6599                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6600                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6601                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6602
6603                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6604
6605                 //Set the error array so we can notify the user when they try to hit send if any errors
6606                 //are present.  We will also notify them now (after hitting compose button).
6607                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6608
6609
6610                 //if error element is returning an array, then check the length to make sure we have error messages
6611                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6612                         //add error messages for display
6613                         for(i in ret.errorArray)
6614                                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6615                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6616                         //if error element is returning an object, and the object value is not empty or null, then display error message
6617                         for(i in ret.errorArray)
6618                                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6619                 }
6620
6621                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6622                 if(SUGAR.isIE) {
6623                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6624                         if(overlayPanel) {
6625                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6626                         }
6627                 }
6628         },
6629
6630
6631         handleDeleteSignature : function(o) {
6632                 SUGAR.hideMessageBox();
6633         var ret = YAHOO.lang.JSON.parse(o.responseText);
6634                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6635         var field = document.getElementById('signature_id');
6636                 SUGAR.email2.util.emptySelectOptions(field);
6637
6638                 for(var i in ret.signatures) { // iterate through assoc array
6639                         var opt = new Option(ret.signatures[i], i);
6640                         field.options.add(opt);
6641                 }
6642                 setSigEditButtonVisibility();
6643         },
6644
6645         /**
6646          */
6647         handleDeleteReturn : function(o) {
6648                 // force refresh ListView
6649                 SUGAR.hideMessageBox();
6650                 if(document.getElementById('focusEmailMbox')) {
6651                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6652                 }
6653
6654                 // need to display success message before calling next async call?
6655                 document.getElementById(this.target).innerHTML = o.responseText;
6656         },
6657
6658         /**
6659          */
6660     handleFailure : function(o) {
6661                 // Failure handler
6662                 SUGAR.showMessageBox('Exception occurred...', o.statusText, 'alert');
6663                 if(document.getElementById('saveButton')) {
6664                         document.getElementById('saveButton').disabled = false;
6665                 }
6666         },
6667
6668         handleReplyForward : function(o) {
6669                 var a = YAHOO.lang.JSON.parse(o.responseText);
6670                 globalA = a;
6671                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6672
6673                 document.getElementById('email_id' + idx).value = a.uid;
6674                 document.getElementById('emailSubject' + idx).value = a.name;
6675                 document.getElementById('addressTO' + idx).value = a.from;
6676                 document.getElementById('uid' + idx).value = a.uid;
6677                 if(a.cc) {
6678                         document.getElementById('addressCC' + idx).value = a.cc;
6679                         SE.composeLayout.showHiddenAddress('cc', idx);
6680                 }
6681
6682                 if(a.type) {
6683                         document.getElementById('type' + idx).value = a.type;
6684                 }
6685
6686                 // apply attachment values
6687                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6688
6689                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6690         },
6691
6692         handleReplyForwardForDraft : function(o) {
6693                 var a = YAHOO.lang.JSON.parse(o.responseText);
6694                 globalA = a;
6695                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6696
6697                 document.getElementById('email_id' + idx).value = a.uid;
6698                 document.getElementById('emailSubject' + idx).value = a.name;
6699                 document.getElementById('addressTO' + idx).value = a.to;
6700
6701                 if(a.cc) {
6702                         document.getElementById('addressCC' + idx).value = a.cc;
6703                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6704                 }
6705
6706                 if(a.bcc) {
6707                         document.getElementById('addressBCC' + idx).value = a.bcc;
6708                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6709                 }
6710
6711
6712                 if(a.type) {
6713                         document.getElementById('type' + idx).value = a.type;
6714                 }
6715
6716
6717                 // apply attachment values
6718                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6719
6720                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6721         },
6722
6723         /**
6724          */
6725         handleSuccess : function(o) {
6726                 document.getElementById(this.target).innerHTML = o.responseText;
6727                 SUGAR.hideMessageBox();
6728         },
6729
6730         /**
6731          */
6732         ieDeleteSuccess : function(o) {
6733                 SUGAR.hideMessageBox();
6734                 SUGAR.email2.accounts.refreshInboundAccountTable();
6735                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6736                 SUGAR.email2.accounts.rebuildFolderList();
6737         },
6738
6739         /**
6740          */
6741         ieSaveSuccess : function(o) {
6742                 document.getElementById('saveButton').disabled = false;
6743                 var a = YAHOO.lang.JSON.parse(o.responseText);
6744                 if (a) {
6745                         if(a.error) {
6746                                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6747                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6748                         } else {
6749                                 resp = YAHOO.lang.JSON.parse(o.responseText);
6750                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6751                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6752                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6753                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6754                         }
6755                 } else {
6756                      SUGAR.hideMessageBox();
6757                      SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6758                 }
6759
6760         },
6761
6762         /**
6763          */
6764         loadAttachments : function(o) {
6765                 var result = YAHOO.lang.JSON.parse(o.responseText);
6766
6767                 SUGAR.email2.composeLayout.loadAttachments(result);
6768         },
6769
6770         /**
6771          */
6772         loadSignature : function(o) {
6773                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6774                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6775                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6776         },
6777
6778         /**
6779          * Follow up to mark email read|unread|flagged
6780          */
6781         markEmailCleanup : function(o) {
6782                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6783                 if (!ret['status']) {
6784                 SUGAR.hideMessageBox();
6785                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6786                 } else {
6787                         SUGAR.email2.contextMenus.markEmailCleanup();
6788                 } // else
6789         },
6790
6791         /**
6792          */
6793         rebuildShowFolders : function(o) {
6794                 var t = YAHOO.lang.JSON.parse(o.responseText);
6795                 var show = document.getElementById('ieAccountListShow');
6796
6797                 SUGAR.email2.util.emptySelectOptions(show);
6798
6799                 for(i=0; i<t.length; i++) { // iterate through assoc array
6800                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6801                         opt.selected = t[i].selected;
6802                         show.options.add(opt);
6803                 }
6804
6805                 SUGAR.email2.accounts.renderTree();
6806         },
6807         /**
6808          */
6809         saveListViewSortOrderPart2 : function() {
6810                 // create the JSON string the func expects
6811                 focusFolderPath = '[ "Home", "' + ieName + '"';
6812
6813                 var f = new String(focusFolder);
6814                 var fEx = f.split('.');
6815
6816                 for(i=0; i<fEx.length; i++) {
6817                         focusFolderPath += ', "' + fEx[i] +'"'
6818                 }
6819
6820                 focusFolderPath += ']';
6821
6822                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6823                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6824         },
6825
6826         /**
6827          *
6828          */
6829         sendEmailCleanUp : function(o) {
6830         var ret;
6831         SUGAR.hideMessageBox();
6832
6833         try {
6834             ret = YAHOO.lang.JSON.parse(o.responseText);
6835             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6836             //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6837         } catch(err) {
6838             if (o.responseText) {
6839                 SUGAR.showMessageBox(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6840                     }
6841             // Else we have an error here.
6842         }        
6843
6844                 if (typeof(SE.grid) != 'undefined')
6845                         SE.listView.refreshGrid();
6846                 //Disabled while address book is disabled
6847
6848                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6849                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6850                 //close the shortcut bar menu
6851                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6852                         if(action_sugar_grp1 == 'DetailView') {
6853                                 showSubPanel('history',null,true);
6854                         } else if(action_sugar_grp1 == 'quickcreate') {
6855                                 closeEmailOverlay();
6856                         }
6857                 }
6858
6859         },
6860
6861         ieSendSuccess : function(o) {
6862                 SUGAR.hideMessageBox();
6863                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6864         },
6865
6866         /**
6867          */
6868         settingsFolderRefresh : function(o) {
6869                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6870                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6871                 var user = document.getElementById('userFolders');
6872
6873                 SUGAR.email2.util.emptySelectOptions(user);
6874
6875                 for(i=0; i<ret.userFolders.length; i++) {
6876                         var display = ret.userFolders[i].name;
6877                         var value = ret.userFolders[i].id;
6878                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6879                         var opt = new Option(display, value, selected);
6880                         opt.selected = selected;
6881                         user.options.add(opt);
6882                 }
6883         },
6884
6885         /**
6886          */
6887         startRequest : function(callback, args, forceAbort) {
6888                 if(this.currentRequestObject != null) {
6889                         if(this.forceAbort == true) {
6890                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6891                         }
6892                 }
6893                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6894                 this._reset();
6895         },
6896
6897         requestInProgress : function() {
6898                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6899         },
6900
6901         /**
6902          */
6903         updateFolderSubscriptions : function() {
6904                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6905                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6906                 SUGAR.hideMessageBox();
6907         },
6908
6909         /**
6910          */
6911         updateFrameFolder : function() {
6912                 SUGAR.email2.folders.checkEmailAccounts();
6913         },
6914
6915         /**
6916          */
6917         updateUserPrefs : function(o) {
6918                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6919                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6920         },
6921
6922         /**
6923          */
6924         uploadAttachmentSuccessful : function(o) {
6925                 // clear out field
6926                 document.getElementById('email_attachment').value = '';
6927                 
6928                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6929                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6930                 var overall = document.getElementById('addedFiles' + idx);
6931                 var index = overall.childNodes.length;
6932                 var out =
6933                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6934                                 // remove button
6935                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6936                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6937                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6938                                 // file icon
6939                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6940                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6941                                 // hidden id field
6942                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6943                                 // file name
6944                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6945                                 "<br/>" +
6946                         "</div>";
6947                 overall.innerHTML += out;
6948                 if(SUGAR.email2.util.isIe()) {
6949                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6950                 }
6951
6952                 // hide popup
6953                 SUGAR.email2.addFileDialog.hide();
6954                 // focus attachments
6955                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6956         }
6957 };
6958
6959
6960 ///////////////////////////////////////////////////////////////////////////
6961 ////    PER MODULE CALLBACK OBJECTS
6962 AjaxObject.accounts = {
6963         saveOutboundCleanup : function(o) {
6964                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6965                 SUGAR.email2.accounts.outboundDialog.hide();
6966                 var id = o.responseText;
6967                 SUGAR.email2.accounts.newAddedOutboundId = id;
6968                 },
6969         saveDefaultOutboundCleanup: function(o){
6970
6971         },
6972         callbackEditOutbound : {
6973                 success : function(o)
6974                 {
6975                         var ret = YAHOO.lang.JSON.parse(o.responseText);
6976                         // show overlay
6977                         SUGAR.email2.accounts.showAddSmtp();
6978
6979                         // fill values
6980                         document.getElementById("mail_id").value = ret.id;
6981                         document.getElementById("type").value = ret.type;
6982                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6983                         document.getElementById("mail_name").value = ret.name;
6984                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6985                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6986                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6987                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6988                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6989                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6990                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6991
6992             if(ret.type == 'system-override') {
6993                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6994                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6995             }
6996             else {
6997                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6998                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6999             }
7000             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
7001
7002                 },
7003                 failure : AjaxObject.handleFailure,
7004                 timeout : AjaxObject.timeout,
7005                 scope   : AjaxObject
7006         },
7007         callbackDeleteOutbound : {
7008                 success : function(o) {
7009                     var ret = YAHOO.lang.JSON.parse(o.responseText);
7010                     if(ret.is_error)
7011                     {
7012                         if(confirm(ret.error_message))
7013                 {
7014                     SUGAR.showMessageBox(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
7015                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7016                 }
7017                 else
7018                     SUGAR.hideMessageBox();
7019                     }
7020                     else
7021                     {
7022                              SUGAR.hideMessageBox();
7023                              SUGAR.email2.accounts.refreshOuboundAccountTable();
7024                     }
7025                 },
7026
7027                 failure : AjaxObject.handleFailure,
7028                 timeout : AjaxObject.timeout,
7029                 scope   : AjaxObject
7030         },
7031
7032         callbackCheckMailProgress : {
7033            success : function(o) {
7034                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7035                    SUGAR.email2.accounts.totalMsgCount = -1;
7036                }
7037
7038                //Check for server timeout / errors
7039                var ret = YAHOO.lang.JSON.parse(o.responseText);
7040                var done = false;
7041
7042                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7043                    SUGAR.hideMessageBox();
7044                    SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7045                    SUGAR.email2.accounts.totalMsgCount = -1;
7046                //SUGAR.email2.folders.rebuildFolders();
7047                done = true;
7048                }
7049
7050                var currIeId = ret['ieid'];
7051
7052
7053                var serverCount = ret.count;
7054
7055                if (ret['status'] == 'done') {
7056                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7057                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7058                            //We are all done
7059                            done = true;
7060                            break;
7061                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7062                            //Go to next account
7063                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
7064                            ret.count = 0;
7065                            SUGAR.email2.accounts.totalMsgCount = -1;
7066                            break;
7067                        }
7068                    }
7069                }
7070                else if (ret.mbox && ret.totalcount && ret.count) {
7071                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7072                    if (ret.count >= ret.totalcount) {
7073                        serverCount = 0;
7074                    }
7075                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7076                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7077                } else {
7078                        SUGAR.hideMessageBox();
7079                SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7080                SUGAR.email2.accounts.totalMsgCount = -1;
7081                done = true;
7082                    }
7083
7084                if (done) {
7085                    SUGAR.email2.accounts.totalMsgCount = -1;
7086                    SUGAR.hideMessageBox();
7087                    SUGAR.email2.folders.rebuildFolders();
7088                    SE.listView.refreshGrid();
7089                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7090                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7091                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7092                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7093            } else {
7094                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7095                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7096                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7097                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7098                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7099                }
7100            },
7101            failure : AjaxObject.handleFailure,
7102        timeout : AjaxObject.timeout,
7103        scope   : AjaxObject
7104         }
7105 };
7106
7107 ///////////////////////////////////////////////////////////////////////////////
7108 ////    COMPOSE LAYOUT
7109 AjaxObject.composeLayout = {
7110         /**
7111          * Populates the record id
7112          */
7113     saveDraftCleanup : function(o) {
7114         var ret;
7115         SUGAR.hideMessageBox();
7116
7117         try {
7118             ret = YAHOO.lang.JSON.parse(o.responseText);
7119             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7120         } catch(err) {
7121             if (o.responseText) {
7122                 SUGAR.showMessageBox(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7123             }
7124         }
7125     }
7126 };
7127
7128 AjaxObject.composeLayout.callback = {
7129         saveDraft : {
7130                 success : AjaxObject.composeLayout.saveDraftCleanup,
7131                 failure : AjaxObject.handleFailure,
7132                 timeout : AjaxObject.timeout,
7133                 scope   : AjaxObject
7134         }
7135 };
7136
7137 AjaxObject.detailView = {
7138         /**
7139          * Pops-up a printable view of an email
7140          */
7141         displayPrintable : function(o) {
7142                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7143                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7144                 // 2 below must be in global context
7145                 meta = ret.meta;
7146                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7147                 email = ret.meta.email;
7148                 if (typeof(email.cc) == 'undefined') {
7149                   email.cc = "";
7150                 }
7151
7152                 var out = displayTemplate.exec({
7153                         'app_strings'   : app_strings,
7154                         'theme'                 : theme,
7155                         'idx'                   : 'Preview',
7156                         'meta'                  : meta,
7157                         'email'                 : meta.email
7158                 });
7159
7160                 // open popup window
7161                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7162                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7163
7164                 popup.document.write(out);
7165                 popup.document.close();
7166         },
7167
7168         /**
7169          * Takes formatted response and creates a modal pop-over containing a title and content
7170          */
7171         displayView : function(o) {
7172                 var SED = SUGAR.email2.detailView;
7173                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7174
7175                 if(!SED.viewDialog) {
7176                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7177                                 modal:true,
7178                 visible:true,
7179                 fixedcenter:true,
7180                 constraintoviewport: true,
7181                                 shadow  : true
7182                         });
7183             SED.viewDialog.renderEvent.subscribe(function() {
7184                 var content = this.body.firstChild;
7185                 var viewH = YAHOO.util.Dom.getViewportHeight();
7186                 if (content) {
7187                         this.body.style.overflow = "auto";
7188                         this.body.style.width = "800px";
7189                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7190                 }
7191             }, SED.viewDialog);
7192                 } // end lazy load
7193                 SED.viewDialog.setHeader(ret.title);
7194                 SED.viewDialog.setBody(ret.html);
7195                 SED.viewDialog.render();
7196                 SED.viewDialog.show();
7197         },
7198
7199         /**
7200          * Generates a modal popup to populate with the contents of bean's full EditView
7201          */
7202         showQuickCreateForm : function(o) {
7203                 var SED = SUGAR.email2.detailView;
7204                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7205
7206                 if(!SED.quickCreateDialog) {
7207                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7208                                 modal:true,
7209                                 visible:true,
7210                 fixedcenter:true,
7211                 constraintoviewport: true,
7212                                 shadow  : true
7213                         });
7214
7215             SED.quickCreateDialog.renderEvent.subscribe(function() {
7216                 var viewH = YAHOO.util.Dom.getViewportHeight();
7217                 var contH = 0;
7218                 for (var i in this.body.childNodes) {
7219                         if (this.body.childNodes[i].clientHeight) {
7220                                 contH += this.body.childNodes[i].clientHeight;
7221                         } else if (this.body.childNodes[i].offsetHeight) {
7222                                 contH += this.body.childNodes[i].offsetHeight;
7223                         } // if
7224                 }
7225                         this.body.style.width = "800px";
7226                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7227                         this.body.style.overflow = "auto";
7228             }, SED.quickCreateDialog);
7229
7230             SED.quickCreateDialog.hideEvent.subscribe(function(){
7231                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7232                                 /*for(var qsField in qsFields){
7233                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7234                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7235                                 }*/
7236                         });
7237             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7238                 } // end lazy load
7239                 if (ret.html) {
7240                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7241                 }
7242                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7243                 SED.quickCreateDialog.render();
7244                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7245
7246                 SED.quickCreateDialog.ieId = ret.ieId;
7247                 SED.quickCreateDialog.uid = ret.uid;
7248         SED.quickCreateDialog.mbox = ret.mbox;
7249         SED.quickCreateDialog.qcmodule = ret.module;
7250
7251         SED.quickCreateDialog.show();
7252
7253                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7254                 if (editForm) {
7255                   editForm.module.value = 'Emails';
7256                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7257                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7258                   var instId = ret.module + count;
7259                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7260                   SED.quickCreateEmailCallback = function(instId, tableId) {
7261                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7262                           if (typeof(eaw) == "undefined")
7263                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7264                                                 + instId + "','" + tableId + "');", 100);
7265                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7266                   }
7267                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7268                                         + instId + "','" + tableId + "');", 100);
7269                 }
7270         },
7271
7272         saveQuickCreateForm : function(o) {
7273             SUGAR.hideMessageBox();
7274                 SUGAR.email2.detailView.quickCreateDialog.hide();
7275                 validate['EditView'] = [ ];
7276         },
7277
7278         saveQuickCreateFormAndReply : function(o) {
7279         SUGAR.hideMessageBox();
7280         var ret = YAHOO.lang.JSON.parse(o.responseText);
7281         SUGAR.email2.detailView.quickCreateDialog.hide();
7282         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7283         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7284         if (ret) {
7285             var emailID = ret.id;
7286             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7287         } else {
7288             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7289         }
7290         //Cean the validate cache to prevent errors on the next call
7291         validate['EditView'] = [ ];
7292     },
7293
7294         saveQuickCreateFormAndAddToAddressBook : function(o) {
7295            SUGAR.hideMessageBox();
7296                 SUGAR.email2.detailView.quickCreateDialog.hide();
7297                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7298                 validate['EditView'] = [ ];
7299         },
7300
7301         handleAssignmentDialogAssignAction : function() {
7302
7303
7304             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7305
7306             var dist = 'direct';
7307             var users = false;
7308             var rules = false;
7309             var get = "";
7310             var found_teams = false;
7311             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7312             if(!found_teams && assign_user_id == '' )
7313             {
7314                 alert(warning_message);
7315                 return;
7316             }
7317
7318             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7319             var uids = "";
7320             for(i=0; i<emailUids.length; i++) {
7321                 if(uids != '') {
7322                     uids += app_strings.LBL_EMAIL_DELIMITER;
7323                 }
7324                 uids += emailUids[i];
7325             }
7326
7327             var row = SUGAR.email2.grid.getSelectedRows()[0];
7328             var data = SUGAR.email2.grid.getRecord(row).getData();
7329             var ieid = data.ieId;
7330             var mbox = data.mbox;
7331             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7332             SUGAR.email2.contextMenus.assignToDialogue.hide();
7333             SUGAR.showMessageBox('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7334
7335         },
7336
7337         handleAssignmentDialogDeleteAction : function() {
7338                 // TO pass list of UIDS/emailIds
7339                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7340                 var row = SUGAR.email2.grid.getSelections()[0];
7341                 var ieid = row.data.ieId;
7342             var mbox = row.data.mbox;
7343         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7344         SUGAR.email2.contextMenus.assignmentDialog.hide();
7345                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7346
7347                 // AJAX Call
7348
7349         },
7350
7351         showEmailDetailView : function(o) {
7352         SUGAR.hideMessageBox();
7353         var SED = SUGAR.email2.detailView;
7354                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7355
7356                 if(!SED.quickCreateDialog) {
7357                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7358                                 modal:true,
7359                                 visible:true,
7360                 //fixedcenter:true,
7361                 constraintoviewport: true,
7362                 draggable: true,
7363                                 autofillheight: "body",
7364                                 shadow  : true
7365                         });
7366                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7367                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7368                 var contH = 0;
7369                 for (var i in this.body.childNodes) {
7370                         if (this.body.childNodes[i].offsetHeight)
7371                                 contH += this.body.childNodes[i].offsetHeight;
7372                 }
7373                         this.body.style.overflow = "auto";
7374                         this.body.style.width = "800px";
7375                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7376                         this.center();
7377             }, SED.quickCreateDialog);
7378                 }
7379                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7380                 SED.quickCreateDialog.setBody(ret.html);
7381                 SED.quickCreateDialog.render();
7382         SUGAR.util.evalScript(ret.html);
7383         SED.quickCreateDialog.show();
7384         },
7385
7386         showAssignmentDialogWithData : function(o) {
7387         var SEC = SUGAR.email2.contextMenus;
7388                 SUGAR.hideMessageBox();
7389         var ret = YAHOO.lang.JSON.parse(o.responseText);
7390         if (!SEC.assignmentDialog) {
7391                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7392                         visible:false,
7393                 fixedcenter:true,
7394                 constraintoviewport: true,
7395                         modal   : true
7396                 });
7397                 SEC.assignmentDialog.setBody("");
7398                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7399                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7400                 var iev = YAHOO.util.Dom.get("Distribute");
7401                 if (iev) {
7402                         this.body.style.width = "700px";
7403                 }
7404             },  SEC.assignmentDialog);
7405                 SEC.assignmentDialog.render();
7406         }
7407         SEC.assignmentDialog.setBody(ret);
7408         SEC.assignmentDialog.render();
7409         validate = [];
7410         SEC.assignmentDialog.show();
7411         SUGAR.util.evalScript(ret);
7412         },
7413
7414         showImportForm : function(o) {
7415                 var SED = SUGAR.email2.detailView;
7416                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7417         
7418         document.getElementById('quickCreateContent').innerHTML = "";
7419         SUGAR.hideMessageBox();
7420         if (!ret) {
7421             return false;
7422         }
7423
7424         if(!SED.importDialog) {
7425             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7426                 modal:true,
7427                 visible:false,
7428                 fixedcenter:true,
7429                 constraintoviewport: true,
7430                 buttons : [{
7431                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7432                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7433                 }]//,
7434                 //scroll : true
7435             });
7436             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7437             SED.importDialog.setBody("");
7438             SED.importDialog.hideEvent.subscribe(function(){
7439                 for(var i in QSFieldsArray) {
7440                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7441                                 QSFieldsArray[i].destroy();
7442                                 delete QSFieldsArray[i];
7443                         }
7444                         if (QSProcessedFieldsArray[i]) {
7445                                 QSProcessedFieldsArray[i] = false;
7446                         } // if
7447                                 }
7448             });
7449             SED.importDialog.renderEvent.subscribe(function() {
7450                 var iev = YAHOO.util.Dom.get("ImportEditView");
7451                 if (iev) {
7452                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7453                         this.body.style.width = "600px";
7454                 }
7455             }, SED.importDialog);
7456             SED.importDialog.render();
7457         } // end lazy load
7458         SED.importDialog.setBody(ret.html);
7459         SED.importDialog.ret = ret;
7460         SUGAR.util.evalScript(ret.html);
7461         SED.importDialog.render();
7462         validate = [];
7463         SED.importDialog.show();
7464         SED.importDialog.focusFirstButton();
7465     },
7466     getImportAction : function(ret) {
7467         if (!check_form('ImportEditView')) return false;
7468         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7469                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7470                 return false;
7471         } // if
7472                 var get = "";
7473         var editView = document.getElementById('ImportEditView');
7474         if (editView.assigned_user_id != null) {
7475             get = get + "&user_id=" + editView.assigned_user_id.value
7476             //var user_id = editView.assigned_user_id.value;
7477         }
7478         var parent_id = editView.parent_id.value;
7479         var parent_type = editView.parent_type.value;
7480         var row = SUGAR.email2.grid.getSelectedRows()[0];
7481         row = SUGAR.email2.grid.getRecord(row);
7482         var data = row.getData();
7483         var ieId = data.ieId;
7484         var mbox = data.mbox;
7485         var serverDelete = editView.serverDelete.checked;
7486         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7487         var uids = "";
7488         for(i=0; i<emailUids.length; i++) {
7489             if(uids != '') {
7490                 uids += app_strings.LBL_EMAIL_DELIMITER;
7491             }
7492             uids += emailUids[i];
7493         }
7494
7495         var action = 'importEmail&uid=';
7496         if (ret.move) {
7497             action = 'moveEmails';
7498             action = action + '&sourceFolder=' + ret['srcFolder'];
7499             action = action + '&sourceIeId=' + ret['srcIeId'];
7500             action = action + '&destinationFolder=' + ret['dstFolder'];
7501             action = action + '&destinationIeId=' + ret['dstIeId'];
7502             action = action + '&emailUids=';
7503         }
7504         if (action.search(/importEmail/) != -1) {
7505             SUGAR.showMessageBox(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7506         } else {
7507             SUGAR.showMessageBox("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7508         }
7509
7510         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7511         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7512         SUGAR.email2.detailView.importDialog.hide();
7513         document.getElementById('importDialogContent').innerHTML = "";
7514
7515     },
7516     showRelateForm : function(o) {
7517         var SED = SUGAR.email2.detailView;
7518         var ret = YAHOO.lang.JSON.parse(o.responseText);
7519         document.getElementById('quickCreateContent').innerHTML = "";
7520         SUGAR.hideMessageBox();
7521         if (!ret) {
7522             return false;
7523         }
7524         dialog_loaded = true;
7525
7526         if(!SED.relateDialog) {
7527             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7528                                 modal:true,
7529                                 visible:true,
7530                 fixedcenter:true,
7531                 width: '800px',
7532                 constraintoviewport: true,
7533                                 buttons : [{
7534                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7535                                         if (!check_form('RelateEditView')) return false;
7536                                         var get = "";
7537                         var editView = document.getElementById('RelateEditView');
7538                         var parent_id = editView.parent_id.value;
7539                         var parent_type = editView.parent_type.value;
7540                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7541                         row  = SUGAR.email2.grid.getRecord(row);
7542                         var ieId = row.getData().ieId;
7543                         var mbox = row.getData().mbox;
7544                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7545                         var uids = "";
7546                         for(i=0; i<emailUids.length; i++) {
7547                             if(uids != '') {
7548                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7549                             }
7550                             uids += emailUids[i];
7551                         }
7552                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7553                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7554                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7555                         SED.relateDialog.hide();
7556                         document.getElementById('relateDialogContent').innerHTML = "";
7557                         }
7558                 }]
7559                         });
7560
7561             SED.relateDialog.hideEvent.subscribe(function(){
7562                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7563                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7564                         delete QSFieldsArray['ImportEditView_parent_name'];
7565                 } // if
7566                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7567                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7568                                 } // if
7569             });
7570
7571             SED.relateDialog.renderEvent.subscribe(function() {
7572                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7573                 var contH = 0;
7574                 for (var i in this.body.childNodes) {
7575                         if (this.body.childNodes[i].clientHeight)
7576                                 contH += this.body.childNodes[i].clientHeight;
7577                 }
7578             }, SED.relateDialog);
7579             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7580                 } // end lazy load
7581
7582         SED.relateDialog.setBody(ret.html);
7583         SED.relateDialog.render();
7584         SUGAR.util.evalScript(ret.html);
7585         SED.relateDialog.show();
7586     }
7587 };
7588 /**
7589  * DetailView callbacks
7590  */
7591 AjaxObject.detailView.callback = {
7592         emailDetail : {
7593                 success : function(o) {
7594                         SUGAR.email2.o = o;
7595                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7596                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7597                 },
7598                 argument: [targetDiv],
7599                 failure : AjaxObject.handleFailure,
7600                 timeout : 0,
7601                 scope   : AjaxObject
7602         },
7603         emailPreview : {
7604                 success : function(o) {
7605                         SUGAR.email2.o = o;
7606                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7607                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7608                 },
7609                 failure : AjaxObject.handleFailure,
7610                 timeout : 0,
7611                 scope   : AjaxObject
7612         },
7613         viewPrint : {
7614                 success : AjaxObject.detailView.displayPrintable,
7615                 failure : AjaxObject.handleFailure,
7616                 timeout : AjaxObject.timeout,
7617                 scope   : AjaxObject
7618         },
7619         viewRaw : {
7620                 success : AjaxObject.detailView.displayView,
7621                 failure : AjaxObject.handleFailure,
7622                 timeout : AjaxObject.timeout,
7623                 scope   : AjaxObject
7624         }
7625 };
7626
7627
7628
7629
7630
7631 AjaxObject.folders = {
7632         /**
7633          * check-mail post actions
7634          */
7635         checkMailCleanup : function(o) {
7636                 SUGAR.hideMessageBox();
7637                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7638
7639                 // refresh focus ListView
7640                 SE.listView.refreshGrid();
7641                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7642         },
7643
7644         /**
7645          */
7646         rebuildFolders : function(o) {
7647                 SUGAR.hideMessageBox();
7648
7649                 var data = YAHOO.lang.JSON.parse(o.responseText);
7650
7651                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7652                 SUGAR.email2.folders.setSugarFolders();
7653         }
7654 };
7655 AjaxObject.folders.callback = {
7656         checkMail : {
7657                 success : AjaxObject.folders.checkMailCleanup,
7658                 failure : AjaxObject.handleFailure,
7659                 timeout : 600000, // 5 mins
7660                 scope   : AjaxObject
7661         }
7662 }
7663
7664 AjaxObject.rules = {
7665         loadRulesForSettings : function(o) {
7666                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7667                 // assume we have the class we need
7668                 SUGAR.routing.getStrings();
7669                 SUGAR.routing.getDependentDropdowns();
7670         }
7671 };
7672 ////    END PER MODULE CALLBACK OBJECTS
7673 ///////////////////////////////////////////////////////////////////////////
7674
7675
7676 var callback = {
7677         success : AjaxObject.handleSuccess,
7678         failure : AjaxObject.handleFailure,
7679         timeout : AjaxObject.timeout,
7680         scope   : AjaxObject
7681 };
7682 var callbackAccount = {
7683         success : AjaxObject.ieSaveSuccess,
7684         failure : AjaxObject.handleFailure,
7685         timeout : AjaxObject.timeout,
7686         scope   : AjaxObject
7687 };
7688 var callbackAccountDelete = {
7689         success : AjaxObject.ieDeleteSuccess,
7690         failure : AjaxObject.handleFailure,
7691         timeout : AjaxObject.timeout,
7692         scope   : AjaxObject
7693 };
7694 var callbackOutboundTest = {
7695         success : AjaxObject.ieSendSuccess,
7696         failure : AjaxObject.handleFailure,
7697         timeout : AjaxObject.timeout,
7698         scope   : AjaxObject
7699 };
7700
7701
7702
7703 var callbackTeamInfoForSettings = {
7704 success : function (o) {
7705         var data = YAHOO.lang.JSON.parse(o.responseText);
7706         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7707 },
7708 failure : AjaxObject.handleFailure,
7709 timeout : AjaxObject.timeout,
7710 scope   : AjaxObject
7711
7712 };
7713
7714 var callbackStatusForImport = {
7715 success : function (o) {
7716         SUGAR.hideMessageBox();
7717         if (o.responseText != "")  {
7718                 var statusString = "";
7719                 var data = YAHOO.lang.JSON.parse(o.responseText);
7720                 for(i=0; i<data.length; i++) {
7721                         statusString = statusString + data[i] + '<br/>';
7722                 }
7723                 SUGAR.showMessageBox(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7724         }
7725         SE.listView.refreshGrid();
7726
7727 },
7728 failure : AjaxObject.handleFailure,
7729 timeout : AjaxObject.timeout,
7730 scope   : AjaxObject
7731
7732 };
7733 var callbackComposeCache = {
7734         success : AjaxObject.composeCache,
7735         failure : AjaxObject.handleFailure,
7736         timeout : AjaxObject.timeout,
7737         scope   : AjaxObject
7738 };
7739 var callbackDelete = {
7740         success : AjaxObject.handleDeleteReturn,
7741         failure : AjaxObject.handleFailure,
7742         timeout : AjaxObject.timeout,
7743         scope   : AjaxObject
7744 };
7745 var callbackEmailDetailMultiple = {
7746         success : function(o) {
7747                 SUGAR.hideMessageBox();
7748         var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7749                 var ret = new Object();
7750
7751                 for(var i=0; i<retMulti.length; i++) {
7752                         ret = retMulti[i];
7753
7754                         SUGAR.email2._setDetailCache(ret);
7755                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7756                 }
7757         },
7758         failure : AjaxObject.handleFailure,
7759         timeout : 0,
7760         scope   : AjaxObject
7761 };
7762 var callbackListViewSortOrderChange = {
7763         success : AjaxObject.saveListViewSortOrderPart2,
7764         failure : AjaxObject.handleFailure,
7765         timeout : AjaxObject.timeout,
7766         scope   : AjaxObject,
7767         argument        : [ieId, ieName, focusFolder]
7768 };
7769 var callbackEmptyTrash = {
7770         success : function(o) {
7771                 SUGAR.hideMessageBox();
7772                 AjaxObject.folderRenameCleanup;
7773         },
7774         failure : AjaxObject.handleFailure,
7775         timeout : AjaxObject.timeout,
7776         scope   : AjaxObject
7777 };
7778 var callbackClearCacheFiles = {
7779         success : function(o) {
7780                 SUGAR.hideMessageBox();
7781         },
7782         failure : AjaxObject.handleFailure,
7783         timeout : AjaxObject.timeout,
7784         scope   : AjaxObject
7785 };
7786 var callbackFolderRename = {
7787         success : function(o) {SUGAR.hideMessageBox();SUGAR.email2.folders.rebuildFolders();},
7788         failure : AjaxObject.handleFailure,
7789         timeout : AjaxObject.timeout,
7790         scope   : AjaxObject
7791 };
7792 var callbackFolderDelete = {
7793         success : function(o) {
7794                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7795                 if (ret.status) {
7796                     if (ret.folder_id) {
7797                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7798                         if(node)
7799                                 SUGAR.email2.tree.removeNode(node, true);
7800                     } else if (ret.ieId && ret.mbox) {
7801                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7802                         if(node)
7803                                 SUGAR.email2.tree.removeNode(node, true);
7804                     }
7805                         SUGAR.hideMessageBox();
7806                         //SUGAR.email2.folders.loadSettingFolder();
7807                 } else {
7808                         SUGAR.hideMessageBox();
7809                         SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7810                 } // else
7811         },
7812         failure : AjaxObject.handleFailure,
7813         timeout : AjaxObject.timeout,
7814         scope   : AjaxObject
7815 };
7816 var callbackFolderSave = {
7817         success : function(o) {
7818                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7819
7820                 switch(ret.action) {
7821                         case 'newFolderSave':
7822                                 SUGAR.email2.folders.rebuildFolders();
7823                         break;
7824                 }
7825         },
7826         failure : AjaxObject.handleFailure,
7827         timeout : AjaxObject.timeout,
7828         scope   : AjaxObject
7829 };
7830 var callbackFolderSubscriptions = {
7831         success : AjaxObject.updateFolderSubscriptions,
7832         failure : AjaxObject.handleFailure,
7833         timeout : AjaxObject.timeout,
7834         scope   : AjaxObject
7835 };
7836 var callbackFolderUpdate = {
7837         success : AjaxObject.updateFrameFolder,
7838         failure : AjaxObject.handleFailure,
7839         timeout : AjaxObject.timeout,
7840         scope   : AjaxObject
7841 };
7842 var callbackFolders = {
7843         success : AjaxObject.folders.rebuildFolders,
7844         //success : void(true),
7845         failure : AjaxObject.handleFailure,
7846         timeout : AjaxObject.timeout,
7847         scope   : AjaxObject
7848 };
7849 var callbackFullSync = {
7850         success : AjaxObject.fullSyncCleanup,
7851         failure : AjaxObject.handleFailure,
7852         timeout : 9999999999999,
7853         scope   : AjaxObject
7854 };
7855 var callbackGeneric = {
7856         success : function() {
7857                 SUGAR.hideMessageBox();
7858         },
7859         failure : AjaxObject.handleFailure,
7860         timeout : AjaxObject.timeout,
7861         scope   : AjaxObject
7862 };
7863 var callbackIeAccountRetrieve = {
7864         success : function(o) {
7865                 // return JSON encoding
7866                 SUGAR.hideMessageBox();
7867                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7868                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7869         },
7870         failure : AjaxObject.handleFailure,
7871         timeout : AjaxObject.timeout,
7872         scope   : AjaxObject
7873 };
7874 var callbackImportOneEmail = {
7875         success :  AjaxObject.detailView.showImportForm,
7876         failure : AjaxObject.handleFailure,
7877         timeout : AjaxObject.timeout,
7878         scope   : AjaxObject
7879 };
7880 var callbackRelateEmail = {
7881     success : AjaxObject.detailView.showRelateForm,
7882     failure : AjaxObject.handleFailure,
7883     timeout : AjaxObject.timeout,
7884     scope   : AjaxObject
7885 }
7886 var callbackEmailDetailView = {
7887     success : AjaxObject.detailView.showEmailDetailView,
7888     failure : AjaxObject.handleFailure,
7889     timeout : AjaxObject.timeout,
7890     scope   : AjaxObject
7891 }
7892 var callbackAssignmentDialog = {
7893         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7894         failure : AjaxObject.handleFailure,
7895         timeout : AjaxObject.timeout,
7896         scope   : AjaxObject
7897 };
7898 var callbackAssignmentAction = {
7899         success :  function(o) {
7900                 SE.listView.refreshGrid();
7901                 SUGAR.hideMessageBox();
7902                 if(o.responseText != '') {
7903                SUGAR.showMessageBox('Assignment action result', o.responseText, 'alert');
7904             } // if
7905         } ,
7906         failure : AjaxObject.handleFailure,
7907         timeout : AjaxObject.timeout,
7908         scope   : AjaxObject
7909 };
7910 var callbackMoveEmails = {
7911         success :  function(o) {
7912             SE.listView.refreshGrid();
7913                 SUGAR.hideMessageBox();
7914                 if(o.responseText != '') {
7915                SUGAR.showMessageBox(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7916             } // if
7917         } ,
7918         failure : AjaxObject.handleFailure,
7919         timeout : AjaxObject.timeout,
7920         scope   : AjaxObject
7921 };
7922 var callbackLoadAttachments = {
7923         success : AjaxObject.loadAttachments,
7924         failure : AjaxObject.handleFailure,
7925         timeout : AjaxObject.timeout,
7926         scope   : AjaxObject
7927 };
7928 var callbackLoadRules = {
7929         success : AjaxObject.rules.loadRulesForSettings,
7930         failure : AjaxObject.handleFailure,
7931         timeout : AjaxObject.timeout,
7932         scope   : AjaxObject
7933 };
7934 var callbackLoadSignature = {
7935         success : AjaxObject.loadSignature,
7936         failure : AjaxObject.handleFailure,
7937         timeout : AjaxObject.timeout,
7938         scope   : AjaxObject
7939 };
7940 var callbackDeleteSignature = {
7941         success : AjaxObject.handleDeleteSignature,
7942         failure : AjaxObject.handleFailure,
7943         timeout : AjaxObject.timeout,
7944         scope   : AjaxObject
7945 };
7946 /*var callbackMoveEmails = {
7947     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7948     failure : AjaxObject.handleFailure,
7949     timeout : AjaxObject.timeout,
7950     scope   : AjaxObject
7951 }*/
7952 var callbackOutboundSave = {
7953         success : AjaxObject.accounts.saveOutboundCleanup,
7954         failure : AjaxObject.handleFailure,
7955         timeout : AjaxObject.timeout,
7956         scope   : AjaxObject
7957 };
7958 var callbackDefaultOutboundSave = {
7959         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7960         failure : AjaxObject.handleFailure,
7961         timeout : AjaxObject.timeout,
7962         scope   : AjaxObject
7963 };
7964 var callbackQuickCreate = {
7965         success : AjaxObject.detailView.showQuickCreateForm,
7966         failure : AjaxObject.handleFailure,
7967         timeout : AjaxObject.timeout,
7968         scope   : AjaxObject
7969 };
7970 var callbackQuickCreateSave = {
7971         success : AjaxObject.detailView.saveQuickCreateForm,
7972         failure : AjaxObject.handleFailure,
7973         timeout : AjaxObject.timeout,
7974         scope   : AjaxObject
7975 };
7976 var callbackQuickCreateSaveAndAddToAddressBook = {
7977         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7978         failure : AjaxObject.handleFailure,
7979         timeout : AjaxObject.timeout,
7980         scope   : AjaxObject
7981 };
7982 var callbackQuickCreateSaveAndReply = {
7983     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7984     failure : AjaxObject.handleFailure,
7985     timeout : AjaxObject.timeout,
7986     scope   : AjaxObject
7987 }
7988 var callbackQuickCreateSaveAndReplyCase = {
7989     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7990     failure : AjaxObject.handleFailure,
7991     timeout : AjaxObject.timeout,
7992     scope   : AjaxObject
7993 }
7994 var callbackRebuildShowAccountList = {
7995         success : AjaxObject.rebuildShowFolders,
7996         failure : AjaxObject.handleFailure,
7997         timeout : AjaxObject.timeout,
7998         scope   : AjaxObject
7999 };
8000
8001 var callbackRefreshSugarFolders = {
8002         success : function(o) {
8003                 var t = YAHOO.lang.JSON.parse(o.responseText);
8004                 SUGAR.email2.folders.setSugarFoldersEnd(t);
8005         },
8006         failure : AjaxObject.handleFailure,
8007         timeout : AjaxObject.timeout,
8008         scope   : AjaxObject
8009 };
8010 var callbackReplyForward = {
8011         success : AjaxObject.handleReplyForward,
8012         finish : function(a, retryCount) {
8013                 if (typeof(retryCount) == 'undefined') {
8014                         retryCount = 0;
8015                 } else {
8016                         retryCount++;
8017                 }
8018                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8019                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8020         try {
8021                         var html = t.getContent();
8022
8023             html = "&nbsp;<div><hr></div>" + a.description;
8024
8025                         t.setContent(html);//
8026
8027             if (a.type != 'draft') {
8028                 // Next step, attach signature
8029                 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8030             }
8031
8032                 } catch(e) {
8033                         if (retryCount < 5) {
8034                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8035                                 return;
8036                         }
8037                 }
8038                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8039                 if (tabArray != null && tabArray.length > 0) {
8040                         for (i = 0 ; i < tabArray.length ; i++) {
8041                                 var tabObject = tabArray[i];
8042                                 if (tabObject.get("id") == ("composeTab" + idx)) {
8043                                         var tabLabel = a.name;
8044                                 if (tabLabel != null && tabLabel.length > 25) {
8045                                         tabLabel = tabLabel.substring(0, 25) + "...";
8046                                 } // if
8047                                         tabObject.get("labelEl").firstChild.data = tabLabel;
8048                                         break;
8049                                 }
8050                         }
8051                 }
8052
8053                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8054                 if (a.parent_name != null && a.parent_name != "") {
8055                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
8056                 }
8057                 if (a.parent_type != null && a.parent_type != "") {
8058                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
8059                 }
8060                 if (a.parent_id != null && a.parent_id != "") {
8061                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
8062                 }
8063                 if (a.fromAccounts.status) {
8064                         var addressFrom = document.getElementById('addressFrom' + idx);
8065                 SUGAR.email2.util.emptySelectOptions(addressFrom);
8066                 var fromAccountOpts = a.fromAccounts.data;
8067                 for(i=0; i<fromAccountOpts.length; i++) {
8068                       var key = fromAccountOpts[i].value;
8069                       var display = fromAccountOpts[i].text;
8070                       var opt = new Option(display, key);
8071                       if (fromAccountOpts[i].selected) {
8072                         opt.selected = true;
8073                       }
8074                       addressFrom.options.add(opt);
8075                 }
8076                 } // if
8077                 SUGAR.hideMessageBox();
8078
8079         },
8080         failure : AjaxObject.handleFailure,
8081         timeout : AjaxObject.timeout,
8082         scope   : AjaxObject,
8083         argument        : [sendType]
8084 };
8085 var callbackSendEmail = {
8086         success : AjaxObject.sendEmailCleanUp,
8087         failure : AjaxObject.handleFailure,
8088         timeout : AjaxObject.timeout,
8089         scope   : AjaxObject
8090 };
8091 var callbackSettings = {
8092         success : AjaxObject.updateUserPrefs,
8093         failure : AjaxObject.handleFailure,
8094         timeout : AjaxObject.timeout,
8095         scope   : AjaxObject
8096 };
8097 var callbackSettingsFolderRefresh = {
8098         success : AjaxObject.settingsFolderRefresh,
8099         failure : AjaxObject.handleFailure,
8100         timeout : AjaxObject.timeout,
8101         scope   : AjaxObject
8102 };
8103 var callbackLoadSettingFolder = {
8104         success : function(o) {
8105                 AjaxObject.settingsFolderRefresh(o);
8106                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8107         },
8108         failure : AjaxObject.handleFailure,
8109         timeout : AjaxObject.timeout,
8110         scope   : AjaxObject
8111
8112 };
8113 var callbackUploadAttachment = {
8114         success : AjaxObject.uploadAttachmentSuccessful,
8115         upload  : AjaxObject.uploadAttachmentSuccessful,
8116         failure : AjaxObject.handleFailure,
8117         timeout : AjaxObject.timeout,
8118         scope   : AjaxObject
8119 };
8120 var callbackUserPrefs = {
8121         success : function(o) {
8122                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8123         },
8124         failure : AjaxObject.handleFailure,
8125         timeout : AjaxObject.timeout,
8126         scope   : AjaxObject
8127 };
8128
8129 var callbackContextmenus = {
8130         markUnread : {
8131                 success : AjaxObject.markEmailCleanup,
8132                 failure : AjaxObject.handleFailure,
8133                 timeout : AjaxObject.timeout,
8134                 scope   : AjaxObject
8135         }
8136 };
8137
8138 var callbackCheckEmail2 = {
8139         success : function(o) {
8140         var ret = YAHOO.lang.JSON.parse(o.responseText);
8141                 SUGAR.showMessageBox(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8142
8143
8144         },
8145         failure : AjaxObject.handleFailure,
8146         timeout : AjaxObject.timeout,
8147         scope   : AjaxObject
8148 }// End of File modules/Emails/javascript/ajax.js
8149                                 
8150 /*********************************************************************************
8151  * SugarCRM Community Edition is a customer relationship management program developed by
8152  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8153  * 
8154  * This program is free software; you can redistribute it and/or modify it under
8155  * the terms of the GNU Affero General Public License version 3 as published by the
8156  * Free Software Foundation with the addition of the following permission added
8157  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8158  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8159  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8160  * 
8161  * This program is distributed in the hope that it will be useful, but WITHOUT
8162  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8163  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8164  * details.
8165  * 
8166  * You should have received a copy of the GNU Affero General Public License along with
8167  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8168  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8169  * 02110-1301 USA.
8170  * 
8171  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8172  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8173  * 
8174  * The interactive user interfaces in modified source and object code versions
8175  * of this program must display Appropriate Legal Notices, as required under
8176  * Section 5 of the GNU Affero General Public License version 3.
8177  * 
8178  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8179  * these Appropriate Legal Notices must retain the display of the "Powered by
8180  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8181  * technical reasons, the Appropriate Legal Notices must display the words
8182  * "Powered by SugarCRM".
8183  ********************************************************************************/
8184
8185 function gridInit() {
8186         if(SUGAR.email2.grid) {
8187                 SUGAR.email2.grid.destroy();
8188         }
8189         
8190         e2Grid = {
8191                 init : function() {
8192                 
8193                         var Ck = YAHOO.util.Cookie;
8194                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8195
8196                         if (Ck.get("EmailGridWidths")) {
8197                                 for (var i=0; i < widths.length; i++) {
8198                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8199                                 }
8200                         } else {
8201                                 for (var i=0; i < widths.length; i++) {
8202                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8203                                 }
8204                         }
8205                         
8206                         // changes "F" to an icon
8207                         function flaggedIcon(cell, record, column, value) {
8208                                 if(value != "") {
8209                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8210                                 }
8211                         }
8212                         // changes "A" to replied icon
8213                         function repliedIcon(cell, record, column, value) {
8214                                 if(value != "") {
8215                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8216                                 }
8217                         }
8218                 function attachIcon(cell, record, column, value) {
8219                                 if(value == "1") {
8220                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8221                                 }
8222                         }
8223
8224                         var colModel = 
8225                                 [
8226                                         {
8227                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8228                                                 width: 10, 
8229                                                 sortable: false, 
8230                                                 fixed: true,
8231                                                 resizeable: true,
8232                                                 formatter: attachIcon,
8233                                                 key: 'hasAttach'
8234                                         }, 
8235                                     {
8236                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8237                                                 width: widths[0], 
8238                                                 sortable: true, 
8239                                                 fixed: true,
8240                                                 resizeable: true,
8241                                                 formatter: flaggedIcon,
8242                                                 key: 'flagged'
8243                                         }, 
8244                                         {
8245                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8246                                                 width: widths[1], 
8247                                                 sortable: true, 
8248                                                 fixed: true,
8249                                                 resizeable: true,
8250                                                 formatter: repliedIcon,
8251                                                 key: 'status'
8252                                         },
8253                                         {
8254                                                 label: app_strings.LBL_EMAIL_FROM, 
8255                                                 width: widths[2],
8256                                                 sortable: true,
8257                                                 resizeable: true,
8258                                                 key: 'from'
8259                                         }, 
8260                                         {
8261                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8262                                                 width: widths[3], 
8263                                                 sortable: true,
8264                                                 resizeable: true,
8265                                                 key: 'subject'
8266                                         }, 
8267                                         {
8268                                                 label: mod_strings.LBL_LIST_DATE,
8269                                                 width: widths[4], 
8270                                                 sortable: true,
8271                                                 resizeable: true,
8272                         key: 'date'
8273                                         }, 
8274                                         {
8275                                                 label: app_strings.LBL_EMAIL_TO,
8276                                                 width: widths[5], 
8277                                                 sortable: false,
8278                                                 resizeable: true,
8279                         key: 'to_addrs'
8280                                         }, 
8281                                         {
8282                                                 label: 'uid',
8283                                                 hidden: true,
8284                         key: 'uid'
8285                                         }, 
8286                                         {
8287                                                 label: 'mbox',
8288                                                 hidden: true,
8289                         key: 'mbox'
8290                                         }, 
8291                                         {
8292                                                 label: 'ieId',
8293                                                 hidden: true,
8294                         key: 'ieId'
8295                                         }, 
8296                                         {       
8297                                                 label: 'site_url',
8298                                                 hidden: true,
8299                         key: 'site_url'
8300                                         },
8301                                         {       label: 'seen',
8302                                                 hidden: true,
8303                         key: 'seen'
8304                                         },
8305                                         {       label: 'type',
8306                                                 hidden: true,
8307                         key: 'type'
8308                                         }
8309                                 ];
8310                         
8311                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8312                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8313                                 responseSchema: {
8314                                     resultsList: 'Email',
8315                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8316                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8317                                 }
8318                     });
8319                         var params = {
8320                                         to_pdf : "true",
8321                                         module : "Emails",
8322                                         action : "EmailUIAjax",
8323                                         emailUIAction : "getMessageList",
8324                                         mbox : "INBOX",
8325                                         ieId : "",
8326                                         forceRefresh : "false"
8327                         };
8328                         if(lazyLoadFolder != null) {
8329                                 params['mbox'] = lazyLoadFolder.folder;
8330                                 params['ieId'] = lazyLoadFolder.ieId;
8331                                 //Check if the folder is a Sugar Folder
8332                                 var test = new String(lazyLoadFolder.folder);
8333                                 if(test.match(/SUGAR\./)) {
8334                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8335                                         params['mbox'] = test.substr(6);
8336                                 }
8337                         }
8338                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8339         
8340                         // create the Grid
8341                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8342                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8343                                 dynamicData: true,
8344                                 paginator: new YAHOO.widget.Paginator({ 
8345                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8346                                         containers : ["dt-pag-nav"],
8347                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8348                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8349                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8350                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8351                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8352                                 }),
8353                                 initialRequest:SUGAR.util.paramsToUrl(params),
8354                                 width:  "800px",
8355                                 height: "400px"
8356                         });
8357
8358                         initRowDD();
8359
8360                         //Override Paging request construction
8361                         grid.set("generateRequest", function(oState, oSelf) {
8362                     oState = oState || {pagination:null, sortedBy:null};
8363                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8364                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8365                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8366                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8367                     // Build the request 
8368                     var ret = 
8369                             SUGAR.util.paramsToUrl(oSelf.params) + 
8370                             "&sort=" + sort +
8371                         "&dir=" + dir +
8372                         "&start=" + startIndex +
8373                         ((results !== null) ? "&limit=" + results : "");
8374                     return  ret;
8375                 });
8376                         
8377                         
8378                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8379                                 oPayload = oPayload || { };
8380                                 
8381                                 oPayload.totalRecords = oResponse.meta.total;
8382                                 oPayload.unreadRecords = oResponse.meta.unread;
8383                                 
8384                         var tabObject = SE.innerLayout.get("tabs")[0];
8385                         var mboxTitle = "";
8386                         if (this.params.mbox != null) {
8387                                 mboxTitle = this.params.mbox;
8388                         }
8389                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8390                         tabObject.get("labelEl").firstChild.data = tabtext;
8391                         
8392                         if (SE.tree) {
8393                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8394                                 if (node) {
8395                                         node.data.unseen = oResponse.meta.unread;
8396                                         SE.accounts.renderTree();
8397                                 }
8398                         }
8399                                 return oPayload; 
8400                         }
8401                         
8402                         var resize = grid.resizeGrid = function () {
8403                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8404                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8405                         }
8406                         grid.convertDDRows = function() {
8407                                 var rowEl = this.getFirstTrEl();
8408                                 while (rowEl != null) {
8409                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8410                                         rowEl = this.getNextTrEl(rowEl);
8411                                 }
8412                         }
8413                         
8414                         
8415                         grid.on("columnResizeEvent", function(o) {
8416                                 //Find the index of the column
8417                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8418                                 for (var i=0; i < colSet.length; i++) {
8419                                         if (o.column == colSet[i]) {
8420                                                 //Store it in the cookie
8421                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8422                                         }
8423                                 }
8424                                 //this.resizeGrid();
8425                         }, null, grid); 
8426                         
8427                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8428                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8429                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8430                         grid.render();
8431                         SUGAR.email2.listViewLayout.on("render", resize);
8432                         resize();
8433                         
8434                         //Setup the default load parameters
8435                         SUGAR.email2.grid.params = params;
8436                         
8437                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8438                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8439                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8440                 }
8441         };
8442         e2Grid.init();
8443 };
8444
8445
8446 function initRowDD() {
8447         var sg = SUGAR.email2.grid,
8448         Dom = YAHOO.util.Dom;
8449         sg.DDRow = function(oDataTable, oRecord, elTr) {
8450                 if(oDataTable && oRecord && elTr) {
8451                         this.ddtable = oDataTable;
8452                 this.table = oDataTable.getTableEl();
8453                 this.row = oRecord;
8454                 this.rowEl = elTr;
8455                 this.newIndex = null;
8456                 this.init(elTr);
8457                 this.initFrame(); // Needed for DDProxy
8458                 this.invalidHandleTypes = {};
8459             }   
8460         };
8461         
8462         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8463             _resizeProxy: function() {
8464                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8465                 var dragEl = this.getDragEl(),
8466                     el = this.getEl();
8467                 var xy = Dom.getXY(el);
8468                 
8469                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8470                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8471                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8472                 Dom.setStyle(dragEl, 'display', "");
8473             },
8474             
8475             startDrag: function(x, y) { 
8476                 //Check if we should be dragging a set of rows rather than just the one.
8477                 var selectedRows = this.ddtable.getSelectedRows();
8478                 var iSelected = false;
8479                 for (var i in selectedRows) {
8480                         if (this.rowEl.id == selectedRows[i]) {
8481                                 iSelected = true;
8482                                 break
8483                         }
8484                 }
8485                 if (iSelected) {
8486                         this.rows = [];
8487                         for (var i in selectedRows) {
8488                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8489                         }
8490                 } else {
8491                         this.rows = [this.row];
8492                         this.ddtable.unselectAllRows();
8493                         this.ddtable.selectRow(this.row);
8494                 }
8495                 
8496                 //Initialize the dragable proxy
8497                 var dragEl = this.getDragEl(); 
8498                 var clickEl = this.getEl(); 
8499                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8500                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8501                 Dom.addClass(dragEl, "yui-dt-liner");
8502                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8503                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8504                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8505                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8506             },
8507             
8508             clickValidator: function(e) {
8509                 if (this.row.getData()[0] == " ")
8510                         return false;
8511                 var target = YAHOO.util.Event.getTarget(e);
8512                 return ( this.isValidHandleChild(target) && 
8513                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8514             },
8515             /**
8516              * This funciton checks that the target of the drag is a table row in this
8517              * DDGroup and simply moves the sourceEL to that location as a preview.
8518              */
8519             onDragOver: function(ev, id) {
8520                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8521                 if (node && node != this.targetNode) {
8522                         this.targetNode = node;
8523                         SUGAR.email2.folders.unhighliteAll();
8524                         node.highlight();
8525                 }
8526             },
8527             
8528             onDragOut: function(e, id) {
8529                 if (this.targetNode) {
8530                         SUGAR.email2.folders.unhighliteAll();
8531                         this.targetNode = false;
8532                 }
8533             },
8534             endDrag: function() {
8535                 Dom.setStyle(this.getEl(), "opacity", "");
8536                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8537                 if (this.targetNode) {
8538                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8539                 }
8540                 SUGAR.email2.folders.unhighliteAll();
8541                 this.rows = null;
8542             }
8543         });
8544 }
8545
8546 function AddressSearchGridInit() {
8547     function moduleIcon(elCell, oRecord, oColumn, oData) {
8548         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8549     };
8550     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8551         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8552     };
8553     var checkHeader = '<input type="checkbox" ';
8554     if (SUGAR.email2.util.isIe()) {
8555         checkHeader += 'style="top:-5px" ';
8556     }
8557     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8558     var colModel = 
8559             [{
8560                 label: checkHeader,
8561             width: 30,
8562             formatter: selectionCheckBox,
8563             key: 'bean_id'
8564         },
8565             {
8566                 label: mod_strings.LBL_LIST_TYPE,
8567                 width: 25,
8568                 formatter: moduleIcon,
8569                 key: 'bean_module'
8570         },
8571             {
8572                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8573                 width: 180,
8574                 sortable: true,
8575                 key: 'name'
8576             }, 
8577             {
8578                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8579                 width: 300, 
8580                 sortable: true,
8581                 key: 'email'
8582             }];
8583     
8584     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8585                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8586         responseSchema: {
8587             resultsList: 'Person',
8588             fields: ['name', 'email', 'bean_id', 'bean_module'],
8589                     metaFields: {total: 'TotalCount'}
8590         },
8591         //enable sorting on the server accross all data
8592         remoteSort: true
8593     });
8594     dataModel.params = {
8595                 to_pdf          : true,
8596                 module          : "Emails",
8597                 action          : "EmailUIAjax",
8598                 emailUIAction:"getAddressSearchResults"
8599     }
8600     var rb = document.getElementById('hasRelatedBean').checked;
8601         if (rb) {
8602                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8603                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8604                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8605                 dataModel.params['related_bean_id'] = relatedBeanId;
8606                 dataModel.params['related_bean_type'] = relatedBeanType;
8607                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8608         }
8609     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8610     
8611     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8612         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8613                 dynamicData: true,
8614                 paginator: new YAHOO.widget.Paginator({ 
8615                         rowsPerPage: 25,  
8616                         containers : ["dt-pag-nav-addressbook"],
8617                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8618                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8619                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8620                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8621                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8622                 }),
8623                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8624                 width:  "560px",
8625                 height: "250px"
8626     });
8627         //Override Paging request construction
8628         grid.set("generateRequest", function(oState, oSelf) {
8629         oState = oState || {pagination:null, sortedBy:null};
8630         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8631         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8632         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8633         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8634         // Build the request 
8635         var ret = 
8636             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8637             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8638             ((results !== null) ? "&limit=" + results : "");
8639         return  ret;
8640     });
8641     
8642         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8643                 oPayload = oPayload || { };
8644                 oPayload.totalRecords = oResponse.meta.total;
8645                 return oPayload; 
8646         }
8647         
8648         grid.clickToggleSelect= function(args) {
8649                 var isIE = (args.event.target == null);
8650                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8651                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8652                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8653                 }
8654         }
8655         
8656         grid.reSelectRowsOnRender = function (){
8657             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8658         for (var i = 0; i < rows.length; i++) 
8659         {
8660                 var emailAddress = rows[i].getData("email");
8661             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8662             if(alreadyAdded)
8663             {
8664                 rows[i].setData("selected",  true);
8665                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8666             }
8667             else
8668             {
8669                 rows[i].setData("selected",  false);
8670                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8671             }
8672         }
8673         }
8674         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8675         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8676         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8677     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8678     
8679     grid.render();
8680     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8681     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8682     
8683     grid.toggleSelectCheckbox = function(id,checked){
8684         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8685         row.setData("checked",checked);
8686     };
8687     grid.toggleSelect = function(id, checked) {
8688         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8689         checked = row.getData("selected");
8690         if (!checked)
8691         {
8692             SUGAR.email2.addressBook.grid.selectRow(row);
8693             SE.addressBook.insertContactRowToResultTable(id,null)
8694         } else 
8695         {
8696             SUGAR.email2.addressBook.grid.unselectRow(row);
8697             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8698         }
8699         row.setData("selected", !checked);
8700     };
8701     
8702     grid.toggleSelectAll = function(checked) {
8703         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8704         for (var i = 0; i < rows.length; i++) {
8705                         if (typeof(rows[i]) != "undefined")
8706                                 rows[i].setData("checked",  checked);
8707         }
8708         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8709         for (var i = 0; i < checkBoxes.length; i++) {
8710             checkBoxes[i].checked = checked;
8711         }
8712     };
8713     
8714     //Initialize the grid result table.
8715     AddressSearchResultsGridInit();
8716 }
8717
8718
8719
8720 /**
8721 *  Initalize the results table for the address book selection.
8722 *
8723 */
8724 function AddressSearchResultsGridInit()
8725 {
8726     
8727     /* Full name sort funciton to compare by last name if available */
8728     var fullNameSort = function(a, b, desc) {
8729         // Deal with empty values
8730         if(!YAHOO.lang.isValue(a))
8731             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8732         else if(!YAHOO.lang.isValue(b))
8733             return -1;
8734
8735         var aNames = a.getData("name").split(' ');
8736         var bNames = b.getData("name").split(' ');
8737
8738         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8739         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8740
8741         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8742
8743     };
8744     
8745     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8746                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8747                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8748               
8749     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})},
8750                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8751      
8752      var myDataSource = new YAHOO.util.DataSource([]); 
8753          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8754          myDataSource.responseSchema = { 
8755                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8756                 };                                                                 
8757     
8758          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8759                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8760     
8761      var highlightEditableCell = function(oArgs) {
8762             var elCell = oArgs.target;
8763             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8764                 this.highlightCell(elCell);
8765             }
8766         };
8767       
8768      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8769      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8770      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8771      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8772          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8773      
8774      //Setup the context menus
8775      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8776              var task = p_aArgs[1]; 
8777              if(task) 
8778              { 
8779                  var elRow = this.contextEventTarget; 
8780                  elRow = p_myDataTable.getTrEl(elRow); 
8781          
8782                  if(elRow) 
8783                  { 
8784                      switch(task.index) 
8785                      { 
8786                          case 0:     
8787                              var oRecord = p_myDataTable.getRecord(elRow); 
8788                              p_myDataTable.deleteRow(elRow);  
8789                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8790                      } 
8791                  } 
8792              } 
8793          };
8794      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8795                         {trigger:gridResults.getTbodyEl()}); 
8796          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8797          contextMenu.render("addrSearchResultGrid"); 
8798          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8799 }
8800 // End of File modules/Emails/javascript/grid.js
8801                                 
8802 /*********************************************************************************
8803  * SugarCRM Community Edition is a customer relationship management program developed by
8804  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8805  * 
8806  * This program is free software; you can redistribute it and/or modify it under
8807  * the terms of the GNU Affero General Public License version 3 as published by the
8808  * Free Software Foundation with the addition of the following permission added
8809  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8810  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8811  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8812  * 
8813  * This program is distributed in the hope that it will be useful, but WITHOUT
8814  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8815  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8816  * details.
8817  * 
8818  * You should have received a copy of the GNU Affero General Public License along with
8819  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8820  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8821  * 02110-1301 USA.
8822  * 
8823  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8824  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8825  * 
8826  * The interactive user interfaces in modified source and object code versions
8827  * of this program must display Appropriate Legal Notices, as required under
8828  * Section 5 of the GNU Affero General Public License version 3.
8829  * 
8830  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8831  * these Appropriate Legal Notices must retain the display of the "Powered by
8832  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8833  * technical reasons, the Appropriate Legal Notices must display the words
8834  * "Powered by SugarCRM".
8835  ********************************************************************************/
8836
8837
8838 /******************************************************************************
8839  * Initialize Email 2.0 Application
8840  */
8841
8842 //Override Sugar Languge so quick creates work properly
8843
8844
8845 function email2init() {
8846
8847         //Init Tiny MCE
8848     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8849     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8850     if (!SUGAR.util.isTouchScreen()) {
8851          tinyMCE.init({
8852                  convert_urls : false,
8853          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8854          width: tinyConfig.width,
8855          theme: tinyConfig.theme,
8856          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8857          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8858          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8859          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8860          plugins : tinyConfig.plugins,
8861          elements : tinyConfig.elements,
8862          language : tinyConfig.language,
8863          extended_valid_elements : tinyConfig.extended_valid_elements,
8864          mode: tinyConfig.mode,
8865          strict_loading_mode : true,
8866                  force_br_newlines : true,
8867          forced_root_block : '',
8868          directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8869      });
8870     }
8871
8872     // initialze message overlay
8873     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8874             //iframe        : true,
8875             modal       : false,
8876             autoTabs    : true,
8877             width       : 300,
8878             height      : 120,
8879             shadow      : true
8880         }
8881     );
8882         // Hide Sugar menu
8883         if (SUGAR.themes.tempHideLeftCol)
8884         SUGAR.themes.tempHideLeftCol();
8885
8886         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8887 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8888
8889         // set defaults for YAHOO.util.DragDropManager
8890         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8891
8892         SUGAR.email2.nextYear = new Date();
8893         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8894
8895         
8896     // initialize and display UI framework (complexLayout.js)
8897     complexLayoutInit();
8898     
8899     // initialize and display grid (grid.js)
8900     gridInit();
8901     
8902     // initialize treeview for folders
8903         //onloadTreeinit();
8904         SUGAR.email2.folders.rebuildFolders(true);
8905         
8906         
8907     //Setup the Message Box overlay
8908     /*Ext.MessageBox.maxWidth = 350;
8909     Ext.MessageBox.minProgressWidth = 350;
8910
8911         ///////////////////////////////////////////////////////////////////////////
8912         ////    CONTEXT MENUS
8913         // detailView array
8914         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8915 */
8916         var SEC = SUGAR.email2.contextMenus; 
8917         
8918         //Grid menu
8919         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8920                 trigger: SUGAR.email2.grid.get("element"),
8921                 lazyload: true
8922         });
8923         emailMenu.subscribe("beforeShow", function() {
8924                 var oTarget = this.contextEventTarget;
8925                 if (typeof(oTarget) == "undefined")
8926                   return;
8927                 var grid = SUGAR.email2.grid;
8928                 var selectedRows = grid.getSelectedRows();
8929                 var multipleSelected = (selectedRows.length > 1) ? true: false;
8930                 if (!multipleSelected)
8931                 {
8932                         grid.unselectAllRows();
8933                         grid.selectRow(oTarget);
8934                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
8935                 }
8936                 else if(multipleSelected)
8937                 {
8938                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8939                 }
8940         });
8941         
8942         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8943         //us to access individual elements easier by name rather than by index
8944         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
8945                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8946         emailMenu.addItems([
8947         {
8948             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8949             id: 'showDetailView',
8950             onclick: { fn: SEC.showDetailView }
8951         },
8952         {
8953             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8954             onclick: { fn: SEC.openMultiple }
8955         },
8956         {
8957             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8958             onclick: { fn: SEC.archiveToSugar }
8959         },
8960         {
8961             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8962             id: 'reply',
8963             onclick: { fn: SEC.replyForwardEmailContext }
8964         },
8965         {
8966             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8967             id: 'replyAll',
8968             onclick: { fn: SEC.replyForwardEmailContext }
8969         },
8970         {
8971             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8972             id: 'forward',
8973             onclick: { fn: SEC.replyForwardEmailContext }
8974         },
8975         {
8976             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8977             id: 'delete',
8978             onclick: { fn: SEC.markDeleted }
8979         },
8980         {
8981             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8982             id: 'print',
8983             onclick: { fn: SEC.viewPrintable }
8984         },                
8985         // Mark... submenu
8986         {
8987             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8988             submenu: {
8989                         id: "markEmailMenu",
8990                 itemdata : [
8991                     {
8992                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
8993                         onclick: { fn: SEC.markUnread }
8994                     },
8995                     {
8996                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
8997                         onclick: { fn: SEC.markRead }
8998                     },
8999                     {
9000                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9001                         onclick: { fn: SEC.markFlagged }
9002                     },
9003                     {
9004                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9005                         onclick: {  fn: SEC.markUnflagged }
9006                     }
9007                 ]
9008             }
9009          },
9010         {
9011             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9012                 id: 'assignTo',
9013                 onclick: { fn: SEC.assignEmailsTo }
9014          },
9015          {
9016             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9017             id: 'relateTo',
9018             onclick: { fn: SEC.relateTo }
9019          }
9020     ]);
9021         SEC.emailListContextMenu.render();
9022         
9023         //Handle the Tree folder menu trigger ourselves
9024         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9025
9026         
9027         //Folder Menu
9028     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9029                 trigger: "",
9030                 lazyload: true 
9031         });
9032     SEC.frameFoldersContextMenu.addItems([
9033                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9034                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9035                         onclick: {  fn: function() {
9036                         var node = SUGAR.email2.clickedFolderNode;
9037                         if (node.data.ieId) {
9038                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9039                     }}
9040                 },
9041                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
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, true)};
9047                     }}
9048                 },
9049                 {
9050                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9051                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9052                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9053                 },
9054                 {
9055                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9056                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9057                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9058                 },
9059                 {
9060                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9061                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9062                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9063                  },
9064                  {
9065                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9066                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9067                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9068                   },
9069                  {
9070                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9071                     onclick: {  fn: function() {
9072                         var node = SUGAR.email2.clickedFolderNode;
9073                         if (node.data.ieId) {
9074                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9075                     }}
9076                   } 
9077         ]);
9078     SEC.frameFoldersContextMenu.render();
9079     
9080     SEC.initContactsMenu = function() {
9081         // contacts
9082         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9083                 trigger: "contacts",
9084                 lazyload: true
9085         });
9086         SEC.contactsContextMenu.addItems([
9087                 {
9088                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9089                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9090                 },
9091                 {
9092                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9093                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9094                 }
9095         ]);
9096         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9097                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9098                 if (oTarget && !grid.isSelected(oTarget)) {
9099                         grid.unselectAllRows();
9100                         grid.selectRow(oTarget);
9101                 }
9102         });
9103         SEC.contactsContextMenu.render();
9104         }
9105         
9106         
9107         // set auto-check timer
9108         SUGAR.email2.folders.startCheckTimer();
9109         // check if we're coming from an email-link click
9110         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9111         
9112         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9113         
9114         //Init fix for YUI 2.7.0 datatable sort.
9115         SUGAR.email2.addressBook.initFixForDatatableSort();
9116 }
9117
9118 function createTreePanel(treeData, params) {
9119         var tree = new YAHOO.widget.TreeView(params.id);
9120         var root = tree.getRoot();
9121         
9122         //if (treeData.nodes && treeData[0].id == "Home")
9123         //      treeData = treeData[0];
9124         return tree;
9125 }
9126
9127 function addChildNodes(parentNode, parentData) {
9128         var Ck = YAHOO.util.Cookie;
9129         var nextyear = SUGAR.email2.nextYear;
9130         var nodes = parentData.nodes || parentData.children;
9131         for (i in nodes) {
9132                 if (typeof(nodes[i]) == 'object') {
9133                         if (nodes[i].data) {
9134                 // See comment about href below.
9135                                 // nodes[i].data.href = '#';
9136                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9137                                 node.action = nodes[i].data.action;
9138                         } else {
9139                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9140                                         addChildNodes(parentNode, nodes[i]);
9141                                         return;
9142                                 }
9143                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9144                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9145                                 if (nodes[i].cls) {
9146                                         nodes[i].className = nodes[i].cls;
9147                                 }
9148                 // Previously, span was added in the label so it was rendering in the tree.
9149                 // Default behavior is to wrap in span if no href property, and since this href
9150                 // doesn't do anything, remove it so that it will be wrapped in spans.
9151                 // nodes[i].href = "#";
9152                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9153                                 //Override YUI child node creation
9154                                 if (nodes[i].children) {
9155                                         nodes[i].nodes = nodes[i].children;
9156                                         nodes[i].children = [ ];
9157                                 }
9158                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9159                         }
9160                         
9161                         if (typeof(nodes[i].nodes) == 'object') {
9162                                 addChildNodes(node, nodes[i]);
9163                         }
9164                 }
9165         }
9166 }
9167
9168 /**
9169  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9170  */
9171 function email2treeinit(tree, treedata, treediv, params) {
9172         //ensure the tree data is not corrupt
9173         if (!treedata) {
9174            return;
9175         }
9176         if (SUGAR.email2.tree) {
9177                 SUGAR.email2.tree.destroy();
9178                 SUGAR.email2.tree = null;
9179         }
9180         
9181         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9182                 id: 'emailtree'
9183         });
9184         
9185         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9186         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9187         tree.subscribe("expandComplete", function(node){
9188                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9189                 for (var i in node.children) {
9190                         SE.accounts.setupDDTarget(node.children[i]);
9191                 }
9192         });
9193         tree.setCollapseAnim("TVSlideOut");
9194         tree.setExpandAnim("TVSlideIn");
9195         var root = tree.root;
9196         while (root.hasChildren()) {
9197                 var node = root.children[0];
9198                 node.destroy();
9199                 tree.removeNode(root.children[0], false);
9200         }
9201         addChildNodes(root, treedata);
9202         tree.render();
9203         SUGAR.email2.accounts.renderTree();
9204 }
9205
9206 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9207         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9208 };
9209
9210
9211 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9212     startDrag: function(x, y) {
9213                 var Dom = YAHOO.util.Dom;       
9214                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9215                 
9216                 this.dragId = "";
9217                 var dragEl = this.getDragEl();  
9218         var clickEl = this.getEl(); 
9219         Dom.setStyle(clickEl, "color", "#AAA");
9220         Dom.setStyle(clickEl, "opacity", "0.25"); 
9221         dragEl.innerHTML = clickEl.innerHTML; 
9222          
9223         Dom.addClass(dragEl, "ygtvcell");
9224         Dom.addClass(dragEl, "ygtvcontent");
9225         Dom.addClass(dragEl, "folderDragProxy");
9226         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9227         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9228         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9229         Dom.setStyle(dragEl, "opacity", "0.5"); 
9230             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9231     },
9232     
9233     onDragOver: function(ev, id) {
9234         var Dom = YAHOO.util.Dom;
9235         if (id != this.dragId)
9236         {
9237                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9238                 if(node.data.cls != "sugarFolder") {
9239                         SUGAR.email2.folders.unhighliteAll();
9240                         return;
9241                 }
9242                 this.dragId = id;
9243                 this.targetNode = node;
9244                 SUGAR.email2.folders.unhighliteAll();
9245                 node.highlight();
9246         }
9247     },
9248     
9249     onDragOut: function(e, id) {
9250         if (this.targetNode) {
9251                 SUGAR.email2.folders.unhighliteAll();
9252                 this.targetNode = false;
9253                 this.dragId = false;
9254         }
9255     },
9256     
9257     endDrag: function() { 
9258         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9259         if (this.targetNode) {
9260                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9261         }
9262     }
9263 });// End of File modules/Emails/javascript/init.js
9264                                 
9265 /*********************************************************************************
9266  * SugarCRM Community Edition is a customer relationship management program developed by
9267  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9268  * 
9269  * This program is free software; you can redistribute it and/or modify it under
9270  * the terms of the GNU Affero General Public License version 3 as published by the
9271  * Free Software Foundation with the addition of the following permission added
9272  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9273  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9274  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9275  * 
9276  * This program is distributed in the hope that it will be useful, but WITHOUT
9277  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9278  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9279  * details.
9280  * 
9281  * You should have received a copy of the GNU Affero General Public License along with
9282  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9283  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9284  * 02110-1301 USA.
9285  * 
9286  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9287  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9288  * 
9289  * The interactive user interfaces in modified source and object code versions
9290  * of this program must display Appropriate Legal Notices, as required under
9291  * Section 5 of the GNU Affero General Public License version 3.
9292  * 
9293  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9294  * these Appropriate Legal Notices must retain the display of the "Powered by
9295  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9296  * technical reasons, the Appropriate Legal Notices must display the words
9297  * "Powered by SugarCRM".
9298  ********************************************************************************/
9299
9300 /**
9301   Complex layout init
9302  */
9303 function complexLayoutInit() {
9304         var se = SUGAR.email2;
9305         var Dom = YAHOO.util.Dom;
9306         se.e2Layout = {
9307         getInnerLayout : function(rows) {
9308                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9309                 parent: se.complexLayout,  
9310                         border:true,
9311                     hideOnLayout: true,
9312                     height: 400,
9313                                 units: [{
9314                                         position: "center",
9315                                     scroll:false, // grid should autoScroll itself
9316                                     split:true,
9317                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9318                                 },{
9319                                         position: "bottom",
9320                                     scroll:true,
9321                                     collapse: false,
9322                                     resize: true,
9323                                     useShim:true,
9324                                     height:'250',
9325                                     body: "<div id='listBottom' />"
9326                                 },{
9327                                     position: "right",
9328                                     scroll:true,
9329                                     collapse: false,
9330                                     resize: true,
9331                                     useShim:true,
9332                                     width:'250',
9333                                     body: "<div id='listRight' />",
9334                                     titlebar: false //,header: "right"
9335                                 }]
9336             });
9337                 se.complexLayout.on("render", function(){
9338                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9339                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9340                                 SUGAR.email2.listViewLayout.set("height", height);
9341                                 SUGAR.email2.listViewLayout.render();
9342                 });
9343             se.listViewLayout.render();
9344             //CSS hack for now
9345             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9346             var rp = se.listViewLayout.resizePreview = function() {
9347                 var pre = Dom.get("displayEmailFramePreview");
9348                 if (pre) {
9349                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9350                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9351                 }
9352             };
9353             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9354             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9355             se.e2Layout.setPreviewPanel(rows);
9356             se.previewLayout = se.listViewLayout;
9357             return se.listViewLayout;
9358         },
9359         
9360         getInnerLayout2Rows : function() {
9361             return this.getInnerLayout(true);
9362         },
9363         getInnerLayout2Columns : function() {
9364             return this.getInnerLayout(false);
9365         },
9366         
9367         init : function(){
9368             // initialize state manager, we will use cookies
9369 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9370                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9371                 se.complexLayout = new YAHOO.widget.Layout("container", {
9372                         border:true,
9373                 hideOnLayout: true,
9374                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9375                 width: Dom.getViewportWidth() - 40,
9376                 units: [{
9377                         position: "center",
9378                     scroll:false,
9379                     body: "<div id='emailtabs'></div>"
9380                 },
9381                 {
9382                         position: "left",
9383                         scroll: true,
9384                         body: "<div id='lefttabs'></div>",
9385                     collapse: true,
9386                     width: 210,
9387                     minWidth: 100,
9388                     resize:true,
9389                     useShim:true,
9390                     titlebar: true,
9391                     header: "&nbsp;"
9392                 },
9393                 {
9394                     header: Dom.get('footerLinks').innerHTML,
9395                                         position: 'bottom',
9396                                         id: 'mbfooter',
9397                                         height: 22,
9398                                         border: false
9399                 }]
9400             });
9401                 se.complexLayout.render();
9402                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9403                         tp.addTab(new YAHOO.widget.Tab({ 
9404                                 label: "Inbox",
9405                                 scroll : true,
9406                                 content : "<div id='listViewDiv'/>",
9407                                 id : "center",
9408                                 active : true
9409                         }));
9410                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9411                         tp.appendTo(centerEl);
9412                         //CSS hack for now
9413                         tp.get("element").style.borderRight = "1px solid #666"
9414                         
9415                         var listV =  this.getInnerLayout2Rows();
9416                         listV.set("height", tp.get("element").clientHeight - 25);
9417                         listV.render();
9418             
9419             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9420             var folderTab = new YAHOO.widget.Tab({ 
9421                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9422                                 scroll : true,
9423                                 content : "<div id='emailtree'/>",
9424                                 id : "tree",
9425                                 active : true
9426                         });
9427             folderTab.on("activeChange", function(o){ 
9428                 if (o.newValue) {
9429                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9430                 }
9431             });
9432             se.leftTabs.addTab(folderTab);
9433             
9434             var tabContent = SUGAR.util.getAndRemove("searchTab");
9435             var searchTab = new YAHOO.widget.Tab({ 
9436                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9437                                 scroll : true,
9438                                 content : tabContent.innerHTML,
9439                                 id : tabContent.id
9440                         });
9441             searchTab.on("activeChange", function(o){ 
9442                 if (o.newValue) 
9443                 {
9444                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9445                    //Setup the calendars if needed
9446                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9447                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9448                    
9449                        //Initalize sqs object for assigned user name 
9450                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
9451                        
9452                        //Attach event handler for when the relate module option is selected for the correct sqs object
9453                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9454                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9455                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
9456                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9457                        
9458                        //If enter key is pressed, perform search
9459                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9460                        for(var i=0; i < addKeyPressFields.length;i++)
9461                        {
9462                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9463                                 if (e.keyCode == 13) {
9464                                         YAHOO.util.Event.stopEvent(e);
9465                                         SUGAR.email2.search.searchAdvanced();
9466                                 }
9467                        });
9468                        }
9469                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
9470                        enableQS(true);
9471                        //Clear parent values if selecting another parent type.
9472                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
9473                            function(){ 
9474                                document.getElementById('data_parent_id_search').value =''; 
9475                                document.getElementById('data_parent_name_search').value =''; 
9476                            });
9477                 
9478                 }
9479             });
9480             se.leftTabs.addTab(searchTab);
9481             
9482             var resizeTabBody = function() {
9483                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9484                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9485             }
9486             resizeTabBody();
9487             se.complexLayout.on("render", resizeTabBody);
9488             se.leftTabs.on("activeTabChange", resizeTabBody);
9489                         //hack to allow left pane scroll bar to fully show
9490                 var lefttabsDiv = document.getElementById('lefttabs');
9491                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9492                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9493                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9494           
9495         },
9496         initSQSObject: function(formName,fieldName)
9497         {
9498             var fullFieldName = formName + '_' + fieldName; //SQS Convention
9499             var resultName = fullFieldName + '_' + 'results';
9500             
9501             if (QSFieldsArray[fullFieldName] != null) 
9502             {
9503                 QSFieldsArray[fullFieldName].destroy();
9504                 delete QSFieldsArray[fullFieldName];
9505             }
9506             if (QSProcessedFieldsArray[fullFieldName])
9507             QSProcessedFieldsArray[fullFieldName] = false;
9508
9509             if( Dom.get(resultName) )
9510             {
9511                 var obj = document.getElementById(resultName);
9512                 obj.parentNode.removeChild(obj);
9513             }
9514         },
9515         setPreviewPanel: function(rows) {
9516                 if (rows) {
9517                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9518                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9519                 Dom.get("listRight").innerHTML = "";
9520                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9521             } else {
9522                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9523                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9524                 Dom.get("listBottom").innerHTML = "";
9525                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9526             }
9527         }
9528     };
9529         se.e2Layout.init();
9530 }
9531
9532 var myBufferedListenerObject = new Object();
9533 myBufferedListenerObject.refit = function() {
9534     if(SUGAR.email2.grid) {
9535         SUGAR.email2.grid.autoSize();
9536     }
9537 }
9538 // End of File modules/Emails/javascript/complexLayout.js
9539                                 
9540 /*********************************************************************************
9541  * SugarCRM Community Edition is a customer relationship management program developed by
9542  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9543  * 
9544  * This program is free software; you can redistribute it and/or modify it under
9545  * the terms of the GNU Affero General Public License version 3 as published by the
9546  * Free Software Foundation with the addition of the following permission added
9547  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9548  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9549  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9550  * 
9551  * This program is distributed in the hope that it will be useful, but WITHOUT
9552  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9553  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9554  * details.
9555  * 
9556  * You should have received a copy of the GNU Affero General Public License along with
9557  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9558  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9559  * 02110-1301 USA.
9560  * 
9561  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9562  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9563  * 
9564  * The interactive user interfaces in modified source and object code versions
9565  * of this program must display Appropriate Legal Notices, as required under
9566  * Section 5 of the GNU Affero General Public License version 3.
9567  * 
9568  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9569  * these Appropriate Legal Notices must retain the display of the "Powered by
9570  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9571  * technical reasons, the Appropriate Legal Notices must display the words
9572  * "Powered by SugarCRM".
9573  ********************************************************************************/
9574
9575 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9576 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9577 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9578 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9579 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9580 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9581 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9582 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9583 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9584 '               <input type="hidden" id="composeType" name="composeType">' +
9585 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9586 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9587 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9588 '               <input type="hidden" id="sendTo" name="sendTo">' +
9589 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9590 '               <input type="hidden" id="sendCc" name="sendCc">' +
9591 '               <input type="hidden" id="setEditor" name="setEditor">' +
9592 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9593 '               <input type="hidden" id="parent_id" name="parent_id">' +
9594 '               <input type="hidden" id="parent_type" name="parent_type">' +
9595 '               <input type="hidden" id="attachments" name="attachments">' +
9596 '               <input type="hidden" id="documents" name="documents">' +
9597 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9598 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9599 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9600 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9601 '                       <tr>' +
9602 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9603 '                                       <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>' +
9604 '                                       <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>' +
9605 '                                       <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>' +
9606 '                                       <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>' +
9607 '</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>' + 
9608 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9609 '<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>' +
9610 '                       </td></tr></tbody></table></th>'     +
9611 '                       </tr>' +
9612 '                       <tr>' +
9613 '                               <td>' +
9614 '                                       <div style="margin:5px;">' +
9615 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9616 '                                               <tr>' +
9617 '                                                       <td class="emailUILabel" NOWRAP >' +
9618 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9619 '                                                       </td>' +
9620 '                                                       <td class="emailUIField" NOWRAP>' +
9621 '                                                               <div>' +
9622 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9623 '                                                               </div>' +
9624 '                                                       </td>' +
9625 '                                               </tr>' +
9626 '                                               <tr>' +
9627 '                                                       <td class="emailUILabel" NOWRAP>' +
9628 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9629 '                                   {app_strings.LBL_EMAIL_TO}:' +
9630 '                               </button>' + 
9631 '                                                       </td>' +
9632 '                                                       <td class="emailUIField" NOWRAP>' +
9633 '                                                               <div class="ac_autocomplete">' +
9634 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9635 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9636 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9637 '                                                               </div>' +
9638 '                                                       </td>' +
9639 '                                               </tr>' +
9640 '                                               <tr id="add_addr_options_tr{idx}">' +
9641 '                                                       <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>'+
9642 '                                               </tr>'+
9643 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9644 '                                                       <td class="emailUILabel" NOWRAP>' +
9645 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9646 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9647 '                               </button>' + 
9648 '                                                       </td>' +
9649 '                                                       <td class="emailUIField" NOWRAP>' +
9650 '                                                               <div class="ac_autocomplete">' +
9651 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9652 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9653 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9654 '                                                               </div>' +
9655 '                                                       </td>' +
9656 '                                               </tr>' +
9657 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9658 '                                                       <td class="emailUILabel" NOWRAP>' +
9659 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9660 '                               {app_strings.LBL_EMAIL_BCC}:' +
9661 '                               </button>' + 
9662 '                                                       </td>' +
9663 '                                                       <td class="emailUIField" NOWRAP>' +
9664 '                                                               <div class="ac_autocomplete">' +
9665 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9666 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9667 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9668 '                                                               </div>' +
9669 '                                                       </td>' +
9670 '                                               </tr>' +
9671 '                                               <tr>' +
9672 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9673 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9674 '                                                       </td>' +
9675 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9676 '                                                               <div class="ac_autocomplete">' +
9677 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9678 '                                                               </div>' +
9679 '                                                       </td>' +
9680 '                                               </tr>' +
9681 '                                       </table>' +
9682 '                                       </div>' +
9683 '                               </td>'   +
9684 '                       </tr>' +
9685 '               </table>' +
9686 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9687 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9688 '                       <div style="padding:5px;">' +
9689 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9690 '                                       <tr>' +
9691 '                                               <th>' +
9692 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9693 '                                                       <br />' +
9694 '                                                       &nbsp;' +
9695 '                                               </th>' +
9696 '                                       </tr>' +
9697 '                                       <tr>' +
9698 '                                               <td>' +
9699 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9700 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9701 '                                               </td>' +
9702 '                                       </tr>' +
9703 '                                       <tr>' +
9704 '                                               <td>' +
9705 '                                                       &nbsp;' +
9706 '                                                       <br />' +
9707 '                                                       &nbsp;' +
9708 '                                               </td>' +
9709 '                                       </tr>' +
9710 '                                       <tr>' +
9711 '                                               <th>' +
9712 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9713 '                                                       <br />' +
9714 '                                                       &nbsp;' +
9715 '                                               </th>' +
9716 '                                       </tr>' +
9717 '                                       <tr>' +
9718 '                                               <td>' +
9719 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9720 '                                                       <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>' +
9721 '                                               </td>' +
9722 '                                       </tr>' +
9723 '                                       <tr>' +
9724 '                                               <td>' +
9725 '                                                       &nbsp;' +
9726 '                                                       <br />' +
9727 '                                                       &nbsp;' +
9728 '                                               </td>' +
9729 '                                       </tr>' +
9730 '                                       <tr>' +
9731 '                                               <th>' +
9732 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9733 '                                                       <br />' +
9734 '                                                       &nbsp;' +
9735 '                                               </th>' +
9736 '                                       </tr>' +
9737 '                                       <tr>' +
9738 '                                               <td>' +
9739 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9740 '                                               </td>' +
9741 '                                       </tr>' +
9742 '                               </table>' +
9743 '                       </div>' +
9744 '               </div>' +
9745 '       </form>' +
9746 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9747 '             <div style="padding:5px;">' +
9748 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9749 '                               <table border="0" width="100%">' +
9750 '                                       <tr>' +
9751 '                                               <td NOWRAP style="padding:2px;">' +
9752 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9753 '                                               </td>' +
9754 '                                       </tr>' +
9755 '                                       <tr>' +
9756 '                                               <td NOWRAP style="padding:2px;">' +
9757 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9758 '                                               </td>' +
9759 '                                       </tr>' +
9760 '                               </table>' +
9761 '                               <br />' +
9762 '                               <table border="0" width="100%">' +
9763 '                                       <tr>' +
9764 '                                               <td NOWRAP style="padding:2px;">' +
9765 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9766 '                                               </td>' +
9767 '                                       </tr>' +
9768 '                                       <tr>' +
9769 '                                               <td NOWRAP style="padding:2px;">' +
9770 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9771 '                                               </td>' +
9772 '                                       </tr>' +
9773 '                               </table>' +
9774 '                               <table border="0" width="100%">' +
9775 '                                       <tr>' +
9776 '                                               <td NOWRAP style="padding:2px;">' +
9777 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9778 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9779 '                                               </td>' +
9780 '                                       </tr>' +
9781 '                               </table>' +
9782 '         </form>' +
9783 '                       </div> ' +
9784 '               </div>' +
9785 '</div>';
9786 // End of File modules/Emails/javascript/composeEmailTemplate.js
9787                                 
9788 /*********************************************************************************
9789  * SugarCRM Community Edition is a customer relationship management program developed by
9790  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9791  * 
9792  * This program is free software; you can redistribute it and/or modify it under
9793  * the terms of the GNU Affero General Public License version 3 as published by the
9794  * Free Software Foundation with the addition of the following permission added
9795  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9796  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9797  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9798  * 
9799  * This program is distributed in the hope that it will be useful, but WITHOUT
9800  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9801  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9802  * details.
9803  * 
9804  * You should have received a copy of the GNU Affero General Public License along with
9805  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9806  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9807  * 02110-1301 USA.
9808  * 
9809  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9810  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9811  * 
9812  * The interactive user interfaces in modified source and object code versions
9813  * of this program must display Appropriate Legal Notices, as required under
9814  * Section 5 of the GNU Affero General Public License version 3.
9815  * 
9816  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9817  * these Appropriate Legal Notices must retain the display of the "Powered by
9818  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9819  * technical reasons, the Appropriate Legal Notices must display the words
9820  * "Powered by SugarCRM".
9821  ********************************************************************************/
9822
9823 SUGAR.email2.templates['displayOneEmail'] = 
9824 '<div class="emailDetailTable" style="height:100%">' +
9825 '<div id="viewMenuDiv{idx}"></div>' + 
9826 '<div width="100%" class="displayEmailValue">' +
9827 '                                       <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>' +
9828 '                                       <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>' +
9829 '                                       <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>' +
9830 '                                       <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>' +
9831 '                                       <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>' +
9832 '                                       <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>' +
9833 '                                       <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>' +
9834 '                                       <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>' +
9835 '                                       <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>' +
9836 '</div>' +
9837 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9838 '                               <tr>' +
9839 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9840 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9841 '                                       </td>' +
9842 '                                       <td width="99%" class="displayEmailValue">' +
9843 '                                               {email.from_addr}' +
9844 '                                       </td>' +
9845 '                               </tr>' +
9846 '                               <tr>' +
9847 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9848 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9849 '                                       </td>' +
9850 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9851 '                                               <b>{email.name}</b>' +
9852 '                                       </td>' +
9853 '                               </tr>' +
9854 '                               <tr>' +
9855 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9856 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9857 '                                       </td>' +
9858 '                                       <td class="displayEmailValue">' +
9859 '                                               {email.date_start} {email.time_start}' +
9860 '                                       </td>' +
9861 '                               </tr>' +
9862 '                               <tr>' +
9863 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9864 '                                               {app_strings.LBL_EMAIL_TO}:' +
9865 '                                       </td>' +
9866 '                                       <td class="displayEmailValue">' +
9867 '                                               {email.toaddrs}' +
9868 '                                       </td>' +
9869 '                               </tr>' +
9870 '                               <tr>{meta.cc}</tr>' +
9871 '                               <tr>{email.attachments}</tr>' +
9872 '                       </table>' +
9873 '                       <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>' +
9874 //'                           {email.description}' +
9875 '</div>'
9876 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9877                                 
9878 /*********************************************************************************
9879  * SugarCRM Community Edition is a customer relationship management program developed by
9880  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9881  * 
9882  * This program is free software; you can redistribute it and/or modify it under
9883  * the terms of the GNU Affero General Public License version 3 as published by the
9884  * Free Software Foundation with the addition of the following permission added
9885  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9886  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9887  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9888  * 
9889  * This program is distributed in the hope that it will be useful, but WITHOUT
9890  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9891  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9892  * details.
9893  * 
9894  * You should have received a copy of the GNU Affero General Public License along with
9895  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9896  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9897  * 02110-1301 USA.
9898  * 
9899  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9900  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9901  * 
9902  * The interactive user interfaces in modified source and object code versions
9903  * of this program must display Appropriate Legal Notices, as required under
9904  * Section 5 of the GNU Affero General Public License version 3.
9905  * 
9906  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9907  * these Appropriate Legal Notices must retain the display of the "Powered by
9908  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9909  * technical reasons, the Appropriate Legal Notices must display the words
9910  * "Powered by SugarCRM".
9911  ********************************************************************************/
9912
9913 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9914 '<body onload="javascript:window.print();">' + 
9915 '<style>' + 
9916 'body {' + 
9917 '       margin: 0px;' + 
9918 '       font-family: helvetica, impact, sans-serif;' +
9919 '       font-size : 12pt;' +
9920 '} ' +
9921 'table {' +
9922 '       padding:10px;' +
9923 '}' +
9924 '</style>' +
9925 '<div>' +
9926 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9927 '       <tr>' +
9928 '               <td>' +
9929 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9930 '                               <tr>' +
9931 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9932 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9933 '                                       </td>' +
9934 '                                       <td width="99%" class="displayEmailValue">' +
9935 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9936 '                                       </td>' +
9937 '                               </tr>' +
9938 '                               <tr>' +
9939 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9940 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9941 '                                       </td>' +
9942 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9943 '                                               <b>{email.name}</b>' +
9944 '                                       </td>' +
9945 '                               </tr>' +
9946 '                               <tr>' +
9947 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9948 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9949 '                                       </td>' +
9950 '                                       <td class="displayEmailValue">' +
9951 '                                               {email.date_start} {email.time_start}' +
9952 '                                       </td>' +
9953 '                               </tr>' +
9954 '                               <tr>' +
9955 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9956 '                                               {app_strings.LBL_EMAIL_TO}:' +
9957 '                                       </td>' +
9958 '                                       <td class="displayEmailValue">' +
9959 '                                               {email.toaddrs}' +
9960 '                                       </td>' +
9961 '                               </tr>' +
9962 '                               {email.cc}' +
9963 '                               {email.attachments}' +
9964 '                       </table>' +
9965 '               </td>' +
9966 '       </tr>' +
9967 '       <tr>' +
9968 '               <td>' +
9969 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9970 '                               <tr>' +
9971 '                                       <td style="border-top: 1px solid #333;">' +
9972 '                                               <div style="padding:5px;">' +
9973                                                         '{email.description}' +
9974 '                                               </div>' +
9975 '                                       </td>' +
9976 '                               </tr>' +
9977 '                       </table>' +
9978 '               </td>' +
9979 '       </tr>' +
9980 '</table>' +
9981 '</div>' +
9982 '</body></html>';
9983 // End of File modules/Emails/javascript/viewPrintable.js
9984                                 
9985 /*********************************************************************************
9986  * SugarCRM Community Edition is a customer relationship management program developed by
9987  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9988  *
9989  * This program is free software; you can redistribute it and/or modify it under
9990  * the terms of the GNU Affero General Public License version 3 as published by the
9991  * Free Software Foundation with the addition of the following permission added
9992  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9993  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9994  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9995  *
9996  * This program is distributed in the hope that it will be useful, but WITHOUT
9997  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9998  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9999  * details.
10000  *
10001  * You should have received a copy of the GNU Affero General Public License along with
10002  * this program; if not, see http://www.gnu.org/licenses or write to the Free
10003  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
10004  * 02110-1301 USA.
10005  *
10006  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
10007  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
10008  *
10009  * The interactive user interfaces in modified source and object code versions
10010  * of this program must display Appropriate Legal Notices, as required under
10011  * Section 5 of the GNU Affero General Public License version 3.
10012  *
10013  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
10014  * these Appropriate Legal Notices must retain the display of the "Powered by
10015  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
10016  * technical reasons, the Appropriate Legal Notices must display the words
10017  * "Powered by SugarCRM".
10018  ********************************************************************************/
10019 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10020 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;}
10021 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');}
10022 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;}}
10023 if(QSProcessedFieldsArray[qs_index_id]){skipSTR='collection_0';if(qs_index_id.lastIndexOf(skipSTR)!=(qs_index_id.length-skipSTR.length)){continue;}}
10024 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10025 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}
10026 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]]);}}}
10027 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]]);}}
10028 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10029 {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]])
10030 {document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value="";}}}};search.setFields=function(data,filter)
10031 {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])
10032 {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';}}}}
10033 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))
10034 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10035 {if(this.inputElement.id=='shipping_account_name')
10036 {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)/;}
10037 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10038 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10039 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];}}}
10040 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]];}
10041 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;}}}}});}
10042 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10043 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10044 // End of File include/javascript/quicksearch.js
10045