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