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