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