]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.2.3
[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);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(YAHOO.env.ua.ie){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};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         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5415
5416         // get attachments if any
5417         AjaxObject.target = '';
5418         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5419     },
5420
5421     appendEmailTemplateJSON : function() {
5422         var idx = SE.composeLayout.currentInstanceId; // post increment
5423
5424         // query based on template, contact_id0,related_to
5425         //jchi 09/10/2008 refix #7743
5426         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5427             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5428         }
5429
5430         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,'"');
5431
5432         // cn: bug 14361 - text-only templates don't fill compose screen
5433         if(text == '') {
5434             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/>");
5435         }
5436
5437         var tiny = SE.util.getTiny('htmleditor' + idx);
5438         var tinyHTML = tiny.getContent();
5439         var openTag = '<div><span><span>';
5440         var closeTag = '</span></span></div>';
5441         var htmllow = tinyHTML.toLowerCase();
5442         var start = htmllow.indexOf(openTag);
5443                 if (start > -1) {
5444                 var htmlPart2 = tinyHTML.substr(start);
5445                 tinyHTML = text + htmlPart2;
5446                 tiny.setContent(tinyHTML);
5447                 } else {
5448                 tiny.setContent(text);
5449                 }
5450     },
5451
5452     /**
5453      * Writes out the signature in the email editor
5454      */
5455     setSignature : function(idx) {
5456         if (!tinyMCE)
5457             return false;
5458         var hide = document.getElementById('setEditor' + idx).checked;
5459         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5460         //wait for signatures to load before trying to set them
5461         if (!SE.composeLayout.signatures) {
5462             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5463                         return;
5464         }
5465
5466         if(idx) {
5467             var sel = document.getElementById('signatures' + idx);
5468         } else {
5469             var sel = document.getElementById('signature_id');
5470             idx = SE.tinyInstances.currentHtmleditor;
5471         }
5472
5473         //Ensure that the tinyMCE html has been rendered.
5474         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5475             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5476                     return;
5477                 }
5478
5479         var signature = '';
5480
5481         try {
5482             signature = sel.options[sel.selectedIndex].value;
5483         } catch(e) {
5484
5485         }
5486
5487         var openTag = '<div><span><span>';
5488         var closeTag = '</span></span></div>';
5489         var t = tinyMCE.getInstanceById('htmleditor' + idx);
5490         //IE 6 Hack
5491         if(typeof(t) != 'undefined')
5492         {
5493             t.contentDocument = t.contentWindow.document;
5494             var html = t.getContent();
5495         }
5496         else
5497         {
5498             var html = '';
5499         }
5500
5501         var htmllow = html.toLowerCase();
5502         var start = htmllow.indexOf(openTag);
5503         var end = htmllow.indexOf(closeTag) + closeTag.length;
5504
5505         // selected "none" - remove signature from email
5506         if(signature == '') {
5507             if (start > -1) {
5508                 var htmlPart1 = html.substr(0, start);
5509                 var htmlPart2 = html.substr(end, html.length);
5510
5511                 html = htmlPart1 + htmlPart2;
5512                 t.setContent(html);
5513             }
5514             SE.signatures.lastAttemptedLoad = '';
5515             return false;
5516         }
5517
5518         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5519             SE.signatures.lastAttemptedLoad = '';
5520
5521         SE.signatures.lastAttemptedLoad = signature;
5522
5523         if(typeof(SE.signatures[signature]) == 'undefined') {
5524             //lazy load
5525             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5526             SE.signatures.targetInstance = (idx) ? idx : "";
5527             AjaxObject.target = '';
5528             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5529         } else {
5530             var newSignature = this.prepareSignature(SE.signatures[signature]);
5531
5532             // clear out old signature
5533             if(SE.signatures.lastAttemptedLoad && start > -1) {
5534                 var htmlPart1 = html.substr(0, start);
5535                 var htmlPart2 = html.substr(end, html.length);
5536
5537                 html = htmlPart1 + htmlPart2;
5538             }
5539
5540             // [pre|ap]pend
5541                         start = html.indexOf('<div><hr></div>');
5542             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5543                                 var htmlPart1 = html.substr(0, start);
5544                                 var htmlPart2 = html.substr(start, html.length);
5545                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5546             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5547                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5548             } else {
5549                 var newHtml = html + openTag + newSignature + closeTag;
5550             }
5551             //tinyMCE.setContent(newHtml);
5552             t.setContent(newHtml);
5553         }
5554     },
5555
5556     prepareSignature : function(str) {
5557         var signature = new String(str);
5558
5559         signature = signature.replace(/&lt;/gi, '<');
5560         signature = signature.replace(/&gt;/gi, '>');
5561
5562         return signature;
5563     },
5564
5565
5566     showAttachmentPanel : function(idx) {
5567         var east = SE.composeLayout[idx].getUnitByPosition("right");
5568         var tabs = SE.composeLayout[idx].rightTabs;
5569         east.expand();
5570         tabs.set("activeTab", tabs.getTab(0));
5571     },
5572
5573     /**
5574      * expands sidebar and displays options panel
5575      */
5576     showOptionsPanel : function(idx) {
5577         var east = SE.composeLayout[idx].getUnitByPosition("right");
5578         var tabs = SE.composeLayout[idx].rightTabs;
5579         east.expand();
5580         tabs.set("activeTab", tabs.getTab(1));
5581     },
5582
5583     /**
5584      * Selects the Contacts tab
5585      */
5586     showContactsPanel : function() {
5587         SE.complexLayout.regions.west.showPanel("contactsTab");
5588     },
5589
5590     /**
5591      * Generates fields for Select Document
5592      */
5593     addDocumentField : function(idx) {
5594         var basket = document.getElementById('addedDocuments' + idx);
5595         if(basket) {
5596             var index = (basket.childNodes.length / 7) - 1;
5597             if(index < 0)
5598                 index = 0;
5599         } else {
5600             index = 0;
5601         }
5602
5603         var test = document.getElementById('documentId' + idx + index);
5604
5605         while(test != null) {
5606             index++;
5607             test = document.getElementById('documentId' + idx + index);
5608         }
5609
5610         var documentCup = document.createElement("div");
5611         documentCup.id = 'documentCup' + idx + index;
5612         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5613                 // document id field
5614                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5615                 // document name field
5616                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5617                 // select button
5618                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5619                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5620                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5621                 // remove button
5622                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5623                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5624                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5625                 "<br/>";
5626
5627         basket.appendChild(documentCup);
5628         //basket.innerHTML += out;
5629         return index;
5630     },
5631
5632     /**
5633      * Makes async call to save a draft of the email
5634      * @param int Instance index
5635      */
5636     saveDraft : function(tinyInstance) {
5637         this.sendEmail(tinyInstance, true);
5638     },
5639
5640     selectDocument : function(target) {
5641         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5642         windowName = 'selectDocument';
5643         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5644
5645         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5646         if(window.focus) {
5647             // put the focus on the popup if the browser supports the focus() method
5648             win.focus();
5649         }
5650     },
5651
5652     /**
5653      * Modal popup for file attachment dialogue
5654      */
5655     addFileField : function() {
5656         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5657             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5658                 modal:true,
5659                 visible:false,
5660                 fixedcenter:true,
5661                 constraintoviewport: true,
5662                 scroll: true,
5663                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5664                         fn:function(){SE.addFileDialog.hide();}
5665                 })
5666             });
5667             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5668             SE.addFileDialog.render();
5669            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5670         }
5671         Dom.removeClass("addFileDialog", "yui-hidden");
5672
5673         SE.addFileDialog.show();
5674     },
5675
5676     /**
5677      * Async upload of file to temp dir
5678      */
5679     uploadAttachment : function() {
5680         if(document.getElementById('email_attachment').value != "") {
5681             var formObject = document.getElementById('uploadAttachment');
5682             YAHOO.util.Connect.setForm(formObject, true, true);
5683             AjaxObject.target = '';
5684             AjaxObject.startRequest(callbackUploadAttachment, null);
5685         } else {
5686             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5687         }
5688     },
5689
5690     /**
5691      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5692      * @param string target in focus compose layout
5693      */
5694     setDocument : function(idx, target, documentId, documentName, docRevId) {
5695         // fields are named/id'd [fieldName][instanceId][index]
5696         var addedDocs = document.getElementById("addedDocuments" + idx);
5697         var docId = document.getElementById('documentId' + idx + target);
5698         var docName = document.getElementById('documentName' + idx + target);
5699         var docRevisionId = document.getElementById('document' + idx + target);
5700         docId.value = documentId;
5701         docName.value = documentName;
5702         docRevisionId.value = docRevId;
5703     },
5704
5705     /**
5706      * Removes the bucket div containing the document input fields
5707      */
5708     deleteDocumentField : function(documentCup) {
5709         var f0 = document.getElementById(documentCup);
5710         f0.parentNode.removeChild(f0);
5711     },
5712
5713     /**
5714      * Removes a Template Attachment field
5715      * @param int
5716      * @param int
5717      */
5718     deleteTemplateAttachmentField : function(idx, index) {
5719         // create not-in-array values for removal filtering
5720         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5721
5722         if(r != "") {
5723             r += "::";
5724         }
5725
5726         r += document.getElementById('templateAttachmentId' + idx + index).value;
5727         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5728
5729         var target = 'templateAttachmentCup' + idx + index;
5730         d =  document.getElementById(target);
5731         d.parentNode.removeChild(d);
5732     },
5733
5734     /**
5735      * Async removal of uploaded temp file
5736      * @param string index Should be a concatenation of idx and index
5737      * @param string
5738      */
5739     deleteUploadAttachment : function(index, file) {
5740         var d = document.getElementById('email_attachment_bucket' + index);
5741         d.parentNode.removeChild(d);
5742
5743         // make async call to delete cached file
5744         AjaxObject.target = '';
5745         AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5746     },
5747
5748     /**
5749      * Attaches files coming from Email Templates
5750      */
5751     addTemplateAttachmentField : function(idx) {
5752         // expose title
5753         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5754
5755         var basket = document.getElementById('addedTemplateAttachments' + idx);
5756
5757         if(basket) {
5758             var index = basket.childNodes.length;
5759             if(index < 0)
5760                 index = 0;
5761         } else {
5762             index = 0;
5763         }
5764
5765         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5766                                 // remove button
5767                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5768                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5769                                         idx + "\",\"" + index + "\");'/>" +
5770                                 // file icon
5771                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5772                                 // templateAttachment field
5773                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5774                                 // docId field
5775                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5776                                 // file name
5777                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
5778                                 "<br id='br" + index + "></br>" +
5779                                 "<br id='brdoc" + index + "></br>" +
5780                         "</div>";
5781                 basket.innerHTML = basket.innerHTML + out;
5782
5783         return index;
5784     },
5785
5786     /**
5787      * Sends one email via async call
5788      * @param int idx Editor instance ID
5789      * @param bool isDraft
5790      */
5791     sendEmail : function(idx, isDraft) {
5792
5793         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5794         var obAccountID = document.getElementById('addressFrom' + idx).value;
5795
5796         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5797         {
5798             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5799             return false;
5800         }
5801
5802
5803         var form = document.getElementById('emailCompose' + idx);
5804         var composeOptionsFormName = "composeOptionsForm" + idx;
5805
5806         
5807         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5808         if (t != null || typeof(t) != "undefined") {
5809             var html = t.getContent();
5810         } else {
5811             var html = "<p>" + document.getElementById('htmleditor' + idx).value + "</p>";
5812         }
5813
5814             var subj = document.getElementById('emailSubject' + idx).value;
5815         var to = trim(document.getElementById('addressTO' + idx).value);
5816         var cc = trim(document.getElementById('addressCC' + idx).value);
5817         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5818         var email_id = document.getElementById('email_id' + idx).value;
5819         var composeType = document.getElementById('composeType').value;
5820         var parent_type = document.getElementById("parent_type").value;
5821         var parent_id = document.getElementById("parent_id").value;
5822
5823         var el_uid = document.getElementById("uid");
5824         var uid = (el_uid == null) ? '' : el_uid.value;
5825
5826         var el_ieId = document.getElementById("ieId");
5827         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5828
5829         var el_mbox = document.getElementById("mbox");
5830         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5831
5832         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5833                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5834                 return false;
5835         }
5836
5837         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5838                 return;
5839         } // if
5840                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5841                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5842         parent_id = parentIdValue;
5843         parent_type = parentTypeValue;
5844
5845         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5846         // baseline viability check
5847
5848         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5849             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5850             return false;
5851         } else if(subj == '' && !isDraft) {
5852             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5853                 return false;
5854             } else {
5855                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5856             }
5857         } else if(html == '' && !isDraft) {
5858             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5859                 return false;
5860             }
5861         }
5862
5863         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5864                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5865                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5866         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5867         html = html.replace(/&lt;/ig, "sugarLessThan");
5868         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5869
5870         form.sendDescription.value = html;
5871         form.sendSubject.value = subj;
5872         form.sendTo.value = to;
5873         form.sendCc.value = cc;
5874         form.sendBcc.value = bcc;
5875         form.email_id.value = email_id;
5876         form.composeType.value = composeType;
5877         form.composeLayoutId.value = 'composeLayout' + idx;
5878         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5879         form.saveToSugar.value = 1;
5880         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5881         form.parent_type.value = parent_type;
5882         form.parent_id.value = parent_id;
5883         form.uid.value = uid;
5884         form.ieId.value = ieId;
5885         form.mbox.value = mbox;
5886
5887         // email attachments
5888         var addedFiles = document.getElementById('addedFiles' + idx);
5889         if(addedFiles) {
5890             for(i=0; i<addedFiles.childNodes.length; i++) {
5891                 var bucket = addedFiles.childNodes[i];
5892
5893                 for(j=0; j<bucket.childNodes.length; j++) {
5894                     var node = bucket.childNodes[j];
5895                     var nName = new String(node.name);
5896
5897                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5898                         if(form.attachments.value != '') {
5899                             form.attachments.value += "::";
5900                         }
5901                         form.attachments.value += node.value;
5902                     }
5903                 }
5904             }
5905         }
5906
5907         // sugar documents
5908         var addedDocs = document.getElementById('addedDocuments' + idx);
5909         if(addedDocs) {
5910             for(i=0; i<addedDocs.childNodes.length; i++) {
5911                 var cNode = addedDocs.childNodes[i];
5912                 for(j=0; j<cNode.childNodes.length; j++) {
5913                     var node = cNode.childNodes[j];
5914                     var nName = new String(node.name);
5915                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5916                         if(form.documents.value != '') {
5917                             form.documents.value += "::";
5918                         }
5919                         form.documents.value += node.value;
5920                     }
5921                 }
5922             }
5923         }
5924
5925         // template attachments
5926         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5927         if(addedTemplateAttachments) {
5928             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5929                 var cNode = addedTemplateAttachments.childNodes[i];
5930                 for(j=0; j<cNode.childNodes.length; j++) {
5931                     var node = cNode.childNodes[j];
5932                     var nName = new String(node.name);
5933                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5934                         if(form.templateAttachments.value != "") {
5935                             form.templateAttachments.value += "::";
5936                         }
5937                         form.templateAttachments.value += node.value;
5938                     }
5939                 }
5940             }
5941         }
5942
5943         // remove attachments
5944         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5945
5946         YAHOO.util.Connect.setForm(form);
5947
5948         AjaxObject.target = 'frameFlex';
5949
5950         // sending a draft email
5951         if(!isDraft && in_draft) {
5952             // remove row
5953             SE.listView.removeRowByUid(email_id);
5954         }
5955
5956         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5957         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5958
5959         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5960     },
5961
5962     /**
5963      * Handles clicking the email address link from a given view
5964      */
5965     composePackage : function() {
5966         if(composePackage != null) {
5967             SE.composeLayout.c0_composeNewEmail();
5968
5969
5970             if(composePackage.to_email_addrs) {
5971                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5972             } // if
5973             if (composePackage.subject != null && composePackage.subject.length > 0) {
5974                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5975             }
5976
5977             //If no parent fields are set in the composePackage, ensure they are cleared.
5978             var parentFields = ['parent_type','parent_name','parent_id'];
5979             for(var i=0;i<parentFields.length;i++)
5980             {
5981                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5982                     composePackage[parentFields[i]] = "";
5983             }
5984
5985             document.getElementById("parent_type").value = composePackage.parent_type;
5986             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5987             document.getElementById("parent_id").value = composePackage.parent_id;
5988             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5989             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5990
5991             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5992                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5993             } // if
5994             if (composePackage.body != null && composePackage.body.length > 0) {
5995                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5996                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5997                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5998             } // if
5999             if (composePackage.attachments != null) {
6000                                 SE.composeLayout.loadAttachments(composePackage.attachments);
6001             } // if
6002
6003             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
6004                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
6005                         SE.util.emptySelectOptions(addressFrom);
6006                         var fromAccountOpts = composePackage.fromAccounts.data;
6007                         for(i=0; i<fromAccountOpts.length; i++) {
6008                               var key = fromAccountOpts[i].value;
6009                               var display = fromAccountOpts[i].text;
6010                               var opt = new Option(display, key);
6011                               if (fromAccountOpts[i].selected) {
6012                                 opt.selected = true;
6013                               }
6014                               addressFrom.options.add(opt);
6015                         }
6016
6017             } // if
6018         } // if
6019     },
6020
6021     setContentOnThisTiny : function() {
6022         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6023         var tinyHTML = tiny.getContent();
6024         composePackage.body = decodeURI(encodeURI(composePackage.body));
6025         // cn: bug 14361 - text-only templates don't fill compose screen
6026         if(composePackage.body == '') {
6027             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,'"');
6028         } // if
6029         //Flag determines if we should clear the tiny contents or just append
6030         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6031             SE.composeLayout.tinyHTML = '';
6032         else
6033             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6034
6035          tiny.setContent(SE.composeLayout.tinyHTML);
6036          //Indicate that the contents has been loaded successfully.
6037          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6038     },
6039     /**
6040      * Confirms closure of a compose screen if "x" is clicked
6041      */
6042     confirmClose : function(panel) {
6043         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6044             SE.composeLayout.closeCompose(panel.id);
6045             return true;
6046         } else {
6047             return false;
6048         }
6049     },
6050
6051     /**
6052      * forces close of a compose screen
6053      */
6054     forceCloseCompose : function(id) {
6055         SE.composeLayout.closeCompose(id);
6056
6057         // handle flow back to originating view
6058         if(composePackage) {
6059             // check if it's a module we need to return to
6060             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6061                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6062                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6063                     window.location = url;
6064                 }
6065             }
6066         }
6067     },
6068
6069     /**
6070      * closes the editor that just sent email
6071      * @param string id ID of composeLayout tab
6072      */
6073     closeCompose : function(id) {
6074         // destroy tinyMCE instance
6075         var idx = id.substr(13, id.length);
6076         var instanceId = "htmleditor" + idx;
6077         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6078
6079         // nullify DOM and namespace values.
6080         inCompose = false;
6081         SE.composeLayout[idx] = null;
6082         SE.tinyInstances[instanceId] = null;
6083         var tabsArray = SE.innerLayout.get("tabs");
6084         for (i = 0 ; i < tabsArray.length ; i++) {
6085                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6086                         tabsArray[i].close();
6087                         break;
6088                 }
6089         }
6090         //SE.innerLayout.getTab(idx).close();
6091     },
6092
6093     /**
6094     *  Enable the quick search for the compose relate field or search tab
6095     */
6096     enableQuickSearchRelate: function(idx,overides){
6097
6098         if(typeof overides != 'undefined')
6099         {
6100             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6101             var newModule = document.getElementById(newModuleID).value;
6102             var formName = overides['formName'];
6103             var fieldName = overides['fieldName'];
6104             var fieldId = overides['fieldId'];
6105             var fullName = formName + "_" + fieldName;
6106             var postBlurFunction = null;
6107         }
6108         else
6109         {
6110             var newModule = document.getElementById('data_parent_type'+idx).value;
6111             var formName = 'emailCompose'+idx;
6112             var fieldName = 'data_parent_name'+idx;
6113             var fieldId = 'data_parent_id'+idx;
6114             var fullName = formName + "_" + fieldName;
6115             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6116         }
6117
6118         if(typeof sqs_objects == 'undefined')
6119             window['sqs_objects'] = new Array;
6120
6121         window['sqs_objects'][fullName] = {
6122             form:formName,
6123                         method:"query",
6124                         modules:[newModule],
6125                         group:"or",
6126             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6127             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6128                         post_onblur_function: postBlurFunction,
6129             order:"name","limit":"30","no_match_text":"No Match"};
6130
6131
6132         if(typeof QSProcessedFieldsArray != 'undefined')
6133                 QSProcessedFieldsArray[fullName] = false;
6134         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6135                 QSFieldsArray[fullName].destroy();
6136                 delete QSFieldsArray[fullName];
6137         }
6138         if (Dom.get(fullName + "_results")) {
6139                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6140         }
6141
6142         enableQS(false);
6143     },
6144
6145         qsAddAddress : function(o) {
6146         if (o.name != "" && o.email1 != "")
6147         {
6148                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6149                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6150         }
6151     },
6152     /**
6153      * Returns a new instance ID, 0-index
6154      */
6155     getNewInstanceId : function() {
6156         this.currentInstanceId = this.currentInstanceId + 1;
6157         return this.currentInstanceId;
6158     },
6159
6160     /**
6161      * 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.
6162      */
6163     loadAttachments : function(result) {
6164         var idx = SE.composeLayout.currentInstanceId;
6165
6166         if(typeof(result) == 'object') {
6167                 //jchi #20680. Clean the former template attachments;
6168                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6169                         if(basket.innerHTML != ''){
6170                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6171                                         if (btn != 'yes'){
6172                                                 basket.innerHTML = '';
6173                                         }
6174                                 });
6175                         }
6176             for(i in result) {
6177                 if(typeof result[i] == 'object') {
6178                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6179                     var bean = result[i];
6180                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6181                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6182                 }
6183             }
6184         }
6185     },
6186
6187     /**
6188      * fills drop-down values for email templates and signatures
6189      */
6190     setComposeOptions : function(idx) {
6191         // send from accounts
6192         var addressFrom = document.getElementById('addressFrom' + idx);
6193
6194         if (addressFrom.options.length <= 0) {
6195                 SE.util.emptySelectOptions(addressFrom);
6196                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6197                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6198                       var key = fromAccountOpts[id].value;
6199                       var display = fromAccountOpts[id].text;
6200                       var is_default = false;
6201                       if(key == SUGAR.default_inbound_accnt_id)
6202                         is_default = true;
6203                       var opt = new Option(display, key);
6204                       addressFrom.options.add(opt);
6205                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6206                 }
6207         }
6208
6209         // email templates
6210         var et = document.getElementById('email_template' + idx);
6211         SE.util.emptySelectOptions(et);
6212
6213         for(var key in this.emailTemplates) { // iterate through assoc array
6214             var display = this.emailTemplates[key];
6215             var opt = new Option(display, key);
6216             et.options.add(opt);
6217         }
6218
6219         // signatures
6220         var sigs = document.getElementById('signatures' + idx);
6221         SE.util.emptySelectOptions(sigs);
6222
6223         for(var key in this.signatures) { // iterate through assoc array
6224             var display = this.signatures[key];
6225             var opt = new Option(display, key);
6226
6227             if(key == SE.userPrefs.signatures.signature_default) {
6228                 opt.selected = true;
6229             }
6230
6231             sigs.options.add(opt);
6232         }
6233
6234         // html/plain email?
6235         var htmlEmail = document.getElementById('setEditor' + idx);
6236         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6237             htmlEmail.checked = true;
6238         } else {
6239                 htmlEmail.checked = false;
6240         }
6241
6242         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6243     },
6244
6245     /**
6246      * After compose screen is rendered, async call to get email body from Sugar
6247      */
6248     replyForwardEmailStage2 : function() {
6249         SE.util.clearHiddenFieldValues('emailUIForm');
6250         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6251
6252         var ieId = SE.composeLayout.replyForwardObj.ieId;
6253         var uid = SE.composeLayout.replyForwardObj.uid;
6254         var mbox = SE.composeLayout.replyForwardObj.mbox;
6255         var type = SE.composeLayout.replyForwardObj.type;
6256         var idx = SE.composeLayout.currentInstanceId;
6257
6258         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6259
6260         document.getElementById('emailSubject' + idx).value = type;
6261         document.getElementById('emailUIAction').value = 'composeEmail';
6262         document.getElementById('composeType').value = type;
6263         document.getElementById('ieId').value = ieId;
6264         document.getElementById('uid').value = uid;
6265         document.getElementById('mbox').value = mbox;
6266                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6267         var formObject = document.getElementById('emailUIForm');
6268         YAHOO.util.Connect.setForm(formObject);
6269
6270         var sendType = type;
6271         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6272     },
6273
6274     /**
6275     *  Show the hidden cc or bcc fields
6276     */
6277     showHiddenAddress: function(addrType,idx){
6278
6279         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6280         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6281                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6282                 this[addrType+'Hidden'+idx] = false;
6283
6284                 //After bcc or cc is added, move options below last addr field
6285                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6286
6287                 //If both cc and bcc hidden, remove the empty row containing text.
6288                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6289                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6290                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6291
6292                 // SE.composeLayout.resizeEditor(idx);
6293     },
6294     /**
6295     *  Hide the cc and bcc fields if they were shown.
6296     */
6297     hideHiddenAddresses: function(idx){
6298
6299         var addrTypes = ['cc','bcc'];
6300         for(var i = 0;i<addrTypes.length;i++)
6301         {
6302             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6303             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6304             this[addrTypes[i] + 'Hidden'+idx] = true
6305         }
6306
6307         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6308         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6309         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6310     }
6311 };
6312
6313 ////    END SE.composeLayout
6314 ///////////////////////////////////////////////////////////////////////////////
6315 ///////////////////////////////////////////////////////////////////////////////
6316 ////    SE.util
6317 SE.util = {
6318     /**
6319      * Cleans serialized UID lists of duplicates
6320      * @param string
6321      * @return string
6322      */
6323     cleanUids : function(str) {
6324         var seen = new Object();
6325         var clean = "";
6326         var arr = new String(str).split(",");
6327
6328         for(var i=0; i<arr.length; i++) {
6329             if(seen[arr[i]]) {
6330                 continue;
6331             }
6332
6333             clean += (clean != "") ? "," : "";
6334             clean += arr[i];
6335             seen[arr[i]] = true;
6336         }
6337
6338         return clean;
6339     },
6340
6341     /**
6342      * Clears hidden field values
6343      * @param string id ID of form element to clear
6344      */
6345     clearHiddenFieldValues : function(id) {
6346         var form = document.getElementById(id);
6347
6348         for(i=0; i<form.elements.length; i++) {
6349             if(form.elements[i].type == 'hidden') {
6350                 var e = form.elements[i];
6351                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6352                     e.value = '';
6353                 }
6354             }
6355         }
6356     },
6357
6358     /**
6359      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6360      */
6361     emptySelectOptions : function(el) {
6362         if(el) {
6363             for(i=el.childNodes.length - 1; i >= 0; i--) {
6364                 if(el.childNodes[i]) {
6365                     el.removeChild(el.childNodes[i]);
6366                 }
6367             }
6368         }
6369     },
6370
6371     /**
6372      * Returns the MBOX path in the manner php_imap expects:
6373      * ie: INBOX.DEBUG.test
6374      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6375      */
6376     generateMboxPath : function(str) {
6377         var ex = str.split("::");
6378
6379         /* we have a serialized MBOX path */
6380         if(ex.length > 1) {
6381             var start = false;
6382             var ret = '';
6383             for(var i=0; i<ex.length; i++) {
6384                 if(ex[i] == 'INBOX') {
6385                     start = true;
6386                 }
6387
6388                 if(start == true) {
6389                     if(ret != "") {
6390                         ret += ".";
6391                     }
6392                     ret += ex[i];
6393                 }
6394             }
6395         } else {
6396             /* we have a Sugar folder GUID - do nothing */
6397             return str;
6398         }
6399
6400         return ret;
6401     },
6402
6403     /**
6404      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6405      * @param HTMLElement el
6406      * @return string GUID of found element or empty on failure
6407      */
6408     getGuidFromElement : function(el) {
6409         var GUID = '';
6410         var iterations = 4;
6411         var passedEl = el;
6412
6413         // upwards
6414         for(var i=0; i<iterations; i++) {
6415             if(el) {
6416                 if(el.id.match(SE.reGUID)) {
6417                     return el.id;
6418                 } else {
6419                     el = el.parentNode;
6420                 }
6421             }
6422         }
6423
6424         return GUID;
6425     },
6426
6427     /**
6428      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6429      * @return string
6430      */
6431     getPanelId : function() {
6432         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6433     },
6434
6435     /**
6436      * wrapper to handle weirdness with IE
6437      * @param string instanceId
6438      * @return tinyMCE Controller object
6439      */
6440     getTiny : function(instanceId) {
6441         if(instanceId == '') {
6442             return null;
6443         }
6444
6445         var t = tinyMCE.getInstanceById(instanceId);
6446
6447         if(this.isIe()) {
6448             this.sleep(200);
6449             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6450         }
6451         return t;
6452     },
6453
6454     /**
6455      * Simple check for MSIE browser
6456      * @return bool
6457      */
6458     isIe : function() {
6459         var nav = new String(navigator.appVersion);
6460         if(nav.match(/MSIE/)) {
6461             return true;
6462         }
6463         return false;
6464     },
6465
6466     /**
6467      * Recursively removes an element from the DOM
6468      * @param HTMLElement
6469      */
6470     removeElementRecursive : function(el) {
6471         this.emptySelectOptions(el);
6472     },
6473
6474     /**
6475      * Fakes a sleep
6476      * @param int
6477      */
6478     sleep : function(secs) {
6479         setTimeout("void(0);", secs);
6480     },
6481
6482     /**
6483      * Converts a <select> element to an Ext.form.combobox
6484      */
6485      convertSelect : function(select) {
6486        alert('in convertSelect');
6487        if (typeof(select) == "string") {
6488            select = document.getElementById(select);
6489        }
6490      },
6491
6492      findChildNode : function (parent, property, value) {
6493          for (i in parent.children) {
6494                  var child = parent.children[i];
6495                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6496                          return child;
6497                  var searchChild = SE.util.findChildNode(child, property, value);
6498                  if (searchChild)
6499                          return searchChild;
6500          }
6501          return false;
6502      },
6503
6504      cascadeNodes : function (parent, fn, scope, args) {
6505          for (i in parent.children) {
6506                  var child = parent.children[i];
6507                  var s = scope ? scope : child;
6508                  var a = args ? args : child;
6509                  fn.call(s, a);
6510                  SE.util.cascadeNodes(child, fn, scope, args);
6511          }
6512      }
6513 };
6514
6515
6516 ////    END UTIL
6517 ///////////////////////////////////////////////////////////////////////////////
6518
6519
6520 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6521                                 
6522 /*********************************************************************************
6523  * SugarCRM Community Edition is a customer relationship management program developed by
6524  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6525  * 
6526  * This program is free software; you can redistribute it and/or modify it under
6527  * the terms of the GNU Affero General Public License version 3 as published by the
6528  * Free Software Foundation with the addition of the following permission added
6529  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6530  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6531  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6532  * 
6533  * This program is distributed in the hope that it will be useful, but WITHOUT
6534  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6535  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6536  * details.
6537  * 
6538  * You should have received a copy of the GNU Affero General Public License along with
6539  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6540  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6541  * 02110-1301 USA.
6542  * 
6543  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6544  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6545  * 
6546  * The interactive user interfaces in modified source and object code versions
6547  * of this program must display Appropriate Legal Notices, as required under
6548  * Section 5 of the GNU Affero General Public License version 3.
6549  * 
6550  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6551  * these Appropriate Legal Notices must retain the display of the "Powered by
6552  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6553  * technical reasons, the Appropriate Legal Notices must display the words
6554  * "Powered by SugarCRM".
6555  ********************************************************************************/
6556
6557
6558 if (typeof console == "undefined")
6559         console = { log: function(o) {alert(o)} };
6560
6561 var AjaxObject = {
6562         ret : '',
6563         currentRequestObject : null,
6564         //timeout : 30000, // 30 second timeout default
6565         timeout : 9999999999, // 30 second timeout default
6566         forceAbort : false,
6567         trail : new Array(),
6568
6569         /**
6570          */
6571         _reset : function() {
6572                 this.timeout = 30000;
6573                 this.forceAbort = false;
6574         },
6575
6576         folderRenameCleanup : function() {
6577                 SUGAR.email2.folders.setSugarFolders();
6578         },
6579
6580         fullSyncCleanup : function(o) {
6581                 this.folders.checkMailCleanup(o);
6582                 SUGAR.email2.settings.settingsDialog.hide();
6583         },
6584
6585         /**
6586          */
6587         composeCache : function(o) {
6588                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6589                 // get email templates and user signatures
6590                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6591
6592                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6593                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6594                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6595
6596                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6597
6598                 //Set the error array so we can notify the user when they try to hit send if any errors
6599                 //are present.  We will also notify them now (after hitting compose button).
6600                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6601
6602
6603                 //if error element is returning an array, then check the length to make sure we have error messages
6604                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6605                         //add error messages for display
6606                         for(i in ret.errorArray)
6607                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6608                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6609                         //if error element is returning an object, and the object value is not empty or null, then display error message
6610                         for(i in ret.errorArray)
6611                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6612                 }
6613
6614                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6615                 if(SUGAR.isIE) {
6616                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6617                         if(overlayPanel) {
6618                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6619                         }
6620                 }
6621         },
6622
6623
6624         handleDeleteSignature : function(o) {
6625                 hideOverlay();
6626                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6627                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6628         var field = document.getElementById('signature_id');
6629                 SUGAR.email2.util.emptySelectOptions(field);
6630
6631                 for(var i in ret.signatures) { // iterate through assoc array
6632                         var opt = new Option(ret.signatures[i], i);
6633                         field.options.add(opt);
6634                 }
6635                 setSigEditButtonVisibility();
6636         },
6637
6638         /**
6639          */
6640         handleDeleteReturn : function(o) {
6641                 // force refresh ListView
6642                 hideOverlay();
6643                 if(document.getElementById('focusEmailMbox')) {
6644                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6645                 }
6646
6647                 // need to display success message before calling next async call?
6648                 document.getElementById(this.target).innerHTML = o.responseText;
6649         },
6650
6651         /**
6652          */
6653     handleFailure : function(o) {
6654                 // Failure handler
6655                 overlay('Exception occurred...', o.statusText, 'alert');
6656                 if(document.getElementById('saveButton')) {
6657                         document.getElementById('saveButton').disabled = false;
6658                 }
6659         },
6660
6661         handleReplyForward : function(o) {
6662                 var a = YAHOO.lang.JSON.parse(o.responseText);
6663                 globalA = a;
6664                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6665
6666                 document.getElementById('email_id' + idx).value = a.uid;
6667                 document.getElementById('emailSubject' + idx).value = a.name;
6668                 document.getElementById('addressTO' + idx).value = a.from;
6669                 document.getElementById('uid' + idx).value = a.uid;
6670                 if(a.cc) {
6671                         document.getElementById('addressCC' + idx).value = a.cc;
6672                         SE.composeLayout.showHiddenAddress('cc', idx);
6673                 }
6674
6675                 if(a.type) {
6676                         document.getElementById('type' + idx).value = a.type;
6677                 }
6678
6679                 // apply attachment values
6680                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6681
6682                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6683         },
6684
6685         handleReplyForwardForDraft : function(o) {
6686                 var a = YAHOO.lang.JSON.parse(o.responseText);
6687                 globalA = a;
6688                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6689
6690                 document.getElementById('email_id' + idx).value = a.uid;
6691                 document.getElementById('emailSubject' + idx).value = a.name;
6692                 document.getElementById('addressTO' + idx).value = a.to;
6693
6694                 if(a.cc) {
6695                         document.getElementById('addressCC' + idx).value = a.cc;
6696                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6697                 }
6698
6699                 if(a.bcc) {
6700                         document.getElementById('addressBCC' + idx).value = a.bcc;
6701                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6702                 }
6703
6704
6705                 if(a.type) {
6706                         document.getElementById('type' + idx).value = a.type;
6707                 }
6708
6709
6710                 // apply attachment values
6711                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6712
6713                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6714         },
6715
6716         /**
6717          */
6718         handleSuccess : function(o) {
6719                 document.getElementById(this.target).innerHTML = o.responseText;
6720                 hideOverlay();
6721         },
6722
6723         /**
6724          */
6725         ieDeleteSuccess : function(o) {
6726                 hideOverlay();
6727                 
6728                 SUGAR.email2.accounts.refreshInboundAccountTable();
6729                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6730                 SUGAR.email2.accounts.rebuildFolderList();
6731         },
6732
6733         /**
6734          */
6735         ieSaveSuccess : function(o) {
6736                 document.getElementById('saveButton').disabled = false;
6737                 var a = YAHOO.lang.JSON.parse(o.responseText);
6738                 if (a) {
6739                         if(a.error) {
6740                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6741                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6742                         } else {
6743                                 resp = YAHOO.lang.JSON.parse(o.responseText);
6744                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6745                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6746                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6747                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6748                         }
6749                 } else {
6750                      hideOverlay();
6751                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6752                 }
6753
6754         },
6755
6756         /**
6757          */
6758         loadAttachments : function(o) {
6759                 var result = YAHOO.lang.JSON.parse(o.responseText);
6760
6761                 SUGAR.email2.composeLayout.loadAttachments(result);
6762         },
6763
6764         /**
6765          */
6766         loadSignature : function(o) {
6767                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6768                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6769                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6770         },
6771
6772         /**
6773          * Follow up to mark email read|unread|flagged
6774          */
6775         markEmailCleanup : function(o) {
6776                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6777                 if (!ret['status']) {
6778                 hideOverlay();
6779                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6780                 } else {
6781                         SUGAR.email2.contextMenus.markEmailCleanup();
6782                 } // else
6783         },
6784
6785         /**
6786          */
6787         rebuildShowFolders : function(o) {
6788                 var t = YAHOO.lang.JSON.parse(o.responseText);
6789                 var show = document.getElementById('ieAccountListShow');
6790
6791                 SUGAR.email2.util.emptySelectOptions(show);
6792
6793                 for(i=0; i<t.length; i++) { // iterate through assoc array
6794                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6795                         opt.selected = t[i].selected;
6796                         show.options.add(opt);
6797                 }
6798
6799                 SUGAR.email2.accounts.renderTree();
6800         },
6801         /**
6802          */
6803         saveListViewSortOrderPart2 : function() {
6804                 // create the JSON string the func expects
6805                 focusFolderPath = '[ "Home", "' + ieName + '"';
6806
6807                 var f = new String(focusFolder);
6808                 var fEx = f.split('.');
6809
6810                 for(i=0; i<fEx.length; i++) {
6811                         focusFolderPath += ', "' + fEx[i] +'"'
6812                 }
6813
6814                 focusFolderPath += ']';
6815
6816                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6817                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6818         },
6819
6820         /**
6821          *
6822          */
6823         sendEmailCleanUp : function(o) {
6824         var ret;
6825                 hideOverlay();
6826
6827         try {
6828             ret = YAHOO.lang.JSON.parse(o.responseText);
6829             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6830             //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6831         } catch(err) {
6832             if (o.responseText) {
6833                         overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6834                     }
6835             // Else we have an error here.
6836         }
6837         
6838                 if (typeof(SE.grid) != 'undefined')
6839                         SE.listView.refreshGrid();
6840                 //Disabled while address book is disabled
6841
6842                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6843                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6844                 //close the shortcut bar menu
6845                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6846                         if(action_sugar_grp1 == 'DetailView') {
6847                                 showSubPanel('history',null,true);
6848                         } else if(action_sugar_grp1 == 'quickcreate') {
6849                                 closeEmailOverlay();
6850                         }
6851                 }
6852
6853         },
6854
6855         ieSendSuccess : function(o) {
6856                 hideOverlay();
6857                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6858         },
6859
6860         /**
6861          */
6862         settingsFolderRefresh : function(o) {
6863                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6864                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6865                 var user = document.getElementById('userFolders');
6866
6867                 SUGAR.email2.util.emptySelectOptions(user);
6868
6869                 for(i=0; i<ret.userFolders.length; i++) {
6870                         var display = ret.userFolders[i].name;
6871                         var value = ret.userFolders[i].id;
6872                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6873                         var opt = new Option(display, value, selected);
6874                         opt.selected = selected;
6875                         user.options.add(opt);
6876                 }
6877         },
6878
6879         /**
6880          */
6881         startRequest : function(callback, args, forceAbort) {
6882                 if(this.currentRequestObject != null) {
6883                         if(this.forceAbort == true) {
6884                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6885                         }
6886                 }
6887                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6888                 this._reset();
6889         },
6890
6891         requestInProgress : function() {
6892                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6893         },
6894
6895         /**
6896          */
6897         updateFolderSubscriptions : function() {
6898                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6899                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6900                 hideOverlay();
6901         },
6902
6903         /**
6904          */
6905         updateFrameFolder : function() {
6906                 SUGAR.email2.folders.checkEmailAccounts();
6907         },
6908
6909         /**
6910          */
6911         updateUserPrefs : function(o) {
6912                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6913                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6914         },
6915
6916         /**
6917          */
6918         uploadAttachmentSuccessful : function(o) {
6919                 // clear out field
6920                 document.getElementById('email_attachment').value = '';
6921                 
6922                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6923                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6924                 var overall = document.getElementById('addedFiles' + idx);
6925                 var index = overall.childNodes.length;
6926                 var out =
6927                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6928                                 // remove button
6929                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6930                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6931                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6932                                 // file icon
6933                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6934                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6935                                 // hidden id field
6936                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6937                                 // file name
6938                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6939                                 "<br/>" +
6940                         "</div>";
6941                 overall.innerHTML += out;
6942                 if(SUGAR.email2.util.isIe()) {
6943                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6944                 }
6945
6946                 // hide popup
6947                 SUGAR.email2.addFileDialog.hide();
6948                 // focus attachments
6949                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6950         }
6951 };
6952
6953
6954 ///////////////////////////////////////////////////////////////////////////
6955 ////    PER MODULE CALLBACK OBJECTS
6956 AjaxObject.accounts = {
6957         saveOutboundCleanup : function(o) {
6958                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6959                 SUGAR.email2.accounts.outboundDialog.hide();
6960                 var id = o.responseText;
6961                 SUGAR.email2.accounts.newAddedOutboundId = id;
6962                 },
6963         saveDefaultOutboundCleanup: function(o){
6964
6965         },
6966         callbackEditOutbound : {
6967                 success : function(o)
6968                 {
6969                         var ret = YAHOO.lang.JSON.parse(o.responseText);
6970                         // show overlay
6971                         SUGAR.email2.accounts.showAddSmtp();
6972
6973                         // fill values
6974                         document.getElementById("mail_id").value = ret.id;
6975                         document.getElementById("type").value = ret.type;
6976                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6977                         document.getElementById("mail_name").value = ret.name;
6978                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6979                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6980                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6981                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6982                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6983                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6984                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6985
6986             if(ret.type == 'system-override') {
6987                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6988                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6989             }
6990             else {
6991                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6992                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6993             }
6994             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6995
6996                 },
6997                 failure : AjaxObject.handleFailure,
6998                 timeout : AjaxObject.timeout,
6999                 scope   : AjaxObject
7000         },
7001         callbackDeleteOutbound : {
7002                 success : function(o) {
7003                     var ret = YAHOO.lang.JSON.parse(o.responseText);
7004                     if(ret.is_error)
7005                     {
7006                         if(confirm(ret.error_message))
7007                 {
7008                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
7009                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
7010                 }
7011                 else
7012                     hideOverlay();
7013                     }
7014                     else
7015                     {
7016                              hideOverlay();
7017                              SUGAR.email2.accounts.refreshOuboundAccountTable();
7018                     }
7019                 },
7020
7021                 failure : AjaxObject.handleFailure,
7022                 timeout : AjaxObject.timeout,
7023                 scope   : AjaxObject
7024         },
7025
7026         callbackCheckMailProgress : {
7027            success : function(o) {
7028                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7029                    SUGAR.email2.accounts.totalMsgCount = -1;
7030                }
7031
7032                //Check for server timeout / errors
7033                var ret = YAHOO.lang.JSON.parse(o.responseText);
7034                var done = false;
7035
7036                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7037                    hideOverlay();
7038                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7039                    SUGAR.email2.accounts.totalMsgCount = -1;
7040                //SUGAR.email2.folders.rebuildFolders();
7041                done = true;
7042                }
7043
7044                var currIeId = ret['ieid'];
7045
7046
7047                var serverCount = ret.count;
7048
7049                if (ret['status'] == 'done') {
7050                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7051                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7052                            //We are all done
7053                            done = true;
7054                            break;
7055                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7056                            //Go to next account
7057                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
7058                            ret.count = 0;
7059                            SUGAR.email2.accounts.totalMsgCount = -1;
7060                            break;
7061                        }
7062                    }
7063                }
7064                else if (ret.mbox && ret.totalcount && ret.count) {
7065                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7066                    if (ret.count >= ret.totalcount) {
7067                        serverCount = 0;
7068                    }
7069                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7070                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7071                } else {
7072                        hideOverlay();
7073                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7074                SUGAR.email2.accounts.totalMsgCount = -1;
7075                done = true;
7076                    }
7077
7078                if (done) {
7079                    SUGAR.email2.accounts.totalMsgCount = -1;
7080                    hideOverlay();
7081                    SUGAR.email2.folders.rebuildFolders();
7082                    SE.listView.refreshGrid();
7083                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7084                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7085                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7086                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7087            } else {
7088                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7089                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7090                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7091                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7092                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7093                }
7094            },
7095            failure : AjaxObject.handleFailure,
7096        timeout : AjaxObject.timeout,
7097        scope   : AjaxObject
7098         }
7099 };
7100
7101 ///////////////////////////////////////////////////////////////////////////////
7102 ////    COMPOSE LAYOUT
7103 AjaxObject.composeLayout = {
7104     /**
7105      * Populates the record id
7106      */
7107     saveDraftCleanup : function(o) {
7108         var ret;
7109         hideOverlay();
7110
7111         try {
7112             ret = YAHOO.lang.JSON.parse(o.responseText);
7113             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7114         } catch(err) {
7115             if (o.responseText) {
7116                 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7117             }
7118         }
7119     }
7120 };
7121
7122 AjaxObject.composeLayout.callback = {
7123         saveDraft : {
7124                 success : AjaxObject.composeLayout.saveDraftCleanup,
7125                 failure : AjaxObject.handleFailure,
7126                 timeout : AjaxObject.timeout,
7127                 scope   : AjaxObject
7128         }
7129 };
7130
7131 AjaxObject.detailView = {
7132         /**
7133          * Pops-up a printable view of an email
7134          */
7135         displayPrintable : function(o) {
7136                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7137                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7138                 // 2 below must be in global context
7139                 meta = ret.meta;
7140                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7141                 email = ret.meta.email;
7142                 if (typeof(email.cc) == 'undefined') {
7143                   email.cc = "";
7144                 }
7145
7146                 var out = displayTemplate.exec({
7147                         'app_strings'   : app_strings,
7148                         'theme'                 : theme,
7149                         'idx'                   : 'Preview',
7150                         'meta'                  : meta,
7151                         'email'                 : meta.email
7152                 });
7153
7154                 // open popup window
7155                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7156                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7157
7158                 popup.document.write(out);
7159                 popup.document.close();
7160         },
7161
7162         /**
7163          * Takes formatted response and creates a modal pop-over containing a title and content
7164          */
7165         displayView : function(o) {
7166                 var SED = SUGAR.email2.detailView;
7167                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7168
7169                 if(!SED.viewDialog) {
7170                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7171                                 modal:true,
7172                 visible:true,
7173                 fixedcenter:true,
7174                 constraintoviewport: true,
7175                                 shadow  : true
7176                         });
7177             SED.viewDialog.renderEvent.subscribe(function() {
7178                 var content = this.body.firstChild;
7179                 var viewH = YAHOO.util.Dom.getViewportHeight();
7180                 if (content) {
7181                         this.body.style.overflow = "auto";
7182                         this.body.style.width = "800px";
7183                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7184                 }
7185             }, SED.viewDialog);
7186                 } // end lazy load
7187                 SED.viewDialog.setHeader(ret.title);
7188                 SED.viewDialog.setBody(ret.html);
7189                 SED.viewDialog.render();
7190                 SED.viewDialog.show();
7191         },
7192
7193         /**
7194          * Generates a modal popup to populate with the contents of bean's full EditView
7195          */
7196         showQuickCreateForm : function(o) {
7197                 var SED = SUGAR.email2.detailView;
7198                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7199
7200                 if(!SED.quickCreateDialog) {
7201                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7202                                 modal:true,
7203                                 visible:true,
7204                 fixedcenter:true,
7205                 constraintoviewport: true,
7206                                 shadow  : true
7207                         });
7208
7209             SED.quickCreateDialog.renderEvent.subscribe(function() {
7210                 var viewH = YAHOO.util.Dom.getViewportHeight();
7211                 var contH = 0;
7212                 for (var i in this.body.childNodes) {
7213                         if (this.body.childNodes[i].clientHeight) {
7214                                 contH += this.body.childNodes[i].clientHeight;
7215                         } else if (this.body.childNodes[i].offsetHeight) {
7216                                 contH += this.body.childNodes[i].offsetHeight;
7217                         } // if
7218                 }
7219                         this.body.style.width = "800px";
7220                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7221                         this.body.style.overflow = "auto";
7222             }, SED.quickCreateDialog);
7223
7224             SED.quickCreateDialog.hideEvent.subscribe(function(){
7225                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7226                                 /*for(var qsField in qsFields){
7227                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7228                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7229                                 }*/
7230                         });
7231             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7232                 } // end lazy load
7233                 if (ret.html) {
7234                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7235                 }
7236                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7237                 SED.quickCreateDialog.render();
7238                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7239
7240                 SED.quickCreateDialog.ieId = ret.ieId;
7241                 SED.quickCreateDialog.uid = ret.uid;
7242         SED.quickCreateDialog.mbox = ret.mbox;
7243         SED.quickCreateDialog.qcmodule = ret.module;
7244
7245         SED.quickCreateDialog.show();
7246
7247                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7248                 if (editForm) {
7249                   editForm.module.value = 'Emails';
7250                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7251                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7252                   var instId = ret.module + count;
7253                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7254                   SED.quickCreateEmailCallback = function(instId, tableId) {
7255                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7256                           if (typeof(eaw) == "undefined")
7257                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7258                                                 + instId + "','" + tableId + "');", 100);
7259                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7260                   }
7261                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7262                                         + instId + "','" + tableId + "');", 100);
7263                 }
7264         },
7265
7266         saveQuickCreateForm : function(o) {
7267             hideOverlay();
7268                 SUGAR.email2.detailView.quickCreateDialog.hide();
7269                 validate['EditView'] = [ ];
7270         },
7271
7272         saveQuickCreateFormAndReply : function(o) {
7273             hideOverlay();
7274             var ret = YAHOO.lang.JSON.parse(o.responseText);
7275         SUGAR.email2.detailView.quickCreateDialog.hide();
7276         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7277         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7278         if (ret) {
7279             var emailID = ret.id;
7280             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7281         } else {
7282             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7283         }
7284         //Cean the validate cache to prevent errors on the next call
7285         validate['EditView'] = [ ];
7286     },
7287
7288         saveQuickCreateFormAndAddToAddressBook : function(o) {
7289            hideOverlay();
7290                 SUGAR.email2.detailView.quickCreateDialog.hide();
7291                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7292                 validate['EditView'] = [ ];
7293         },
7294
7295         handleAssignmentDialogAssignAction : function() {
7296
7297
7298             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7299
7300             var dist = 'direct';
7301             var users = false;
7302             var rules = false;
7303             var get = "";
7304             var found_teams = false;
7305             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7306             if(!found_teams && assign_user_id == '' )
7307             {
7308                 alert(warning_message);
7309                 return;
7310             }
7311
7312             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7313             var uids = "";
7314             for(i=0; i<emailUids.length; i++) {
7315                 if(uids != '') {
7316                     uids += app_strings.LBL_EMAIL_DELIMITER;
7317                 }
7318                 uids += emailUids[i];
7319             }
7320
7321             var row = SUGAR.email2.grid.getSelectedRows()[0];
7322             var data = SUGAR.email2.grid.getRecord(row).getData();
7323             var ieid = data.ieId;
7324             var mbox = data.mbox;
7325             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7326             SUGAR.email2.contextMenus.assignToDialogue.hide();
7327             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7328
7329         },
7330
7331         handleAssignmentDialogDeleteAction : function() {
7332                 // TO pass list of UIDS/emailIds
7333                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7334                 var row = SUGAR.email2.grid.getSelections()[0];
7335                 var ieid = row.data.ieId;
7336             var mbox = row.data.mbox;
7337         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7338         SUGAR.email2.contextMenus.assignmentDialog.hide();
7339                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7340
7341                 // AJAX Call
7342
7343         },
7344
7345         showEmailDetailView : function(o) {
7346         hideOverlay();
7347         var SED = SUGAR.email2.detailView;
7348                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7349
7350                 if(!SED.quickCreateDialog) {
7351                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7352                                 modal:true,
7353                                 visible:true,
7354                 //fixedcenter:true,
7355                 constraintoviewport: true,
7356                 draggable: true,
7357                                 autofillheight: "body",
7358                                 shadow  : true
7359                         });
7360                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7361                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7362                 var contH = 0;
7363                 for (var i in this.body.childNodes) {
7364                         if (this.body.childNodes[i].offsetHeight)
7365                                 contH += this.body.childNodes[i].offsetHeight;
7366                 }
7367                         this.body.style.overflow = "auto";
7368                         this.body.style.width = "800px";
7369                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7370                         this.center();
7371             }, SED.quickCreateDialog);
7372                 }
7373                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7374                 SED.quickCreateDialog.setBody(ret.html);
7375                 SED.quickCreateDialog.render();
7376         SUGAR.util.evalScript(ret.html);
7377         SED.quickCreateDialog.show();
7378         },
7379
7380         showAssignmentDialogWithData : function(o) {
7381         var SEC = SUGAR.email2.contextMenus;
7382                 hideOverlay();
7383         var ret = YAHOO.lang.JSON.parse(o.responseText);
7384         if (!SEC.assignmentDialog) {
7385                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7386                         visible:false,
7387                 fixedcenter:true,
7388                 constraintoviewport: true,
7389                         modal   : true
7390                 });
7391                 SEC.assignmentDialog.setBody("");
7392                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7393                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7394                 var iev = YAHOO.util.Dom.get("Distribute");
7395                 if (iev) {
7396                         this.body.style.width = "700px";
7397                 }
7398             },  SEC.assignmentDialog);
7399                 SEC.assignmentDialog.render();
7400         }
7401         SEC.assignmentDialog.setBody(ret);
7402         SEC.assignmentDialog.render();
7403         validate = [];
7404         SEC.assignmentDialog.show();
7405         SUGAR.util.evalScript(ret);
7406         },
7407
7408         showImportForm : function(o) {
7409                 var SED = SUGAR.email2.detailView;
7410                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7411         
7412         document.getElementById('quickCreateContent').innerHTML = "";
7413         hideOverlay();
7414         if (!ret) {
7415             return false;
7416         }
7417
7418         if(!SED.importDialog) {
7419             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7420                 modal:true,
7421                 visible:false,
7422                 fixedcenter:true,
7423                 constraintoviewport: true,
7424                 buttons : [{
7425                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7426                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7427                 }]//,
7428                 //scroll : true
7429             });
7430             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7431             SED.importDialog.setBody("");
7432             SED.importDialog.hideEvent.subscribe(function(){
7433                 for(var i in QSFieldsArray) {
7434                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7435                                 QSFieldsArray[i].destroy();
7436                                 delete QSFieldsArray[i];
7437                         }
7438                         if (QSProcessedFieldsArray[i]) {
7439                                 QSProcessedFieldsArray[i] = false;
7440                         } // if
7441                                 }
7442             });
7443             SED.importDialog.renderEvent.subscribe(function() {
7444                 var iev = YAHOO.util.Dom.get("ImportEditView");
7445                 if (iev) {
7446                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7447                         this.body.style.width = "600px";
7448                 }
7449             }, SED.importDialog);
7450             SED.importDialog.render();
7451         } // end lazy load
7452         SED.importDialog.setBody(ret.html);
7453         SED.importDialog.ret = ret;
7454         SUGAR.util.evalScript(ret.html);
7455         SED.importDialog.render();
7456         validate = [];
7457         SED.importDialog.show();
7458         SED.importDialog.focusFirstButton();
7459     },
7460     getImportAction : function(ret) {
7461         if (!check_form('ImportEditView')) return false;
7462         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7463                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7464                 return false;
7465         } // if
7466                 var get = "";
7467         var editView = document.getElementById('ImportEditView');
7468         if (editView.assigned_user_id != null) {
7469             get = get + "&user_id=" + editView.assigned_user_id.value
7470             //var user_id = editView.assigned_user_id.value;
7471         }
7472         var parent_id = editView.parent_id.value;
7473         var parent_type = editView.parent_type.value;
7474         var row = SUGAR.email2.grid.getSelectedRows()[0];
7475         row = SUGAR.email2.grid.getRecord(row);
7476         var data = row.getData();
7477         var ieId = data.ieId;
7478         var mbox = data.mbox;
7479         var serverDelete = editView.serverDelete.checked;
7480         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7481         var uids = "";
7482         for(i=0; i<emailUids.length; i++) {
7483             if(uids != '') {
7484                 uids += app_strings.LBL_EMAIL_DELIMITER;
7485             }
7486             uids += emailUids[i];
7487         }
7488
7489         var action = 'importEmail&uid=';
7490         if (ret.move) {
7491             action = 'moveEmails';
7492             action = action + '&sourceFolder=' + ret['srcFolder'];
7493             action = action + '&sourceIeId=' + ret['srcIeId'];
7494             action = action + '&destinationFolder=' + ret['dstFolder'];
7495             action = action + '&destinationIeId=' + ret['dstIeId'];
7496             action = action + '&emailUids=';
7497         }
7498         if (action.search(/importEmail/) != -1) {
7499             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7500         } else {
7501             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7502         }
7503
7504         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7505         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7506         SUGAR.email2.detailView.importDialog.hide();
7507         document.getElementById('importDialogContent').innerHTML = "";
7508
7509     },
7510     showRelateForm : function(o) {
7511         var SED = SUGAR.email2.detailView;
7512         var ret = YAHOO.lang.JSON.parse(o.responseText);
7513         document.getElementById('quickCreateContent').innerHTML = "";
7514         hideOverlay();
7515         if (!ret) {
7516             return false;
7517         }
7518         dialog_loaded = true;
7519
7520         if(!SED.relateDialog) {
7521             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7522                                 modal:true,
7523                                 visible:true,
7524                 fixedcenter:true,
7525                 width: '800px',
7526                 constraintoviewport: true,
7527                                 buttons : [{
7528                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7529                                         if (!check_form('RelateEditView')) return false;
7530                                         var get = "";
7531                         var editView = document.getElementById('RelateEditView');
7532                         var parent_id = editView.parent_id.value;
7533                         var parent_type = editView.parent_type.value;
7534                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7535                         row  = SUGAR.email2.grid.getRecord(row);
7536                         var ieId = row.getData().ieId;
7537                         var mbox = row.getData().mbox;
7538                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7539                         var uids = "";
7540                         for(i=0; i<emailUids.length; i++) {
7541                             if(uids != '') {
7542                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7543                             }
7544                             uids += emailUids[i];
7545                         }
7546                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7547                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7548                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7549                         SED.relateDialog.hide();
7550                         document.getElementById('relateDialogContent').innerHTML = "";
7551                         }
7552                 }]
7553                         });
7554
7555             SED.relateDialog.hideEvent.subscribe(function(){
7556                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7557                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7558                         delete QSFieldsArray['ImportEditView_parent_name'];
7559                 } // if
7560                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7561                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7562                                 } // if
7563             });
7564
7565             SED.relateDialog.renderEvent.subscribe(function() {
7566                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7567                 var contH = 0;
7568                 for (var i in this.body.childNodes) {
7569                         if (this.body.childNodes[i].clientHeight)
7570                                 contH += this.body.childNodes[i].clientHeight;
7571                 }
7572             }, SED.relateDialog);
7573             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7574                 } // end lazy load
7575
7576         SED.relateDialog.setBody(ret.html);
7577         SED.relateDialog.render();
7578         SUGAR.util.evalScript(ret.html);
7579         SED.relateDialog.show();
7580     }
7581 };
7582 /**
7583  * DetailView callbacks
7584  */
7585 AjaxObject.detailView.callback = {
7586         emailDetail : {
7587                 success : function(o) {
7588                         SUGAR.email2.o = o;
7589                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7590                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7591                 },
7592                 argument: [targetDiv],
7593                 failure : AjaxObject.handleFailure,
7594                 timeout : 0,
7595                 scope   : AjaxObject
7596         },
7597         emailPreview : {
7598                 success : function(o) {
7599                         SUGAR.email2.o = o;
7600                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7601                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7602                 },
7603                 failure : AjaxObject.handleFailure,
7604                 timeout : 0,
7605                 scope   : AjaxObject
7606         },
7607         viewPrint : {
7608                 success : AjaxObject.detailView.displayPrintable,
7609                 failure : AjaxObject.handleFailure,
7610                 timeout : AjaxObject.timeout,
7611                 scope   : AjaxObject
7612         },
7613         viewRaw : {
7614                 success : AjaxObject.detailView.displayView,
7615                 failure : AjaxObject.handleFailure,
7616                 timeout : AjaxObject.timeout,
7617                 scope   : AjaxObject
7618         }
7619 };
7620
7621
7622
7623
7624
7625 AjaxObject.folders = {
7626         /**
7627          * check-mail post actions
7628          */
7629         checkMailCleanup : function(o) {
7630                 hideOverlay();
7631                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7632
7633                 // refresh focus ListView
7634                 SE.listView.refreshGrid();
7635                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7636         },
7637
7638         /**
7639          */
7640         rebuildFolders : function(o) {
7641                 hideOverlay();
7642
7643                 var data = YAHOO.lang.JSON.parse(o.responseText);
7644
7645                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7646                 SUGAR.email2.folders.setSugarFolders();
7647         }
7648 };
7649 AjaxObject.folders.callback = {
7650         checkMail : {
7651                 success : AjaxObject.folders.checkMailCleanup,
7652                 failure : AjaxObject.handleFailure,
7653                 timeout : 600000, // 5 mins
7654                 scope   : AjaxObject
7655         }
7656 }
7657
7658 AjaxObject.rules = {
7659         loadRulesForSettings : function(o) {
7660                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7661                 // assume we have the class we need
7662                 SUGAR.routing.getStrings();
7663                 SUGAR.routing.getDependentDropdowns();
7664         }
7665 };
7666 ////    END PER MODULE CALLBACK OBJECTS
7667 ///////////////////////////////////////////////////////////////////////////
7668
7669
7670 var callback = {
7671         success : AjaxObject.handleSuccess,
7672         failure : AjaxObject.handleFailure,
7673         timeout : AjaxObject.timeout,
7674         scope   : AjaxObject
7675 };
7676 var callbackAccount = {
7677         success : AjaxObject.ieSaveSuccess,
7678         failure : AjaxObject.handleFailure,
7679         timeout : AjaxObject.timeout,
7680         scope   : AjaxObject
7681 };
7682 var callbackAccountDelete = {
7683         success : AjaxObject.ieDeleteSuccess,
7684         failure : AjaxObject.handleFailure,
7685         timeout : AjaxObject.timeout,
7686         scope   : AjaxObject
7687 };
7688 var callbackOutboundTest = {
7689         success : AjaxObject.ieSendSuccess,
7690         failure : AjaxObject.handleFailure,
7691         timeout : AjaxObject.timeout,
7692         scope   : AjaxObject
7693 };
7694
7695
7696
7697 var callbackTeamInfoForSettings = {
7698 success : function (o) {
7699         var data = YAHOO.lang.JSON.parse(o.responseText);
7700         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7701 },
7702 failure : AjaxObject.handleFailure,
7703 timeout : AjaxObject.timeout,
7704 scope   : AjaxObject
7705
7706 };
7707
7708 var callbackStatusForImport = {
7709 success : function (o) {
7710         hideOverlay();
7711         if (o.responseText != "")  {
7712                 var statusString = "";
7713                 var data = YAHOO.lang.JSON.parse(o.responseText);
7714                 for(i=0; i<data.length; i++) {
7715                         statusString = statusString + data[i] + '<br/>';
7716                 }
7717                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7718         }
7719         SE.listView.refreshGrid();
7720
7721 },
7722 failure : AjaxObject.handleFailure,
7723 timeout : AjaxObject.timeout,
7724 scope   : AjaxObject
7725
7726 };
7727 var callbackComposeCache = {
7728         success : AjaxObject.composeCache,
7729         failure : AjaxObject.handleFailure,
7730         timeout : AjaxObject.timeout,
7731         scope   : AjaxObject
7732 };
7733 var callbackDelete = {
7734         success : AjaxObject.handleDeleteReturn,
7735         failure : AjaxObject.handleFailure,
7736         timeout : AjaxObject.timeout,
7737         scope   : AjaxObject
7738 };
7739 var callbackEmailDetailMultiple = {
7740         success : function(o) {
7741                 hideOverlay();
7742                 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7743                 var ret = new Object();
7744
7745                 for(var i=0; i<retMulti.length; i++) {
7746                         ret = retMulti[i];
7747
7748                         SUGAR.email2._setDetailCache(ret);
7749                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7750                 }
7751         },
7752         failure : AjaxObject.handleFailure,
7753         timeout : 0,
7754         scope   : AjaxObject
7755 };
7756 var callbackListViewSortOrderChange = {
7757         success : AjaxObject.saveListViewSortOrderPart2,
7758         failure : AjaxObject.handleFailure,
7759         timeout : AjaxObject.timeout,
7760         scope   : AjaxObject,
7761         argument        : [ieId, ieName, focusFolder]
7762 };
7763 var callbackEmptyTrash = {
7764         success : function(o) {
7765                 hideOverlay();
7766                 AjaxObject.folderRenameCleanup;
7767         },
7768         failure : AjaxObject.handleFailure,
7769         timeout : AjaxObject.timeout,
7770         scope   : AjaxObject
7771 };
7772 var callbackClearCacheFiles = {
7773         success : function(o) {
7774                 hideOverlay();
7775         },
7776         failure : AjaxObject.handleFailure,
7777         timeout : AjaxObject.timeout,
7778         scope   : AjaxObject
7779 };
7780 var callbackFolderRename = {
7781         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7782         failure : AjaxObject.handleFailure,
7783         timeout : AjaxObject.timeout,
7784         scope   : AjaxObject
7785 };
7786 var callbackFolderDelete = {
7787         success : function(o) {
7788                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7789                 if (ret.status) {
7790                     if (ret.folder_id) {
7791                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7792                         if(node)
7793                                 SUGAR.email2.tree.removeNode(node, true);
7794                     } else if (ret.ieId && ret.mbox) {
7795                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7796                         if(node)
7797                                 SUGAR.email2.tree.removeNode(node, true);
7798                     }
7799                         hideOverlay();
7800                         //SUGAR.email2.folders.loadSettingFolder();
7801                 } else {
7802                         hideOverlay();
7803                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7804                 } // else
7805         },
7806         failure : AjaxObject.handleFailure,
7807         timeout : AjaxObject.timeout,
7808         scope   : AjaxObject
7809 };
7810 var callbackFolderSave = {
7811         success : function(o) {
7812                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7813
7814                 switch(ret.action) {
7815                         case 'newFolderSave':
7816                                 SUGAR.email2.folders.rebuildFolders();
7817                         break;
7818                 }
7819         },
7820         failure : AjaxObject.handleFailure,
7821         timeout : AjaxObject.timeout,
7822         scope   : AjaxObject
7823 };
7824 var callbackFolderSubscriptions = {
7825         success : AjaxObject.updateFolderSubscriptions,
7826         failure : AjaxObject.handleFailure,
7827         timeout : AjaxObject.timeout,
7828         scope   : AjaxObject
7829 };
7830 var callbackFolderUpdate = {
7831         success : AjaxObject.updateFrameFolder,
7832         failure : AjaxObject.handleFailure,
7833         timeout : AjaxObject.timeout,
7834         scope   : AjaxObject
7835 };
7836 var callbackFolders = {
7837         success : AjaxObject.folders.rebuildFolders,
7838         //success : void(true),
7839         failure : AjaxObject.handleFailure,
7840         timeout : AjaxObject.timeout,
7841         scope   : AjaxObject
7842 };
7843 var callbackFullSync = {
7844         success : AjaxObject.fullSyncCleanup,
7845         failure : AjaxObject.handleFailure,
7846         timeout : 9999999999999,
7847         scope   : AjaxObject
7848 };
7849 var callbackGeneric = {
7850         success : function() {
7851                 hideOverlay();
7852         },
7853         failure : AjaxObject.handleFailure,
7854         timeout : AjaxObject.timeout,
7855         scope   : AjaxObject
7856 };
7857 var callbackIeAccountRetrieve = {
7858         success : function(o) {
7859                 // return JSON encoding
7860                 hideOverlay();
7861                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7862                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7863         },
7864         failure : AjaxObject.handleFailure,
7865         timeout : AjaxObject.timeout,
7866         scope   : AjaxObject
7867 };
7868 var callbackImportOneEmail = {
7869         success :  AjaxObject.detailView.showImportForm,
7870         failure : AjaxObject.handleFailure,
7871         timeout : AjaxObject.timeout,
7872         scope   : AjaxObject
7873 };
7874 var callbackRelateEmail = {
7875     success : AjaxObject.detailView.showRelateForm,
7876     failure : AjaxObject.handleFailure,
7877     timeout : AjaxObject.timeout,
7878     scope   : AjaxObject
7879 }
7880 var callbackEmailDetailView = {
7881     success : AjaxObject.detailView.showEmailDetailView,
7882     failure : AjaxObject.handleFailure,
7883     timeout : AjaxObject.timeout,
7884     scope   : AjaxObject
7885 }
7886 var callbackAssignmentDialog = {
7887         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7888         failure : AjaxObject.handleFailure,
7889         timeout : AjaxObject.timeout,
7890         scope   : AjaxObject
7891 };
7892 var callbackAssignmentAction = {
7893         success :  function(o) {
7894                 SE.listView.refreshGrid();
7895                 hideOverlay();
7896                 if(o.responseText != '') {
7897                overlay('Assignment action result', o.responseText, 'alert');
7898             } // if
7899         } ,
7900         failure : AjaxObject.handleFailure,
7901         timeout : AjaxObject.timeout,
7902         scope   : AjaxObject
7903 };
7904 var callbackMoveEmails = {
7905         success :  function(o) {
7906             SE.listView.refreshGrid();
7907                 hideOverlay();
7908                 if(o.responseText != '') {
7909                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7910             } // if
7911         } ,
7912         failure : AjaxObject.handleFailure,
7913         timeout : AjaxObject.timeout,
7914         scope   : AjaxObject
7915 };
7916 var callbackLoadAttachments = {
7917         success : AjaxObject.loadAttachments,
7918         failure : AjaxObject.handleFailure,
7919         timeout : AjaxObject.timeout,
7920         scope   : AjaxObject
7921 };
7922 var callbackLoadRules = {
7923         success : AjaxObject.rules.loadRulesForSettings,
7924         failure : AjaxObject.handleFailure,
7925         timeout : AjaxObject.timeout,
7926         scope   : AjaxObject
7927 };
7928 var callbackLoadSignature = {
7929         success : AjaxObject.loadSignature,
7930         failure : AjaxObject.handleFailure,
7931         timeout : AjaxObject.timeout,
7932         scope   : AjaxObject
7933 };
7934 var callbackDeleteSignature = {
7935         success : AjaxObject.handleDeleteSignature,
7936         failure : AjaxObject.handleFailure,
7937         timeout : AjaxObject.timeout,
7938         scope   : AjaxObject
7939 };
7940 /*var callbackMoveEmails = {
7941     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7942     failure : AjaxObject.handleFailure,
7943     timeout : AjaxObject.timeout,
7944     scope   : AjaxObject
7945 }*/
7946 var callbackOutboundSave = {
7947         success : AjaxObject.accounts.saveOutboundCleanup,
7948         failure : AjaxObject.handleFailure,
7949         timeout : AjaxObject.timeout,
7950         scope   : AjaxObject
7951 };
7952 var callbackDefaultOutboundSave = {
7953         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7954         failure : AjaxObject.handleFailure,
7955         timeout : AjaxObject.timeout,
7956         scope   : AjaxObject
7957 };
7958 var callbackQuickCreate = {
7959         success : AjaxObject.detailView.showQuickCreateForm,
7960         failure : AjaxObject.handleFailure,
7961         timeout : AjaxObject.timeout,
7962         scope   : AjaxObject
7963 };
7964 var callbackQuickCreateSave = {
7965         success : AjaxObject.detailView.saveQuickCreateForm,
7966         failure : AjaxObject.handleFailure,
7967         timeout : AjaxObject.timeout,
7968         scope   : AjaxObject
7969 };
7970 var callbackQuickCreateSaveAndAddToAddressBook = {
7971         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7972         failure : AjaxObject.handleFailure,
7973         timeout : AjaxObject.timeout,
7974         scope   : AjaxObject
7975 };
7976 var callbackQuickCreateSaveAndReply = {
7977     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7978     failure : AjaxObject.handleFailure,
7979     timeout : AjaxObject.timeout,
7980     scope   : AjaxObject
7981 }
7982 var callbackQuickCreateSaveAndReplyCase = {
7983     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7984     failure : AjaxObject.handleFailure,
7985     timeout : AjaxObject.timeout,
7986     scope   : AjaxObject
7987 }
7988 var callbackRebuildShowAccountList = {
7989         success : AjaxObject.rebuildShowFolders,
7990         failure : AjaxObject.handleFailure,
7991         timeout : AjaxObject.timeout,
7992         scope   : AjaxObject
7993 };
7994
7995 var callbackRefreshSugarFolders = {
7996         success : function(o) {
7997                 var t = YAHOO.lang.JSON.parse(o.responseText);
7998                 SUGAR.email2.folders.setSugarFoldersEnd(t);
7999         },
8000         failure : AjaxObject.handleFailure,
8001         timeout : AjaxObject.timeout,
8002         scope   : AjaxObject
8003 };
8004 var callbackReplyForward = {
8005         success : AjaxObject.handleReplyForward,
8006         finish : function(a, retryCount) {
8007                 if (typeof(retryCount) == 'undefined') {
8008                         retryCount = 0;
8009                 } else {
8010                         retryCount++;
8011                 }
8012                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8013                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8014         try {
8015                         var html = t.getContent();
8016
8017             html = "&nbsp;<div><hr></div>" + a.description;
8018
8019                         t.setContent(html);//
8020
8021             if (a.type != 'draft') {
8022                 // Next step, attach signature
8023                 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8024             }
8025
8026                 } catch(e) {
8027                         if (retryCount < 5) {
8028                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8029                                 return;
8030                         }
8031                 }
8032                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8033                 if (tabArray != null && tabArray.length > 0) {
8034                         for (i = 0 ; i < tabArray.length ; i++) {
8035                                 var tabObject = tabArray[i];
8036                                 if (tabObject.get("id") == ("composeTab" + idx)) {
8037                                         var tabLabel = a.name;
8038                                 if (tabLabel != null && tabLabel.length > 25) {
8039                                         tabLabel = tabLabel.substring(0, 25) + "...";
8040                                 } // if
8041                                         tabObject.get("labelEl").firstChild.data = tabLabel;
8042                                         break;
8043                                 }
8044                         }
8045                 }
8046
8047                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8048                 if (a.parent_name != null && a.parent_name != "") {
8049                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
8050                 }
8051                 if (a.parent_type != null && a.parent_type != "") {
8052                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
8053                 }
8054                 if (a.parent_id != null && a.parent_id != "") {
8055                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
8056                 }
8057                 if (a.fromAccounts.status) {
8058                         var addressFrom = document.getElementById('addressFrom' + idx);
8059                 SUGAR.email2.util.emptySelectOptions(addressFrom);
8060                 var fromAccountOpts = a.fromAccounts.data;
8061                 for(i=0; i<fromAccountOpts.length; i++) {
8062                       var key = fromAccountOpts[i].value;
8063                       var display = fromAccountOpts[i].text;
8064                       var opt = new Option(display, key);
8065                       if (fromAccountOpts[i].selected) {
8066                         opt.selected = true;
8067                       }
8068                       addressFrom.options.add(opt);
8069                 }
8070                 } // if
8071                 hideOverlay();
8072
8073         },
8074         failure : AjaxObject.handleFailure,
8075         timeout : AjaxObject.timeout,
8076         scope   : AjaxObject,
8077         argument        : [sendType]
8078 };
8079 var callbackSendEmail = {
8080         success : AjaxObject.sendEmailCleanUp,
8081         failure : AjaxObject.handleFailure,
8082         timeout : AjaxObject.timeout,
8083         scope   : AjaxObject
8084 };
8085 var callbackSettings = {
8086         success : AjaxObject.updateUserPrefs,
8087         failure : AjaxObject.handleFailure,
8088         timeout : AjaxObject.timeout,
8089         scope   : AjaxObject
8090 };
8091 var callbackSettingsFolderRefresh = {
8092         success : AjaxObject.settingsFolderRefresh,
8093         failure : AjaxObject.handleFailure,
8094         timeout : AjaxObject.timeout,
8095         scope   : AjaxObject
8096 };
8097 var callbackLoadSettingFolder = {
8098         success : function(o) {
8099                 AjaxObject.settingsFolderRefresh(o);
8100                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8101         },
8102         failure : AjaxObject.handleFailure,
8103         timeout : AjaxObject.timeout,
8104         scope   : AjaxObject
8105
8106 };
8107 var callbackUploadAttachment = {
8108         success : AjaxObject.uploadAttachmentSuccessful,
8109         upload  : AjaxObject.uploadAttachmentSuccessful,
8110         failure : AjaxObject.handleFailure,
8111         timeout : AjaxObject.timeout,
8112         scope   : AjaxObject
8113 };
8114 var callbackUserPrefs = {
8115         success : function(o) {
8116                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8117         },
8118         failure : AjaxObject.handleFailure,
8119         timeout : AjaxObject.timeout,
8120         scope   : AjaxObject
8121 };
8122
8123 var callbackContextmenus = {
8124         markUnread : {
8125                 success : AjaxObject.markEmailCleanup,
8126                 failure : AjaxObject.handleFailure,
8127                 timeout : AjaxObject.timeout,
8128                 scope   : AjaxObject
8129         }
8130 };
8131
8132 var callbackCheckEmail2 = {
8133         success : function(o) {
8134                 var ret = YAHOO.lang.JSON.parse(o.responseText);
8135                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8136
8137
8138         },
8139         failure : AjaxObject.handleFailure,
8140         timeout : AjaxObject.timeout,
8141         scope   : AjaxObject
8142 }// End of File modules/Emails/javascript/ajax.js
8143                                 
8144 /*********************************************************************************
8145  * SugarCRM Community Edition is a customer relationship management program developed by
8146  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8147  * 
8148  * This program is free software; you can redistribute it and/or modify it under
8149  * the terms of the GNU Affero General Public License version 3 as published by the
8150  * Free Software Foundation with the addition of the following permission added
8151  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8152  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8153  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8154  * 
8155  * This program is distributed in the hope that it will be useful, but WITHOUT
8156  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8157  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8158  * details.
8159  * 
8160  * You should have received a copy of the GNU Affero General Public License along with
8161  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8162  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8163  * 02110-1301 USA.
8164  * 
8165  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8166  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8167  * 
8168  * The interactive user interfaces in modified source and object code versions
8169  * of this program must display Appropriate Legal Notices, as required under
8170  * Section 5 of the GNU Affero General Public License version 3.
8171  * 
8172  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8173  * these Appropriate Legal Notices must retain the display of the "Powered by
8174  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8175  * technical reasons, the Appropriate Legal Notices must display the words
8176  * "Powered by SugarCRM".
8177  ********************************************************************************/
8178
8179 function gridInit() {
8180         if(SUGAR.email2.grid) {
8181                 SUGAR.email2.grid.destroy();
8182         }
8183         
8184         e2Grid = {
8185                 init : function() {
8186                 
8187                         var Ck = YAHOO.util.Cookie;
8188                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8189
8190                         if (Ck.get("EmailGridWidths")) {
8191                                 for (var i=0; i < widths.length; i++) {
8192                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8193                                 }
8194                         } else {
8195                                 for (var i=0; i < widths.length; i++) {
8196                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8197                                 }
8198                         }
8199                         
8200                         // changes "F" to an icon
8201                         function flaggedIcon(cell, record, column, value) {
8202                                 if(value != "") {
8203                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8204                                 }
8205                         }
8206                         // changes "A" to replied icon
8207                         function repliedIcon(cell, record, column, value) {
8208                                 if(value != "") {
8209                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8210                                 }
8211                         }
8212                 function attachIcon(cell, record, column, value) {
8213                                 if(value == "1") {
8214                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8215                                 }
8216                         }
8217
8218                         var colModel = 
8219                                 [
8220                                         {
8221                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8222                                                 width: 10, 
8223                                                 sortable: false, 
8224                                                 fixed: true,
8225                                                 resizeable: true,
8226                                                 formatter: attachIcon,
8227                                                 key: 'hasAttach'
8228                                         }, 
8229                                     {
8230                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8231                                                 width: widths[0], 
8232                                                 sortable: true, 
8233                                                 fixed: true,
8234                                                 resizeable: true,
8235                                                 formatter: flaggedIcon,
8236                                                 key: 'flagged'
8237                                         }, 
8238                                         {
8239                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8240                                                 width: widths[1], 
8241                                                 sortable: true, 
8242                                                 fixed: true,
8243                                                 resizeable: true,
8244                                                 formatter: repliedIcon,
8245                                                 key: 'status'
8246                                         },
8247                                         {
8248                                                 label: app_strings.LBL_EMAIL_FROM, 
8249                                                 width: widths[2],
8250                                                 sortable: true,
8251                                                 resizeable: true,
8252                                                 key: 'from'
8253                                         }, 
8254                                         {
8255                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8256                                                 width: widths[3], 
8257                                                 sortable: true,
8258                                                 resizeable: true,
8259                                                 key: 'subject'
8260                                         }, 
8261                                         {
8262                                                 label: mod_strings.LBL_LIST_DATE,
8263                                                 width: widths[4], 
8264                                                 sortable: true,
8265                                                 resizeable: true,
8266                         key: 'date'
8267                                         }, 
8268                                         {
8269                                                 label: app_strings.LBL_EMAIL_TO,
8270                                                 width: widths[5], 
8271                                                 sortable: false,
8272                                                 resizeable: true,
8273                         key: 'to_addrs'
8274                                         }, 
8275                                         {
8276                                                 label: 'uid',
8277                                                 hidden: true,
8278                         key: 'uid'
8279                                         }, 
8280                                         {
8281                                                 label: 'mbox',
8282                                                 hidden: true,
8283                         key: 'mbox'
8284                                         }, 
8285                                         {
8286                                                 label: 'ieId',
8287                                                 hidden: true,
8288                         key: 'ieId'
8289                                         }, 
8290                                         {       
8291                                                 label: 'site_url',
8292                                                 hidden: true,
8293                         key: 'site_url'
8294                                         },
8295                                         {       label: 'seen',
8296                                                 hidden: true,
8297                         key: 'seen'
8298                                         },
8299                                         {       label: 'type',
8300                                                 hidden: true,
8301                         key: 'type'
8302                                         }
8303                                 ];
8304                         
8305                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8306                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8307                                 responseSchema: {
8308                                     resultsList: 'Email',
8309                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8310                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8311                                 }
8312                     });
8313                         var params = {
8314                                         to_pdf : "true",
8315                                         module : "Emails",
8316                                         action : "EmailUIAjax",
8317                                         emailUIAction : "getMessageList",
8318                                         mbox : "INBOX",
8319                                         ieId : "",
8320                                         forceRefresh : "false"
8321                         };
8322                         if(lazyLoadFolder != null) {
8323                                 params['mbox'] = lazyLoadFolder.folder;
8324                                 params['ieId'] = lazyLoadFolder.ieId;
8325                                 //Check if the folder is a Sugar Folder
8326                                 var test = new String(lazyLoadFolder.folder);
8327                                 if(test.match(/SUGAR\./)) {
8328                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8329                                         params['mbox'] = test.substr(6);
8330                                 }
8331                         }
8332                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8333         
8334                         // create the Grid
8335                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8336                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8337                                 dynamicData: true,
8338                                 paginator: new YAHOO.widget.Paginator({ 
8339                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8340                                         containers : ["dt-pag-nav"],
8341                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8342                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8343                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8344                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8345                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8346                                 }),
8347                                 initialRequest:SUGAR.util.paramsToUrl(params),
8348                                 width:  "800px",
8349                                 height: "400px"
8350                         });
8351
8352                         initRowDD();
8353
8354                         //Override Paging request construction
8355                         grid.set("generateRequest", function(oState, oSelf) {
8356                     oState = oState || {pagination:null, sortedBy:null};
8357                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8358                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8359                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8360                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8361                     // Build the request 
8362                     var ret = 
8363                             SUGAR.util.paramsToUrl(oSelf.params) + 
8364                             "&sort=" + sort +
8365                         "&dir=" + dir +
8366                         "&start=" + startIndex +
8367                         ((results !== null) ? "&limit=" + results : "");
8368                     return  ret;
8369                 });
8370                         
8371                         
8372                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8373                                 oPayload = oPayload || { };
8374                                 
8375                                 oPayload.totalRecords = oResponse.meta.total;
8376                                 oPayload.unreadRecords = oResponse.meta.unread;
8377                                 
8378                         var tabObject = SE.innerLayout.get("tabs")[0];
8379                         var mboxTitle = "";
8380                         if (this.params.mbox != null) {
8381                                 mboxTitle = this.params.mbox;
8382                         }
8383                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8384                         tabObject.get("labelEl").firstChild.data = tabtext;
8385                         
8386                         if (SE.tree) {
8387                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8388                                 if (node) {
8389                                         node.data.unseen = oResponse.meta.unread;
8390                                         SE.accounts.renderTree();
8391                                 }
8392                         }
8393                                 return oPayload; 
8394                         }
8395                         
8396                         var resize = grid.resizeGrid = function () {
8397                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8398                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8399                         }
8400                         grid.convertDDRows = function() {
8401                                 var rowEl = this.getFirstTrEl();
8402                                 while (rowEl != null) {
8403                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8404                                         rowEl = this.getNextTrEl(rowEl);
8405                                 }
8406                         }
8407                         
8408                         
8409                         grid.on("columnResizeEvent", function(o) {
8410                                 //Find the index of the column
8411                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8412                                 for (var i=0; i < colSet.length; i++) {
8413                                         if (o.column == colSet[i]) {
8414                                                 //Store it in the cookie
8415                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8416                                         }
8417                                 }
8418                                 //this.resizeGrid();
8419                         }, null, grid); 
8420                         
8421                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8422                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8423                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8424                         grid.render();
8425                         SUGAR.email2.listViewLayout.on("render", resize);
8426                         resize();
8427                         
8428                         //Setup the default load parameters
8429                         SUGAR.email2.grid.params = params;
8430                         
8431                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8432                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8433                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8434                 }
8435         };
8436         e2Grid.init();
8437 };
8438
8439
8440 function initRowDD() {
8441         var sg = SUGAR.email2.grid,
8442         Dom = YAHOO.util.Dom;
8443         sg.DDRow = function(oDataTable, oRecord, elTr) {
8444                 if(oDataTable && oRecord && elTr) {
8445                         this.ddtable = oDataTable;
8446                 this.table = oDataTable.getTableEl();
8447                 this.row = oRecord;
8448                 this.rowEl = elTr;
8449                 this.newIndex = null;
8450                 this.init(elTr);
8451                 this.initFrame(); // Needed for DDProxy
8452                 this.invalidHandleTypes = {};
8453             }   
8454         };
8455         
8456         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8457             _resizeProxy: function() {
8458                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8459                 var dragEl = this.getDragEl(),
8460                     el = this.getEl();
8461                 var xy = Dom.getXY(el);
8462                 
8463                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8464                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8465                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8466                 Dom.setStyle(dragEl, 'display', "");
8467             },
8468             
8469             startDrag: function(x, y) { 
8470                 //Check if we should be dragging a set of rows rather than just the one.
8471                 var selectedRows = this.ddtable.getSelectedRows();
8472                 var iSelected = false;
8473                 for (var i in selectedRows) {
8474                         if (this.rowEl.id == selectedRows[i]) {
8475                                 iSelected = true;
8476                                 break
8477                         }
8478                 }
8479                 if (iSelected) {
8480                         this.rows = [];
8481                         for (var i in selectedRows) {
8482                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8483                         }
8484                 } else {
8485                         this.rows = [this.row];
8486                         this.ddtable.unselectAllRows();
8487                         this.ddtable.selectRow(this.row);
8488                 }
8489                 
8490                 //Initialize the dragable proxy
8491                 var dragEl = this.getDragEl(); 
8492                 var clickEl = this.getEl(); 
8493                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8494                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8495                 Dom.addClass(dragEl, "yui-dt-liner");
8496                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8497                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8498                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8499                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8500             },
8501             
8502             clickValidator: function(e) {
8503                 if (this.row.getData()[0] == " ")
8504                         return false;
8505                 var target = YAHOO.util.Event.getTarget(e);
8506                 return ( this.isValidHandleChild(target) && 
8507                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8508             },
8509             /**
8510              * This funciton checks that the target of the drag is a table row in this
8511              * DDGroup and simply moves the sourceEL to that location as a preview.
8512              */
8513             onDragOver: function(ev, id) {
8514                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8515                 if (node && node != this.targetNode) {
8516                         this.targetNode = node;
8517                         SUGAR.email2.folders.unhighliteAll();
8518                         node.highlight();
8519                 }
8520             },
8521             
8522             onDragOut: function(e, id) {
8523                 if (this.targetNode) {
8524                         SUGAR.email2.folders.unhighliteAll();
8525                         this.targetNode = false;
8526                 }
8527             },
8528             endDrag: function() {
8529                 Dom.setStyle(this.getEl(), "opacity", "");
8530                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8531                 if (this.targetNode) {
8532                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8533                 }
8534                 SUGAR.email2.folders.unhighliteAll();
8535                 this.rows = null;
8536             }
8537         });
8538 }
8539
8540 function AddressSearchGridInit() {
8541     function moduleIcon(elCell, oRecord, oColumn, oData) {
8542         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8543     };
8544     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8545         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8546     };
8547     var checkHeader = '<input type="checkbox" ';
8548     if (SUGAR.email2.util.isIe()) {
8549         checkHeader += 'style="top:-5px" ';
8550     }
8551     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8552     var colModel = 
8553             [{
8554                 label: checkHeader,
8555             width: 30,
8556             formatter: selectionCheckBox,
8557             key: 'bean_id'
8558         },
8559             {
8560                 label: mod_strings.LBL_LIST_TYPE,
8561                 width: 25,
8562                 formatter: moduleIcon,
8563                 key: 'bean_module'
8564         },
8565             {
8566                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8567                 width: 180,
8568                 sortable: true,
8569                 key: 'name'
8570             }, 
8571             {
8572                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8573                 width: 300, 
8574                 sortable: true,
8575                 key: 'email'
8576             }];
8577     
8578     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8579                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8580         responseSchema: {
8581             resultsList: 'Person',
8582             fields: ['name', 'email', 'bean_id', 'bean_module'],
8583                     metaFields: {total: 'TotalCount'}
8584         },
8585         //enable sorting on the server accross all data
8586         remoteSort: true
8587     });
8588     dataModel.params = {
8589                 to_pdf          : true,
8590                 module          : "Emails",
8591                 action          : "EmailUIAjax",
8592                 emailUIAction:"getAddressSearchResults"
8593     }
8594     var rb = document.getElementById('hasRelatedBean').checked;
8595         if (rb) {
8596                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8597                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8598                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8599                 dataModel.params['related_bean_id'] = relatedBeanId;
8600                 dataModel.params['related_bean_type'] = relatedBeanType;
8601                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8602         }
8603     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8604     
8605     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8606         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8607                 dynamicData: true,
8608                 paginator: new YAHOO.widget.Paginator({ 
8609                         rowsPerPage: 25,  
8610                         containers : ["dt-pag-nav-addressbook"],
8611                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8612                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8613                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8614                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8615                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8616                 }),
8617                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8618                 width:  "560px",
8619                 height: "250px"
8620     });
8621         //Override Paging request construction
8622         grid.set("generateRequest", function(oState, oSelf) {
8623         oState = oState || {pagination:null, sortedBy:null};
8624         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8625         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8626         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8627         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8628         // Build the request 
8629         var ret = 
8630             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8631             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8632             ((results !== null) ? "&limit=" + results : "");
8633         return  ret;
8634     });
8635     
8636         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8637                 oPayload = oPayload || { };
8638                 oPayload.totalRecords = oResponse.meta.total;
8639                 return oPayload; 
8640         }
8641         
8642         grid.clickToggleSelect= function(args) {
8643                 var isIE = (args.event.target == null);
8644                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8645                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8646                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8647                 }
8648         }
8649         
8650         grid.reSelectRowsOnRender = function (){
8651             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8652         for (var i = 0; i < rows.length; i++) 
8653         {
8654                 var emailAddress = rows[i].getData("email");
8655             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8656             if(alreadyAdded)
8657             {
8658                 rows[i].setData("selected",  true);
8659                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8660             }
8661             else
8662             {
8663                 rows[i].setData("selected",  false);
8664                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8665             }
8666         }
8667         }
8668         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8669         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8670         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8671     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8672     
8673     grid.render();
8674     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8675     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8676     
8677     grid.toggleSelectCheckbox = function(id,checked){
8678         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8679         row.setData("checked",checked);
8680     };
8681     grid.toggleSelect = function(id, checked) {
8682         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8683         checked = row.getData("selected");
8684         if (!checked)
8685         {
8686             SUGAR.email2.addressBook.grid.selectRow(row);
8687             SE.addressBook.insertContactRowToResultTable(id,null)
8688         } else 
8689         {
8690             SUGAR.email2.addressBook.grid.unselectRow(row);
8691             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8692         }
8693         row.setData("selected", !checked);
8694     };
8695     
8696     grid.toggleSelectAll = function(checked) {
8697         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8698         for (var i = 0; i < rows.length; i++) {
8699                         if (typeof(rows[i]) != "undefined")
8700                                 rows[i].setData("checked",  checked);
8701         }
8702         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8703         for (var i = 0; i < checkBoxes.length; i++) {
8704             checkBoxes[i].checked = checked;
8705         }
8706     };
8707     
8708     //Initialize the grid result table.
8709     AddressSearchResultsGridInit();
8710 }
8711
8712
8713
8714 /**
8715 *  Initalize the results table for the address book selection.
8716 *
8717 */
8718 function AddressSearchResultsGridInit()
8719 {
8720     
8721     /* Full name sort funciton to compare by last name if available */
8722     var fullNameSort = function(a, b, desc) {
8723         // Deal with empty values
8724         if(!YAHOO.lang.isValue(a))
8725             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8726         else if(!YAHOO.lang.isValue(b))
8727             return -1;
8728
8729         var aNames = a.getData("name").split(' ');
8730         var bNames = b.getData("name").split(' ');
8731
8732         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8733         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8734
8735         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8736
8737     };
8738     
8739     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8740                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8741                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8742               
8743     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})},
8744                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8745      
8746      var myDataSource = new YAHOO.util.DataSource([]); 
8747          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8748          myDataSource.responseSchema = { 
8749                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8750                 };                                                                 
8751     
8752          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8753                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8754     
8755      var highlightEditableCell = function(oArgs) {
8756             var elCell = oArgs.target;
8757             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8758                 this.highlightCell(elCell);
8759             }
8760         };
8761       
8762      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8763      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8764      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8765      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8766          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8767      
8768      //Setup the context menus
8769      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8770              var task = p_aArgs[1]; 
8771              if(task) 
8772              { 
8773                  var elRow = this.contextEventTarget; 
8774                  elRow = p_myDataTable.getTrEl(elRow); 
8775          
8776                  if(elRow) 
8777                  { 
8778                      switch(task.index) 
8779                      { 
8780                          case 0:     
8781                              var oRecord = p_myDataTable.getRecord(elRow); 
8782                              p_myDataTable.deleteRow(elRow);  
8783                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8784                      } 
8785                  } 
8786              } 
8787          };
8788      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8789                         {trigger:gridResults.getTbodyEl()}); 
8790          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8791          contextMenu.render("addrSearchResultGrid"); 
8792          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8793 }
8794 // End of File modules/Emails/javascript/grid.js
8795                                 
8796 /*********************************************************************************
8797  * SugarCRM Community Edition is a customer relationship management program developed by
8798  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8799  * 
8800  * This program is free software; you can redistribute it and/or modify it under
8801  * the terms of the GNU Affero General Public License version 3 as published by the
8802  * Free Software Foundation with the addition of the following permission added
8803  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8804  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8805  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8806  * 
8807  * This program is distributed in the hope that it will be useful, but WITHOUT
8808  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8809  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8810  * details.
8811  * 
8812  * You should have received a copy of the GNU Affero General Public License along with
8813  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8814  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8815  * 02110-1301 USA.
8816  * 
8817  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8818  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8819  * 
8820  * The interactive user interfaces in modified source and object code versions
8821  * of this program must display Appropriate Legal Notices, as required under
8822  * Section 5 of the GNU Affero General Public License version 3.
8823  * 
8824  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8825  * these Appropriate Legal Notices must retain the display of the "Powered by
8826  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8827  * technical reasons, the Appropriate Legal Notices must display the words
8828  * "Powered by SugarCRM".
8829  ********************************************************************************/
8830
8831
8832 /******************************************************************************
8833  * Initialize Email 2.0 Application
8834  */
8835
8836 //Override Sugar Languge so quick creates work properly
8837
8838
8839 function email2init() {
8840
8841         //Init Tiny MCE
8842     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8843     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8844     if (!SUGAR.util.isTouchScreen()) {
8845          tinyMCE.init({
8846                  convert_urls : false,
8847          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8848          width: tinyConfig.width,
8849          theme: tinyConfig.theme,
8850          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8851          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8852          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8853          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8854          plugins : tinyConfig.plugins,
8855          elements : tinyConfig.elements,
8856          language : tinyConfig.language,
8857          extended_valid_elements : tinyConfig.extended_valid_elements,
8858          mode: tinyConfig.mode,
8859          strict_loading_mode : true,
8860                  force_br_newlines : true,
8861          forced_root_block : '',
8862          directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8863      });
8864     }
8865
8866     // initialze message overlay
8867     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8868             //iframe        : true,
8869             modal       : false,
8870             autoTabs    : true,
8871             width       : 300,
8872             height      : 120,
8873             shadow      : true
8874         }
8875     );
8876         // Hide Sugar menu
8877         if (SUGAR.themes.tempHideLeftCol)
8878         SUGAR.themes.tempHideLeftCol();
8879
8880         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8881 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8882
8883         // set defaults for YAHOO.util.DragDropManager
8884         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8885
8886         SUGAR.email2.nextYear = new Date();
8887         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8888
8889         
8890     // initialize and display UI framework (complexLayout.js)
8891     complexLayoutInit();
8892     
8893     // initialize and display grid (grid.js)
8894     gridInit();
8895     
8896     // initialize treeview for folders
8897         //onloadTreeinit();
8898         SUGAR.email2.folders.rebuildFolders(true);
8899         
8900         
8901     //Setup the Message Box overlay
8902     /*Ext.MessageBox.maxWidth = 350;
8903     Ext.MessageBox.minProgressWidth = 350;
8904
8905         ///////////////////////////////////////////////////////////////////////////
8906         ////    CONTEXT MENUS
8907         // detailView array
8908         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8909 */
8910         var SEC = SUGAR.email2.contextMenus; 
8911         
8912         //Grid menu
8913         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8914                 trigger: SUGAR.email2.grid.get("element"),
8915                 lazyload: true
8916         });
8917         emailMenu.subscribe("beforeShow", function() {
8918                 var oTarget = this.contextEventTarget;
8919                 if (typeof(oTarget) == "undefined")
8920                   return;
8921                 var grid = SUGAR.email2.grid;
8922                 var selectedRows = grid.getSelectedRows();
8923                 var multipleSelected = (selectedRows.length > 1) ? true: false;
8924                 if (!multipleSelected)
8925                 {
8926                         grid.unselectAllRows();
8927                         grid.selectRow(oTarget);
8928                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
8929                 }
8930                 else if(multipleSelected)
8931                 {
8932                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8933                 }
8934         });
8935         
8936         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8937         //us to access individual elements easier by name rather than by index
8938         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
8939                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8940         emailMenu.addItems([
8941         {
8942             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8943             id: 'showDetailView',
8944             onclick: { fn: SEC.showDetailView }
8945         },
8946         {
8947             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8948             onclick: { fn: SEC.openMultiple }
8949         },
8950         {
8951             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8952             onclick: { fn: SEC.archiveToSugar }
8953         },
8954         {
8955             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8956             id: 'reply',
8957             onclick: { fn: SEC.replyForwardEmailContext }
8958         },
8959         {
8960             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8961             id: 'replyAll',
8962             onclick: { fn: SEC.replyForwardEmailContext }
8963         },
8964         {
8965             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8966             id: 'forward',
8967             onclick: { fn: SEC.replyForwardEmailContext }
8968         },
8969         {
8970             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8971             id: 'delete',
8972             onclick: { fn: SEC.markDeleted }
8973         },
8974         {
8975             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8976             id: 'print',
8977             onclick: { fn: SEC.viewPrintable }
8978         },                
8979         // Mark... submenu
8980         {
8981             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8982             submenu: {
8983                         id: "markEmailMenu",
8984                 itemdata : [
8985                     {
8986                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
8987                         onclick: { fn: SEC.markUnread }
8988                     },
8989                     {
8990                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
8991                         onclick: { fn: SEC.markRead }
8992                     },
8993                     {
8994                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
8995                         onclick: { fn: SEC.markFlagged }
8996                     },
8997                     {
8998                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
8999                         onclick: {  fn: SEC.markUnflagged }
9000                     }
9001                 ]
9002             }
9003          },
9004         {
9005             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9006                 id: 'assignTo',
9007                 onclick: { fn: SEC.assignEmailsTo }
9008          },
9009          {
9010             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9011             id: 'relateTo',
9012             onclick: { fn: SEC.relateTo }
9013          }
9014     ]);
9015         SEC.emailListContextMenu.render();
9016         
9017         //Handle the Tree folder menu trigger ourselves
9018         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9019
9020         
9021         //Folder Menu
9022     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9023                 trigger: "",
9024                 lazyload: true 
9025         });
9026     SEC.frameFoldersContextMenu.addItems([
9027                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9028                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9029                         onclick: {  fn: function() {
9030                         var node = SUGAR.email2.clickedFolderNode;
9031                         if (node.data.ieId) {
9032                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9033                     }}
9034                 },
9035                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9036                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9037                         onclick: {  fn: function() {
9038                         var node = SUGAR.email2.clickedFolderNode;
9039                         if (node.data.ieId) {
9040                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9041                     }}
9042                 },
9043                 {
9044                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9045                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9046                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9047                 },
9048                 {
9049                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9050                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9051                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9052                 },
9053                 {
9054                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9055                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9056                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9057                  },
9058                  {
9059                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9060                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9061                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9062                   },
9063                  {
9064                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9065                     onclick: {  fn: function() {
9066                         var node = SUGAR.email2.clickedFolderNode;
9067                         if (node.data.ieId) {
9068                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9069                     }}
9070                   } 
9071         ]);
9072     SEC.frameFoldersContextMenu.render();
9073     
9074     SEC.initContactsMenu = function() {
9075         // contacts
9076         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9077                 trigger: "contacts",
9078                 lazyload: true
9079         });
9080         SEC.contactsContextMenu.addItems([
9081                 {
9082                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9083                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9084                 },
9085                 {
9086                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9087                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9088                 }
9089         ]);
9090         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9091                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9092                 if (oTarget && !grid.isSelected(oTarget)) {
9093                         grid.unselectAllRows();
9094                         grid.selectRow(oTarget);
9095                 }
9096         });
9097         SEC.contactsContextMenu.render();
9098         }
9099         
9100         
9101         // set auto-check timer
9102         SUGAR.email2.folders.startCheckTimer();
9103         // check if we're coming from an email-link click
9104         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9105         
9106         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9107         
9108         //Init fix for YUI 2.7.0 datatable sort.
9109         SUGAR.email2.addressBook.initFixForDatatableSort();
9110 }
9111
9112 function createTreePanel(treeData, params) {
9113         var tree = new YAHOO.widget.TreeView(params.id);
9114         var root = tree.getRoot();
9115         
9116         //if (treeData.nodes && treeData[0].id == "Home")
9117         //      treeData = treeData[0];
9118         return tree;
9119 }
9120
9121 function addChildNodes(parentNode, parentData) {
9122         var Ck = YAHOO.util.Cookie;
9123         var nextyear = SUGAR.email2.nextYear;
9124         var nodes = parentData.nodes || parentData.children;
9125         for (i in nodes) {
9126                 if (typeof(nodes[i]) == 'object') {
9127                         if (nodes[i].data) {
9128                 // See comment about href below.
9129                                 // nodes[i].data.href = '#';
9130                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9131                                 node.action = nodes[i].data.action;
9132                         } else {
9133                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9134                                         addChildNodes(parentNode, nodes[i]);
9135                                         return;
9136                                 }
9137                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9138                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9139                                 if (nodes[i].cls) {
9140                                         nodes[i].className = nodes[i].cls;
9141                                 }
9142                 // Previously, span was added in the label so it was rendering in the tree.
9143                 // Default behavior is to wrap in span if no href property, and since this href
9144                 // doesn't do anything, remove it so that it will be wrapped in spans.
9145                 // nodes[i].href = "#";
9146                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9147                                 //Override YUI child node creation
9148                                 if (nodes[i].children) {
9149                                         nodes[i].nodes = nodes[i].children;
9150                                         nodes[i].children = [ ];
9151                                 }
9152                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9153                         }
9154                         
9155                         if (typeof(nodes[i].nodes) == 'object') {
9156                                 addChildNodes(node, nodes[i]);
9157                         }
9158                 }
9159         }
9160 }
9161
9162 /**
9163  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9164  */
9165 function email2treeinit(tree, treedata, treediv, params) {
9166         //ensure the tree data is not corrupt
9167         if (!treedata) {
9168            return;
9169         }
9170         if (SUGAR.email2.tree) {
9171                 SUGAR.email2.tree.destroy();
9172                 SUGAR.email2.tree = null;
9173         }
9174         
9175         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9176                 id: 'emailtree'
9177         });
9178         
9179         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9180         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9181         tree.subscribe("expandComplete", function(node){
9182                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9183                 for (var i in node.children) {
9184                         SE.accounts.setupDDTarget(node.children[i]);
9185                 }
9186         });
9187         tree.setCollapseAnim("TVSlideOut");
9188         tree.setExpandAnim("TVSlideIn");
9189         var root = tree.root;
9190         while (root.hasChildren()) {
9191                 var node = root.children[0];
9192                 node.destroy();
9193                 tree.removeNode(root.children[0], false);
9194         }
9195         addChildNodes(root, treedata);
9196         tree.render();
9197         SUGAR.email2.accounts.renderTree();
9198 }
9199
9200 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9201         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9202 };
9203
9204
9205 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9206     startDrag: function(x, y) {
9207                 var Dom = YAHOO.util.Dom;       
9208                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9209                 
9210                 this.dragId = "";
9211                 var dragEl = this.getDragEl();  
9212         var clickEl = this.getEl(); 
9213         Dom.setStyle(clickEl, "color", "#AAA");
9214         Dom.setStyle(clickEl, "opacity", "0.25"); 
9215         dragEl.innerHTML = clickEl.innerHTML; 
9216          
9217         Dom.addClass(dragEl, "ygtvcell");
9218         Dom.addClass(dragEl, "ygtvcontent");
9219         Dom.addClass(dragEl, "folderDragProxy");
9220         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9221         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9222         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9223         Dom.setStyle(dragEl, "opacity", "0.5"); 
9224             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9225     },
9226     
9227     onDragOver: function(ev, id) {
9228         var Dom = YAHOO.util.Dom;
9229         if (id != this.dragId)
9230         {
9231                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9232                 if(node.data.cls != "sugarFolder") {
9233                         SUGAR.email2.folders.unhighliteAll();
9234                         return;
9235                 }
9236                 this.dragId = id;
9237                 this.targetNode = node;
9238                 SUGAR.email2.folders.unhighliteAll();
9239                 node.highlight();
9240         }
9241     },
9242     
9243     onDragOut: function(e, id) {
9244         if (this.targetNode) {
9245                 SUGAR.email2.folders.unhighliteAll();
9246                 this.targetNode = false;
9247                 this.dragId = false;
9248         }
9249     },
9250     
9251     endDrag: function() { 
9252         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9253         if (this.targetNode) {
9254                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9255         }
9256     }
9257 });// End of File modules/Emails/javascript/init.js
9258                                 
9259 /*********************************************************************************
9260  * SugarCRM Community Edition is a customer relationship management program developed by
9261  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9262  * 
9263  * This program is free software; you can redistribute it and/or modify it under
9264  * the terms of the GNU Affero General Public License version 3 as published by the
9265  * Free Software Foundation with the addition of the following permission added
9266  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9267  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9268  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9269  * 
9270  * This program is distributed in the hope that it will be useful, but WITHOUT
9271  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9272  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9273  * details.
9274  * 
9275  * You should have received a copy of the GNU Affero General Public License along with
9276  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9277  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9278  * 02110-1301 USA.
9279  * 
9280  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9281  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9282  * 
9283  * The interactive user interfaces in modified source and object code versions
9284  * of this program must display Appropriate Legal Notices, as required under
9285  * Section 5 of the GNU Affero General Public License version 3.
9286  * 
9287  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9288  * these Appropriate Legal Notices must retain the display of the "Powered by
9289  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9290  * technical reasons, the Appropriate Legal Notices must display the words
9291  * "Powered by SugarCRM".
9292  ********************************************************************************/
9293
9294 /**
9295   Complex layout init
9296  */
9297 function complexLayoutInit() {
9298         var se = SUGAR.email2;
9299         var Dom = YAHOO.util.Dom;
9300         se.e2Layout = {
9301         getInnerLayout : function(rows) {
9302                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9303                 parent: se.complexLayout,  
9304                         border:true,
9305                     hideOnLayout: true,
9306                     height: 400,
9307                                 units: [{
9308                                         position: "center",
9309                                     scroll:false, // grid should autoScroll itself
9310                                     split:true,
9311                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9312                                 },{
9313                                         position: "bottom",
9314                                     scroll:true,
9315                                     collapse: false,
9316                                     resize: true,
9317                                     useShim:true,
9318                                     height:'250',
9319                                     body: "<div id='listBottom' />"
9320                                 },{
9321                                     position: "right",
9322                                     scroll:true,
9323                                     collapse: false,
9324                                     resize: true,
9325                                     useShim:true,
9326                                     width:'250',
9327                                     body: "<div id='listRight' />",
9328                                     titlebar: false //,header: "right"
9329                                 }]
9330             });
9331                 se.complexLayout.on("render", function(){
9332                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9333                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9334                                 SUGAR.email2.listViewLayout.set("height", height);
9335                                 SUGAR.email2.listViewLayout.render();
9336                 });
9337             se.listViewLayout.render();
9338             //CSS hack for now
9339             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9340             var rp = se.listViewLayout.resizePreview = function() {
9341                 var pre = Dom.get("displayEmailFramePreview");
9342                 if (pre) {
9343                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9344                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9345                 }
9346             };
9347             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9348             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9349             se.e2Layout.setPreviewPanel(rows);
9350             se.previewLayout = se.listViewLayout;
9351             return se.listViewLayout;
9352         },
9353         
9354         getInnerLayout2Rows : function() {
9355             return this.getInnerLayout(true);
9356         },
9357         getInnerLayout2Columns : function() {
9358             return this.getInnerLayout(false);
9359         },
9360         
9361         init : function(){
9362             // initialize state manager, we will use cookies
9363 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9364                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9365                 se.complexLayout = new YAHOO.widget.Layout("container", {
9366                         border:true,
9367                 hideOnLayout: true,
9368                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9369                 width: Dom.getViewportWidth() - 40,
9370                 units: [{
9371                         position: "center",
9372                     scroll:false,
9373                     body: "<div id='emailtabs'></div>"
9374                 },
9375                 {
9376                         position: "left",
9377                         scroll: true,
9378                         body: "<div id='lefttabs'></div>",
9379                     collapse: true,
9380                     width: 210,
9381                     minWidth: 100,
9382                     resize:true,
9383                     useShim:true,
9384                     titlebar: true,
9385                     header: "&nbsp;"
9386                 },
9387                 {
9388                     header: Dom.get('footerLinks').innerHTML,
9389                                         position: 'bottom',
9390                                         id: 'mbfooter',
9391                                         height: 22,
9392                                         border: false
9393                 }]
9394             });
9395                 se.complexLayout.render();
9396                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9397                         tp.addTab(new YAHOO.widget.Tab({ 
9398                                 label: "Inbox",
9399                                 scroll : true,
9400                                 content : "<div id='listViewDiv'/>",
9401                                 id : "center",
9402                                 active : true
9403                         }));
9404                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9405                         tp.appendTo(centerEl);
9406                         //CSS hack for now
9407                         tp.get("element").style.borderRight = "1px solid #666"
9408                         
9409                         var listV =  this.getInnerLayout2Rows();
9410                         listV.set("height", tp.get("element").clientHeight - 25);
9411                         listV.render();
9412             
9413             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9414             var folderTab = new YAHOO.widget.Tab({ 
9415                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9416                                 scroll : true,
9417                                 content : "<div id='emailtree'/>",
9418                                 id : "tree",
9419                                 active : true
9420                         });
9421             folderTab.on("activeChange", function(o){ 
9422                 if (o.newValue) {
9423                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9424                 }
9425             });
9426             se.leftTabs.addTab(folderTab);
9427             
9428             var tabContent = SUGAR.util.getAndRemove("searchTab");
9429             var searchTab = new YAHOO.widget.Tab({ 
9430                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9431                                 scroll : true,
9432                                 content : tabContent.innerHTML,
9433                                 id : tabContent.id
9434                         });
9435             searchTab.on("activeChange", function(o){ 
9436                 if (o.newValue) 
9437                 {
9438                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9439                    //Setup the calendars if needed
9440                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9441                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9442                    
9443                        //Initalize sqs object for assigned user name 
9444                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
9445                        
9446                        //Attach event handler for when the relate module option is selected for the correct sqs object
9447                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9448                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9449                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
9450                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9451                        
9452                        //If enter key is pressed, perform search
9453                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9454                        for(var i=0; i < addKeyPressFields.length;i++)
9455                        {
9456                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9457                                 if (e.keyCode == 13) {
9458                                         YAHOO.util.Event.stopEvent(e);
9459                                         SUGAR.email2.search.searchAdvanced();
9460                                 }
9461                        });
9462                        }
9463                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
9464                        enableQS(true);
9465                        //Clear parent values if selecting another parent type.
9466                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
9467                            function(){ 
9468                                document.getElementById('data_parent_id_search').value =''; 
9469                                document.getElementById('data_parent_name_search').value =''; 
9470                            });
9471                 
9472                 }
9473             });
9474             se.leftTabs.addTab(searchTab);
9475             
9476             var resizeTabBody = function() {
9477                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9478                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9479             }
9480             resizeTabBody();
9481             se.complexLayout.on("render", resizeTabBody);
9482             se.leftTabs.on("activeTabChange", resizeTabBody);
9483                         //hack to allow left pane scroll bar to fully show
9484                 var lefttabsDiv = document.getElementById('lefttabs');
9485                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9486                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9487                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9488           
9489         },
9490         initSQSObject: function(formName,fieldName)
9491         {
9492             var fullFieldName = formName + '_' + fieldName; //SQS Convention
9493             var resultName = fullFieldName + '_' + 'results';
9494             
9495             if (QSFieldsArray[fullFieldName] != null) 
9496             {
9497                 QSFieldsArray[fullFieldName].destroy();
9498                 delete QSFieldsArray[fullFieldName];
9499             }
9500             if (QSProcessedFieldsArray[fullFieldName])
9501             QSProcessedFieldsArray[fullFieldName] = false;
9502
9503             if( Dom.get(resultName) )
9504             {
9505                 var obj = document.getElementById(resultName);
9506                 obj.parentNode.removeChild(obj);
9507             }
9508         },
9509         setPreviewPanel: function(rows) {
9510                 if (rows) {
9511                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9512                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9513                 Dom.get("listRight").innerHTML = "";
9514                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9515             } else {
9516                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9517                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9518                 Dom.get("listBottom").innerHTML = "";
9519                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9520             }
9521         }
9522     };
9523         se.e2Layout.init();
9524 }
9525
9526 var myBufferedListenerObject = new Object();
9527 myBufferedListenerObject.refit = function() {
9528     if(SUGAR.email2.grid) {
9529         SUGAR.email2.grid.autoSize();
9530     }
9531 }
9532 // End of File modules/Emails/javascript/complexLayout.js
9533                                 
9534 /*********************************************************************************
9535  * SugarCRM Community Edition is a customer relationship management program developed by
9536  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9537  * 
9538  * This program is free software; you can redistribute it and/or modify it under
9539  * the terms of the GNU Affero General Public License version 3 as published by the
9540  * Free Software Foundation with the addition of the following permission added
9541  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9542  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9543  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9544  * 
9545  * This program is distributed in the hope that it will be useful, but WITHOUT
9546  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9547  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9548  * details.
9549  * 
9550  * You should have received a copy of the GNU Affero General Public License along with
9551  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9552  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9553  * 02110-1301 USA.
9554  * 
9555  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9556  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9557  * 
9558  * The interactive user interfaces in modified source and object code versions
9559  * of this program must display Appropriate Legal Notices, as required under
9560  * Section 5 of the GNU Affero General Public License version 3.
9561  * 
9562  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9563  * these Appropriate Legal Notices must retain the display of the "Powered by
9564  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9565  * technical reasons, the Appropriate Legal Notices must display the words
9566  * "Powered by SugarCRM".
9567  ********************************************************************************/
9568
9569 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9570 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9571 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9572 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9573 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9574 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9575 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9576 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9577 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9578 '               <input type="hidden" id="composeType" name="composeType">' +
9579 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9580 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9581 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9582 '               <input type="hidden" id="sendTo" name="sendTo">' +
9583 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9584 '               <input type="hidden" id="sendCc" name="sendCc">' +
9585 '               <input type="hidden" id="setEditor" name="setEditor">' +
9586 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9587 '               <input type="hidden" id="parent_id" name="parent_id">' +
9588 '               <input type="hidden" id="parent_type" name="parent_type">' +
9589 '               <input type="hidden" id="attachments" name="attachments">' +
9590 '               <input type="hidden" id="documents" name="documents">' +
9591 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9592 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9593 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9594 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9595 '                       <tr>' +
9596 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9597 '                                       <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>' +
9598 '                                       <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>' +
9599 '                                       <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>' +
9600 '                                       <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>' +
9601 '</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>' + 
9602 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9603 '<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>' +
9604 '                       </td></tr></tbody></table></th>'     +
9605 '                       </tr>' +
9606 '                       <tr>' +
9607 '                               <td>' +
9608 '                                       <div style="margin:5px;">' +
9609 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9610 '                                               <tr>' +
9611 '                                                       <td class="emailUILabel" NOWRAP >' +
9612 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9613 '                                                       </td>' +
9614 '                                                       <td class="emailUIField" NOWRAP>' +
9615 '                                                               <div>' +
9616 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9617 '                                                               </div>' +
9618 '                                                       </td>' +
9619 '                                               </tr>' +
9620 '                                               <tr>' +
9621 '                                                       <td class="emailUILabel" NOWRAP>' +
9622 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9623 '                                   {app_strings.LBL_EMAIL_TO}:' +
9624 '                               </button>' + 
9625 '                                                       </td>' +
9626 '                                                       <td class="emailUIField" NOWRAP>' +
9627 '                                                               <div class="ac_autocomplete">' +
9628 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9629 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9630 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9631 '                                                               </div>' +
9632 '                                                       </td>' +
9633 '                                               </tr>' +
9634 '                                               <tr id="add_addr_options_tr{idx}">' +
9635 '                                                       <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>'+
9636 '                                               </tr>'+
9637 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9638 '                                                       <td class="emailUILabel" NOWRAP>' +
9639 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9640 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9641 '                               </button>' + 
9642 '                                                       </td>' +
9643 '                                                       <td class="emailUIField" NOWRAP>' +
9644 '                                                               <div class="ac_autocomplete">' +
9645 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9646 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9647 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9648 '                                                               </div>' +
9649 '                                                       </td>' +
9650 '                                               </tr>' +
9651 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9652 '                                                       <td class="emailUILabel" NOWRAP>' +
9653 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9654 '                               {app_strings.LBL_EMAIL_BCC}:' +
9655 '                               </button>' + 
9656 '                                                       </td>' +
9657 '                                                       <td class="emailUIField" NOWRAP>' +
9658 '                                                               <div class="ac_autocomplete">' +
9659 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9660 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9661 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9662 '                                                               </div>' +
9663 '                                                       </td>' +
9664 '                                               </tr>' +
9665 '                                               <tr>' +
9666 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9667 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9668 '                                                       </td>' +
9669 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9670 '                                                               <div class="ac_autocomplete">' +
9671 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9672 '                                                               </div>' +
9673 '                                                       </td>' +
9674 '                                               </tr>' +
9675 '                                       </table>' +
9676 '                                       </div>' +
9677 '                               </td>'   +
9678 '                       </tr>' +
9679 '               </table>' +
9680 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9681 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9682 '                       <div style="padding:5px;">' +
9683 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9684 '                                       <tr>' +
9685 '                                               <th>' +
9686 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9687 '                                                       <br />' +
9688 '                                                       &nbsp;' +
9689 '                                               </th>' +
9690 '                                       </tr>' +
9691 '                                       <tr>' +
9692 '                                               <td>' +
9693 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9694 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9695 '                                               </td>' +
9696 '                                       </tr>' +
9697 '                                       <tr>' +
9698 '                                               <td>' +
9699 '                                                       &nbsp;' +
9700 '                                                       <br />' +
9701 '                                                       &nbsp;' +
9702 '                                               </td>' +
9703 '                                       </tr>' +
9704 '                                       <tr>' +
9705 '                                               <th>' +
9706 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9707 '                                                       <br />' +
9708 '                                                       &nbsp;' +
9709 '                                               </th>' +
9710 '                                       </tr>' +
9711 '                                       <tr>' +
9712 '                                               <td>' +
9713 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9714 '                                                       <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>' +
9715 '                                               </td>' +
9716 '                                       </tr>' +
9717 '                                       <tr>' +
9718 '                                               <td>' +
9719 '                                                       &nbsp;' +
9720 '                                                       <br />' +
9721 '                                                       &nbsp;' +
9722 '                                               </td>' +
9723 '                                       </tr>' +
9724 '                                       <tr>' +
9725 '                                               <th>' +
9726 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9727 '                                                       <br />' +
9728 '                                                       &nbsp;' +
9729 '                                               </th>' +
9730 '                                       </tr>' +
9731 '                                       <tr>' +
9732 '                                               <td>' +
9733 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9734 '                                               </td>' +
9735 '                                       </tr>' +
9736 '                               </table>' +
9737 '                       </div>' +
9738 '               </div>' +
9739 '       </form>' +
9740 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9741 '             <div style="padding:5px;">' +
9742 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9743 '                               <table border="0" width="100%">' +
9744 '                                       <tr>' +
9745 '                                               <td NOWRAP style="padding:2px;">' +
9746 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9747 '                                               </td>' +
9748 '                                       </tr>' +
9749 '                                       <tr>' +
9750 '                                               <td NOWRAP style="padding:2px;">' +
9751 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9752 '                                               </td>' +
9753 '                                       </tr>' +
9754 '                               </table>' +
9755 '                               <br />' +
9756 '                               <table border="0" width="100%">' +
9757 '                                       <tr>' +
9758 '                                               <td NOWRAP style="padding:2px;">' +
9759 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9760 '                                               </td>' +
9761 '                                       </tr>' +
9762 '                                       <tr>' +
9763 '                                               <td NOWRAP style="padding:2px;">' +
9764 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9765 '                                               </td>' +
9766 '                                       </tr>' +
9767 '                               </table>' +
9768 '                               <table border="0" width="100%">' +
9769 '                                       <tr>' +
9770 '                                               <td NOWRAP style="padding:2px;">' +
9771 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9772 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9773 '                                               </td>' +
9774 '                                       </tr>' +
9775 '                               </table>' +
9776 '         </form>' +
9777 '                       </div> ' +
9778 '               </div>' +
9779 '</div>';
9780 // End of File modules/Emails/javascript/composeEmailTemplate.js
9781                                 
9782 /*********************************************************************************
9783  * SugarCRM Community Edition is a customer relationship management program developed by
9784  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9785  * 
9786  * This program is free software; you can redistribute it and/or modify it under
9787  * the terms of the GNU Affero General Public License version 3 as published by the
9788  * Free Software Foundation with the addition of the following permission added
9789  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9790  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9791  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9792  * 
9793  * This program is distributed in the hope that it will be useful, but WITHOUT
9794  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9795  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9796  * details.
9797  * 
9798  * You should have received a copy of the GNU Affero General Public License along with
9799  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9800  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9801  * 02110-1301 USA.
9802  * 
9803  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9804  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9805  * 
9806  * The interactive user interfaces in modified source and object code versions
9807  * of this program must display Appropriate Legal Notices, as required under
9808  * Section 5 of the GNU Affero General Public License version 3.
9809  * 
9810  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9811  * these Appropriate Legal Notices must retain the display of the "Powered by
9812  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9813  * technical reasons, the Appropriate Legal Notices must display the words
9814  * "Powered by SugarCRM".
9815  ********************************************************************************/
9816
9817 SUGAR.email2.templates['displayOneEmail'] = 
9818 '<div class="emailDetailTable" style="height:100%">' +
9819 '<div id="viewMenuDiv{idx}"></div>' + 
9820 '<div width="100%" class="displayEmailValue">' +
9821 '                                       <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>' +
9822 '                                       <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>' +
9823 '                                       <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>' +
9824 '                                       <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>' +
9825 '                                       <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>' +
9826 '                                       <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>' +
9827 '                                       <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>' +
9828 '                                       <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>' +
9829 '                                       <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>' +
9830 '</div>' +
9831 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9832 '                               <tr>' +
9833 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9834 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9835 '                                       </td>' +
9836 '                                       <td width="99%" class="displayEmailValue">' +
9837 '                                               {email.from_addr}' +
9838 '                                       </td>' +
9839 '                               </tr>' +
9840 '                               <tr>' +
9841 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9842 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9843 '                                       </td>' +
9844 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9845 '                                               <b>{email.name}</b>' +
9846 '                                       </td>' +
9847 '                               </tr>' +
9848 '                               <tr>' +
9849 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9850 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9851 '                                       </td>' +
9852 '                                       <td class="displayEmailValue">' +
9853 '                                               {email.date_start} {email.time_start}' +
9854 '                                       </td>' +
9855 '                               </tr>' +
9856 '                               <tr>' +
9857 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9858 '                                               {app_strings.LBL_EMAIL_TO}:' +
9859 '                                       </td>' +
9860 '                                       <td class="displayEmailValue">' +
9861 '                                               {email.toaddrs}' +
9862 '                                       </td>' +
9863 '                               </tr>' +
9864 '                               <tr>{meta.cc}</tr>' +
9865 '                               <tr>{email.attachments}</tr>' +
9866 '                       </table>' +
9867 '                       <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>' +
9868 //'                           {email.description}' +
9869 '</div>'
9870 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9871                                 
9872 /*********************************************************************************
9873  * SugarCRM Community Edition is a customer relationship management program developed by
9874  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9875  * 
9876  * This program is free software; you can redistribute it and/or modify it under
9877  * the terms of the GNU Affero General Public License version 3 as published by the
9878  * Free Software Foundation with the addition of the following permission added
9879  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9880  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9881  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9882  * 
9883  * This program is distributed in the hope that it will be useful, but WITHOUT
9884  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9885  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9886  * details.
9887  * 
9888  * You should have received a copy of the GNU Affero General Public License along with
9889  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9890  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9891  * 02110-1301 USA.
9892  * 
9893  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9894  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9895  * 
9896  * The interactive user interfaces in modified source and object code versions
9897  * of this program must display Appropriate Legal Notices, as required under
9898  * Section 5 of the GNU Affero General Public License version 3.
9899  * 
9900  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9901  * these Appropriate Legal Notices must retain the display of the "Powered by
9902  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9903  * technical reasons, the Appropriate Legal Notices must display the words
9904  * "Powered by SugarCRM".
9905  ********************************************************************************/
9906
9907 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9908 '<body onload="javascript:window.print();">' + 
9909 '<style>' + 
9910 'body {' + 
9911 '       margin: 0px;' + 
9912 '       font-family: helvetica, impact, sans-serif;' +
9913 '       font-size : 12pt;' +
9914 '} ' +
9915 'table {' +
9916 '       padding:10px;' +
9917 '}' +
9918 '</style>' +
9919 '<div>' +
9920 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9921 '       <tr>' +
9922 '               <td>' +
9923 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9924 '                               <tr>' +
9925 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9926 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9927 '                                       </td>' +
9928 '                                       <td width="99%" class="displayEmailValue">' +
9929 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9930 '                                       </td>' +
9931 '                               </tr>' +
9932 '                               <tr>' +
9933 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9934 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9935 '                                       </td>' +
9936 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9937 '                                               <b>{email.name}</b>' +
9938 '                                       </td>' +
9939 '                               </tr>' +
9940 '                               <tr>' +
9941 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9942 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9943 '                                       </td>' +
9944 '                                       <td class="displayEmailValue">' +
9945 '                                               {email.date_start} {email.time_start}' +
9946 '                                       </td>' +
9947 '                               </tr>' +
9948 '                               <tr>' +
9949 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9950 '                                               {app_strings.LBL_EMAIL_TO}:' +
9951 '                                       </td>' +
9952 '                                       <td class="displayEmailValue">' +
9953 '                                               {email.toaddrs}' +
9954 '                                       </td>' +
9955 '                               </tr>' +
9956 '                               {email.cc}' +
9957 '                               {email.attachments}' +
9958 '                       </table>' +
9959 '               </td>' +
9960 '       </tr>' +
9961 '       <tr>' +
9962 '               <td>' +
9963 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9964 '                               <tr>' +
9965 '                                       <td style="border-top: 1px solid #333;">' +
9966 '                                               <div style="padding:5px;">' +
9967                                                         '{email.description}' +
9968 '                                               </div>' +
9969 '                                       </td>' +
9970 '                               </tr>' +
9971 '                       </table>' +
9972 '               </td>' +
9973 '       </tr>' +
9974 '</table>' +
9975 '</div>' +
9976 '</body></html>';
9977 // End of File modules/Emails/javascript/viewPrintable.js
9978                                 
9979 /*********************************************************************************
9980  * SugarCRM Community Edition is a customer relationship management program developed by
9981  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9982  *
9983  * This program is free software; you can redistribute it and/or modify it under
9984  * the terms of the GNU Affero General Public License version 3 as published by the
9985  * Free Software Foundation with the addition of the following permission added
9986  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9987  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9988  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9989  *
9990  * This program is distributed in the hope that it will be useful, but WITHOUT
9991  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9992  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9993  * details.
9994  *
9995  * You should have received a copy of the GNU Affero General Public License along with
9996  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9997  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9998  * 02110-1301 USA.
9999  *
10000  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
10001  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
10002  *
10003  * The interactive user interfaces in modified source and object code versions
10004  * of this program must display Appropriate Legal Notices, as required under
10005  * Section 5 of the GNU Affero General Public License version 3.
10006  *
10007  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
10008  * these Appropriate Legal Notices must retain the display of the "Powered by
10009  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
10010  * technical reasons, the Appropriate Legal Notices must display the words
10011  * "Powered by SugarCRM".
10012  ********************************************************************************/
10013 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10014 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;}
10015 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');}
10016 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;}}
10017 if(QSProcessedFieldsArray[qs_index_id]){continue;}
10018 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10019 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}
10020 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="";}}
10021 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10022 {search.clearFields=function(){};search.setFields=function(data,filter)
10023 {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])
10024 {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';}}}}
10025 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))
10026 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10027 {if(this.inputElement.id=='shipping_account_name')
10028 {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)/;}
10029 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10030 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10031 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];}}}
10032 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]];}
10033 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;}}}}});}
10034 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10035 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10036 // End of File include/javascript/quicksearch.js
10037