]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.2.0beta4
[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 is a customer relationship management program developed by
159  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
160  *
161  * This program is free software; you can redistribute it and/or modify it under
162  * the terms of the GNU Affero General Public License version 3 as published by the
163  * Free Software Foundation with the addition of the following permission added
164  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
167  *
168  * This program is distributed in the hope that it will be useful, but WITHOUT
169  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
171  * details.
172  *
173  * You should have received a copy of the GNU Affero General Public License along with
174  * this program; if not, see http://www.gnu.org/licenses or write to the Free
175  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
176  * 02110-1301 USA.
177  *
178  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
180  *
181  * The interactive user interfaces in modified source and object code versions
182  * of this program must display Appropriate Legal Notices, as required under
183  * Section 5 of the GNU Affero General Public License version 3.
184  *
185  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186  * these Appropriate Legal Notices must retain the display of the "Powered by
187  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188  * technical reasons, the Appropriate Legal Notices must display the words
189  * "Powered by SugarCRM".
190  ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span>&nbsp;</span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace('&#039;',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};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));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
226                                 
227 /*********************************************************************************
228  * SugarCRM is a customer relationship management program developed by
229  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
230  *
231  * This program is free software; you can redistribute it and/or modify it under
232  * the terms of the GNU Affero General Public License version 3 as published by the
233  * Free Software Foundation with the addition of the following permission added
234  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
237  *
238  * This program is distributed in the hope that it will be useful, but WITHOUT
239  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
241  * details.
242  *
243  * You should have received a copy of the GNU Affero General Public License along with
244  * this program; if not, see http://www.gnu.org/licenses or write to the Free
245  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
246  * 02110-1301 USA.
247  *
248  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
250  *
251  * The interactive user interfaces in modified source and object code versions
252  * of this program must display Appropriate Legal Notices, as required under
253  * Section 5 of the GNU Affero General Public License version 3.
254  *
255  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256  * these Appropriate Legal Notices must retain the display of the "Powered by
257  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258  * technical reasons, the Appropriate Legal Notices must display the words
259  * "Powered by SugarCRM".
260  ********************************************************************************/
261 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)
262 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_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 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;}
265 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();}
266 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';}
267 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='';}
268 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();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&&currentNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
277 currentNode.name=new_name;currentNode.id=new_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++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
280 arrow.value='show';}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
282 break;}}
283 if(!has_primary){return false;}
284 return true;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
287 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_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);}}}
291 divCount++;}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
294 return false;}}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 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'];for(var i in properties)
299 {if(e[properties[i]])
300 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
301 newNode[properties[i]]=e[properties[i]];}}
302 if(recursive)
303 {for(var i in e.childNodes)
304 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
305 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
306 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
307                                 
308 /*********************************************************************************
309  * SugarCRM is a customer relationship management program developed by
310  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
311  *
312  * This program is free software; you can redistribute it and/or modify it under
313  * the terms of the GNU Affero General Public License version 3 as published by the
314  * Free Software Foundation with the addition of the following permission added
315  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
316  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
317  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
318  *
319  * This program is distributed in the hope that it will be useful, but WITHOUT
320  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
321  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
322  * details.
323  *
324  * You should have received a copy of the GNU Affero General Public License along with
325  * this program; if not, see http://www.gnu.org/licenses or write to the Free
326  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
327  * 02110-1301 USA.
328  *
329  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
330  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
331  *
332  * The interactive user interfaces in modified source and object code versions
333  * of this program must display Appropriate Legal Notices, as required under
334  * Section 5 of the GNU Affero General Public License version 3.
335  *
336  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
337  * these Appropriate Legal Notices must retain the display of the "Powered by
338  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
339  * technical reasons, the Appropriate Legal Notices must display the words
340  * "Powered by SugarCRM".
341  ********************************************************************************/
342 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);}
343 return s;},init:function(){if(Rot13.map!=null)
344 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
345 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
346 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
347 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='';}
348 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='';}
349 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='';}}
350 return words;}
351 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName)
352 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
353 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
354 +'module='+module_name
355 +'&to_pdf=1'
356 +'&action='+action
357 +'&target='+pageTarget
358 +'&target1='+pageTarget
359 +'&server_url='+mail_server
360 +'&email_user='+words[0]
361 +'&protocol='+protocol
362 +'&port='+port
363 +'&email_password='+words[1]
364 +'&mailbox='+words[2]
365 +'&ssl='+ssl
366 +'&ie_id='+ie_id
367 +'&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)
368 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
369 this.body.style.width=w}}
370 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
371 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();}
372 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'));}
373 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
374 if(trim(formObject.email_password.value)==""&&trim(formObject.ie_id.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PASSWORD'));}
375 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
376 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
377 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
378 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";}
379 out+=errors[i];}
380 alert(out);return false;}else{return true;}}
381 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?'
382 +'module='+module_name
383 +'&to_pdf=1'
384 +'&action='+action
385 +'&target='+pageTarget
386 +'&target1='+pageTarget
387 +'&server_url='+mail_server
388 +'&email_user='+words[0]
389 +'&protocol='+protocol
390 +'&port='+port
391 +'&email_password='+words[1]
392 +'&mailbox='+words[2]
393 +'&ssl='+ssl
394 +'&personal='+isPersonal
395 +'&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)
396 this.body.style.width=w}}
397 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();}
398 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;}}}
399 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';}}}
400 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='';}
401 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";}}// End of File modules/InboundEmail/InboundEmail.js
402                                 
403 /*********************************************************************************
404  * SugarCRM is a customer relationship management program developed by
405  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
406  * 
407  * This program is free software; you can redistribute it and/or modify it under
408  * the terms of the GNU Affero General Public License version 3 as published by the
409  * Free Software Foundation with the addition of the following permission added
410  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
411  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
412  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
413  * 
414  * This program is distributed in the hope that it will be useful, but WITHOUT
415  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
416  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
417  * details.
418  * 
419  * You should have received a copy of the GNU Affero General Public License along with
420  * this program; if not, see http://www.gnu.org/licenses or write to the Free
421  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
422  * 02110-1301 USA.
423  * 
424  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
425  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
426  * 
427  * The interactive user interfaces in modified source and object code versions
428  * of this program must display Appropriate Legal Notices, as required under
429  * Section 5 of the GNU Affero General Public License version 3.
430  * 
431  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
432  * these Appropriate Legal Notices must retain the display of the "Powered by
433  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
434  * technical reasons, the Appropriate Legal Notices must display the words
435  * "Powered by SugarCRM".
436  ********************************************************************************/
437
438 SUGAR.email2 = {
439     cache : new Object(),
440     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
441     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
442     templates : {},
443     tinyInstances : {
444         currentHtmleditor : ''
445     },
446
447     /**
448      * preserves hits from email server
449      */ 
450     _setDetailCache : function(ret) {
451         if(ret.meta) {
452             var compKey = ret.meta.mbox + ret.meta.uid;
453
454             if(!SUGAR.email2.cache[compKey]) {
455                 SUGAR.email2.cache[compKey] = ret;
456             }
457         }
458     },
459
460     autoSetLayout : function() {
461         var c = document.getElementById('container');
462         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
463         //Ensure a minimum height.
464         tHeight = Math.max(tHeight, 550);
465         c.style.height = tHeight + "px";
466         SUGAR.email2.complexLayout.set('height', tHeight);
467         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
468         SUGAR.email2.complexLayout.render();
469         SUGAR.email2.listViewLayout.resizePreview();        
470     }
471 };
472
473 /**
474  * Shows overlay progress message
475  */
476 function overlayModal(title, body) {
477     overlay(title, body);
478 }
479 function overlay(reqtitle, body, type, additconfig) {
480     var config = { };
481     if (typeof(additconfig) == "object") {
482         var config = additconfig;
483     }
484     config.type = type;
485     config.title = reqtitle;
486     config.msg = body;
487     YAHOO.SUGAR.MessageBox.show(config);
488 };
489
490 function hideOverlay() {
491         YAHOO.SUGAR.MessageBox.hide();
492 };
493 // End of File modules/Emails/javascript/EmailUIShared.js
494                                 
495 /*********************************************************************************
496  * SugarCRM is a customer relationship management program developed by
497  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
498  * 
499  * This program is free software; you can redistribute it and/or modify it under
500  * the terms of the GNU Affero General Public License version 3 as published by the
501  * Free Software Foundation with the addition of the following permission added
502  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
503  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
504  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
505  * 
506  * This program is distributed in the hope that it will be useful, but WITHOUT
507  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
508  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
509  * details.
510  * 
511  * You should have received a copy of the GNU Affero General Public License along with
512  * this program; if not, see http://www.gnu.org/licenses or write to the Free
513  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
514  * 02110-1301 USA.
515  * 
516  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
517  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
518  * 
519  * The interactive user interfaces in modified source and object code versions
520  * of this program must display Appropriate Legal Notices, as required under
521  * Section 5 of the GNU Affero General Public License version 3.
522  * 
523  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
524  * these Appropriate Legal Notices must retain the display of the "Powered by
525  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
526  * technical reasons, the Appropriate Legal Notices must display the words
527  * "Powered by SugarCRM".
528  ********************************************************************************/
529
530
531 (function() {
532         var sw = YAHOO.SUGAR,
533                 Event = YAHOO.util.Event,
534                 Connect = YAHOO.util.Connect,
535             Dom = YAHOO.util.Dom
536             SE = SUGAR.email2;
537
538 ///////////////////////////////////////////////////////////////////////////////
539 ////    EMAIL ACCOUNTS
540 SE.accounts = {
541     outboundDialog : null,
542     inboundAccountEditDialog : null,
543     inboundAccountsSettingsTable : null,
544     outboundAccountsSettingsTable : null,
545     testOutboundDialog : null,
546     errorStyle : 'input-error',
547     normalStyle : '',
548     newAddedOutboundId : '',
549
550     /**
551      * makes async call to retrieve an outbound instance for editting
552      */
553      //EXT111
554     editOutbound : function(obi) {
555
556             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
557
558     },
559     deleteOutbound : function(obi) {
560
561         if(obi.match(/^(add|line|sendmail)+/)) {
562             alert('Invalid Operation');
563         } else {
564                 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
565             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
566         }
567     },
568     //EXT111
569     getReplyAddress : function() {
570         var primary = '';
571
572         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
573             var addy = SE.userPrefs.current_user.emailAddresses[i];
574
575             if(addy.primary_address == "1") {
576                 primary = addy.email_address;
577             }
578
579             if(addy.reply_to == "1") {
580                 return addy.email_address;
581             }
582         }
583
584         return primary;
585     },
586
587     /**
588      * Called on "Accounts" tab activation event
589      */
590     lazyLoad : function() {
591
592         this._setupInboundAccountTable();
593         this._setupOutboundAccountTable();
594
595     },
596
597     _setupInboundAccountTable: function()
598     {
599         //Setup the inbound mail settings
600         if(!this.inboundAccountsSettingsTable)
601         {
602                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
603                                         var clckEvent = oColumn.key;
604                                         var imgSrc = "";
605                                         var is_group = oRecord.getData("is_group");
606                                         if(!is_group)
607                                         {
608                                         if(oColumn.key == 'edit')
609                                         {
610                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
611                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
612                                         }
613                                         else if(oColumn.key == 'delete')
614                                         {
615                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
616                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
617                                         }
618                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
619                                         }
620                    };
621
622                    this.showBoolean = function(el, oRecord, oColumn, oData)
623                    {
624                        var is_group = oRecord.getData("is_group");
625                        var bChecked = oData;
626                        bChecked = (bChecked) ? " checked" : "";
627                        if(!is_group)
628                        {
629                        el.innerHTML = "<input type=\"radio\"" + bChecked +
630                            " name=\"col" + oColumn.getId() + "-radio\"" +
631                            " class=\"yui-dt-radio\">";
632                        }
633                    };
634
635
636                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
637                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
638
639                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
640                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
641                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
642
643
644                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
645                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
646                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
647                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
648                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
649                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
650                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
651                 this.ieDataSource = new YAHOO.util.DataSource(query);
652                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
653                         this.ieDataSource.responseSchema = {
654                                 resultsList: "account_list",
655                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
656                         };
657                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
658                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
659
660                     var elCheckbox = oArgs.target;
661                     var oColumn = this.getColumn(elCheckbox);
662                         if(oColumn.key == 'is_active')
663                         {
664                                 var oRecord = this.getRecord(elCheckbox);
665                                 oRecord.setData("is_active",elCheckbox.checked);
666                                 var t_id = oRecord.getData('id');
667                         var isGroupFolder = oRecord.getData('has_groupfolder');
668
669                         if(isGroupFolder)
670                             SUGAR.email2.folders.updateSubscriptions();
671                         else
672                         SUGAR.email2.folders.setFolderSelection();
673
674                         }
675                 });
676                         var lastDefaultSelectedId = "";
677                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
678
679                     var elRadio = oArgs.target;
680                     var oColumn = this.getColumn(elRadio);
681                         if(oColumn.key == 'is_default')
682                         {
683                                 var oRecord = this.getRecord(elRadio);
684                                 var t_id = oRecord.getData('id');
685                                 var t_isGroup = oRecord.getData('is_group');
686                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
687                                 {
688                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
689                                         lastDefaultSelectedId = t_id;
690                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
691                                 }
692                                 else if(t_isGroup)
693                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
694
695                         }
696                 });
697
698                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
699                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
700         }
701     },
702      _setupOutboundAccountTable: function()
703     {
704         if(!this.outboundAccountsSettingsTable)
705         {
706                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
707                                         var clckEvent = oColumn.key;
708                                         var imgSrc = "";
709                                         var isEditable = oRecord.getData("is_editable");
710                                         var type = oRecord.getData("type");
711                                         if(isEditable)
712                                         {
713                                         if(oColumn.key == 'edit')
714                                         {
715                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
716                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
717                                         }
718                                         else if(oColumn.key == 'delete' && type == 'user')
719                                         {
720                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
721                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
722                                         }
723                                         if(imgSrc != '')
724                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
725                                         }
726                 };
727
728                 //Custom formatter to display any error messages.
729                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
730
731                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
732                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
733
734                         var id = oRecord.getData('id');
735                                         var message = oRecord.getData("errors");
736                                         if(message != '')
737                                         {
738                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
739                                         //Add the id and message for all outbound accounts.
740                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
741                                         }
742                                         else
743                                         {
744                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
745                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
746                                         }
747                 };
748                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
749                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
750
751                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
752                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
753                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
754                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
755
756                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
757                 this.obDataSource = new YAHOO.util.DataSource(query);
758                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
759                         this.obDataSource.responseSchema = {
760
761                                 resultsList: "outbound_account_list",
762                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
763                         };
764
765                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
766
767
768                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
769                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
770                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
771         }
772     },
773     /**
774      * Displays a modal diaglogue to edit outbound account settings
775      */
776     showEditInboundAccountDialogue : function(clear) {
777
778         if(!this.inboundAccountEditDialog) {
779                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
780                 modal:true,
781                                 visible:true,
782                 fixedcenter:true,
783                 constraintoviewport: true,
784                 width   : "600px",
785                 shadow  : true
786             });
787                         EAD.showEvent.subscribe(function() {
788                 var el = this.element;
789                 var viewH = YAHOO.util.Dom.getViewportHeight();
790                 if (this.header && el && viewH - 50 < el.clientHeight) {
791                     var body = this.header.nextElementSibling;
792                                         body.style.overflow = "hidden";
793                     body.style.height = "100%";
794                 }
795             }, EAD);
796             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
797                         Dom.removeClass("editAccountDialogue", "yui-hidden");
798
799         } // end lazy load
800
801         if(clear == undefined || clear == true)
802         {
803                 SE.accounts.clearInboundAccountEditScreen();
804                 //Set default protocol to IMAP when creating new records
805                 document.forms['ieAccount'].elements['protocol'].value = "imap";
806                 SE.accounts.setPortDefault();
807         }
808
809         //Check if we should display username/password fields for outbound account if errors were detected.
810         this.checkOutBoundSelection();
811
812         this.inboundAccountEditDialog.render();
813         this.inboundAccountEditDialog.show();
814     },
815
816     /**
817     *  Set all fields on the outbound edit form to either enabled/disabled
818     *  except for the username/password.
819     *
820     */
821     toggleOutboundAccountDisabledFields: function(disable)
822     {
823         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
824         for(var i=0;i<fields.length;i++)
825         {
826             document.getElementById(fields[i]).disabled = disable;
827         }
828         if(disable)
829             Dom.addClass("mail_smtpssl_row", "yui-hidden");
830         else
831             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
832
833     },
834     /**
835     * Refresh the inbound accounts table.
836     */
837     refreshInboundAccountTable : function()
838     {
839             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
840                 {
841                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
842                                 scope: this.inboundAccountsSettingsTable }
843                         );
844     },
845     /**
846     * Refresh the outbound accounts table.
847     */
848     refreshOuboundAccountTable : function()
849     {
850             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
851                 {
852                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
853                                 scope: this.outboundAccountsSettingsTable }
854                         );
855     },
856     /**
857      * Displays a modal diaglogue to add a SMTP server
858      */
859     showAddSmtp : function() {
860         // lazy load dialogue
861         if(!this.outboundDialog) {
862                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
863                 modal:true,
864                                 visible:true,
865                 fixedcenter:true,
866                 constraintoviewport: true,
867                 width   : "750px",
868                 shadow  : true
869             });
870             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
871             this.outboundDialog.hideEvent.subscribe(function(){
872                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
873                 var out = Dom.get("outbound_email");
874                 if (out && out.value == "SYSTEM_ADD")
875                 {
876                         out.value = out.options[0].value;
877                 }
878                 //Check if we should display username/password for system account.
879                 SE.accounts.checkOutBoundSelection();
880                 return true;
881             });
882
883             Dom.removeClass("outboundDialog", "yui-hidden");
884         } // end lazy load
885
886         // clear out form
887         var form = document.getElementById('outboundEmailForm');
888         for(i=0; i<form.elements.length; i++) {
889             if(form.elements[i].name == 'mail_smtpport') {
890                 form.elements[i].value = 25;
891             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
892                 form.elements[i].value = '';
893             } else if(form.elements[i].type == 'checkbox') {
894                 form.elements[i].checked = false;
895             }
896         }
897         //Render the SMTP buttons
898         if ( !SUGAR.smtpButtonGroup ) {
899             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
900             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
901             {
902                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
903                 document.getElementById('smtp_settings').style.display = '';
904                 form.mail_smtptype.value = e.newValue.get('value');
905             });
906             YAHOO.widget.Button.addHiddenFieldsToForm(form);
907         }
908         //Hide Username/Password
909         SUGAR.email2.accounts.smtp_authenticate_field_display();
910         //Unset readonly fields
911         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
912         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
913                 this.outboundDialog.render();
914         this.outboundDialog.show();
915     },
916
917     /**
918      * Accounts' Advanced Settings view toggle
919      */
920     toggleAdv : function() {
921         var adv = document.getElementById("ie_adv");
922         if(adv.style.display == 'none') {
923             adv.style.display = "";
924         } else {
925             adv.style.display = 'none';
926         }
927     },
928
929         smtp_authenticate_field_display : function() {
930                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
931                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
932                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
933         },
934         
935         smtp_setDefaultSMTPPort : function() {
936                 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
937     
938         if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
939             document.getElementById("mail_smtpport").value = '465';
940         }
941         if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
942             document.getElementById("mail_smtpport").value = '25';
943         }
944         },
945
946     /**
947      * Changes the display used in the outbound email SMTP dialog to match the
948      */
949     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
950     {
951         document.getElementById("smtpButtonGroupTD").style.display = '';
952         document.getElementById("chooseEmailProviderTD").style.display = '';
953         document.getElementById("mailsettings1").style.display = '';
954         document.getElementById("mailsettings2").style.display = '';
955         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
956         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
957         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
958         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
959
960         switch (smtptype) {
961         case "yahoomail":
962             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
963             document.getElementById("mail_smtpport").value = '465';
964             document.getElementById("mail_smtpauth_req").checked = true;
965             var ssl = document.getElementById("mail_smtpssl");
966             for(var j=0;j<ssl.options.length;j++) {
967                 if(ssl.options[j].text == 'SSL') {
968                     ssl.options[j].selected = true;
969                     break;
970                 }
971             }
972             document.getElementById("mailsettings1").style.display = 'none';
973             document.getElementById("mailsettings2").style.display = 'none';
974             document.getElementById("mail_smtppass_label").innerHTML =
975             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
976             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
977             break;
978         case "gmail":
979             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
980             document.getElementById("mail_smtpport").value = '587';
981             document.getElementById("mail_smtpauth_req").checked = true;
982             var ssl = document.getElementById("mail_smtpssl");
983             for(var j=0;j<ssl.options.length;j++) {
984                 if(ssl.options[j].text == 'TLS') {
985                     ssl.options[j].selected = true;
986                     break;
987                 }
988             }
989             document.getElementById("mailsettings1").style.display = 'none';
990             document.getElementById("mailsettings2").style.display = 'none';
991             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
992             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
993             break;
994         case "exchange":
995             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
996                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
997                 document.getElementById("mail_smtpserver").value = '';
998             }
999             document.getElementById("mail_smtpport").value = '25';
1000             document.getElementById("mail_smtpauth_req").checked = true;
1001             document.getElementById("mailsettings1").style.display = '';
1002             document.getElementById("mailsettings2").style.display = '';
1003             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1004             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1005             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1006             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1007             break;
1008         }
1009         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1010         {
1011             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1012             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1013             document.getElementById("mailsettings2").style.display = 'none';
1014         }
1015
1016         SUGAR.email2.accounts.smtp_authenticate_field_display();
1017         SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1018     },
1019
1020     /**
1021     * Fill the gmail default values for inbound accounts.
1022     */
1023     fillInboundGmailDefaults: function () {
1024
1025         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1026         document.forms['ieAccount'].elements['ssl'].checked = true;
1027         document.forms['ieAccount'].elements['protocol'].value = "imap";
1028         SUGAR.email2.accounts.setPortDefault();
1029     },
1030     /**
1031      * Sets Port field to selected protocol and SSL settings defaults
1032      */
1033     setPortDefault : function() {
1034         var prot = document.getElementById('protocol');
1035         var ssl  = document.getElementById('ssl');
1036         var port = document.getElementById('port');
1037         var stdPorts= new Array("110", "143", "993", "995");
1038         var stdBool    = new Boolean(false);
1039         var mailboxdiv = document.getElementById("mailboxdiv");
1040         var trashFolderdiv = document.getElementById("trashFolderdiv");
1041         var sentFolderdiv = document.getElementById("sentFolderdiv");
1042                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1043         if(port.value == '') {
1044             stdBool.value = true;
1045         } else {
1046             for(i=0; i<stdPorts.length; i++) {
1047                 if(stdPorts[i] == port.value) {
1048                     stdBool.value = true;
1049                 }
1050             }
1051         }
1052
1053         if(stdBool.value == true) {
1054             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1055                 port.value = "143";
1056             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1057                 port.value = '993';
1058             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1059                 port.value = '110';
1060             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1061                 port.value = '995';
1062             }
1063         }
1064
1065         if (prot.value == 'imap') {
1066                 mailboxdiv.style.display = "";
1067                 trashFolderdiv.style.display = "";
1068                 sentFolderdiv.style.display = "";
1069                 monitoredFolder.style.display = "";
1070                 if (document.getElementById('mailbox').value == "") {
1071                         document.getElementById('mailbox').value = "INBOX";
1072                 }
1073         } else {
1074                 mailboxdiv.style.display = "none";
1075                 trashFolderdiv.style.display = "none";
1076                 sentFolderdiv.style.display = "none";
1077                         monitoredFolder.style.display = "none";
1078                 document.getElementById('mailbox').value = "";
1079         } // else
1080     },
1081
1082     /**
1083      * Draws/removes red boxes around required fields.
1084      */
1085     ieAccountError : function(style) {
1086         document.getElementById('server_url').className = style;
1087         document.getElementById('email_user').className = style;
1088         document.getElementById('email_password').className = style;
1089         document.getElementById('protocol').className = style;
1090         document.getElementById('port').className = style;
1091     },
1092
1093     checkOutBoundSelection: function() {
1094         var select = Dom.get('outbound_email');
1095         if (!select || select.selectedIndex == -1) { return; }
1096
1097         var v = select.options[select.selectedIndex].value;
1098
1099         if(v == '')
1100         {
1101                 select.options[select.selectedIndex].selected = false;
1102                 v = select.options[0].value;
1103         }
1104         else if (v == 'SYSTEM_ADD')
1105                 SUGAR.email2.accounts.showAddSmtp();
1106
1107         var foundError = false;
1108         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1109                 for(i in errorAccounts)
1110                 {
1111                     if(v == i)
1112                     {
1113                         foundError = true;
1114                         break;
1115                     }
1116                 }
1117
1118                 //Should username/password fields for outbound account.
1119                 if(foundError)
1120                     this.toggleInboundOutboundFields(true);
1121                 else
1122                     this.toggleInboundOutboundFields(false);
1123
1124
1125
1126     },
1127     toggleInboundOutboundFields : function (display)
1128     {
1129         if(display)
1130         {
1131             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1132                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1133         }
1134         else
1135         {
1136             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1137                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1138         }
1139     },
1140     /**
1141      * rebuilds the select options for mailer options
1142      */
1143     rebuildMailerOptions : function() {
1144         var select = document.forms['ieAccount'].elements['outbound_email'];
1145         SE.util.emptySelectOptions(select);
1146
1147         //Get the available sugar mailers
1148         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1149
1150         for(i=0;i<a_outbound.length;i++)
1151         {
1152                 var t_record = a_outbound[i];
1153                 var key = t_record.getData('id');
1154                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1155
1156                 var opt = new Option(display, key);
1157                 select.options.add(opt);
1158                 if (key == SE.accounts.newAddedOutboundId) {
1159                         select.options.selectedIndex = i;
1160                 }
1161         }
1162
1163         select.options.add(new Option('',''));
1164         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1165         //Hide/Show username password fields if necessary.
1166         SE.accounts.checkOutBoundSelection();
1167     },
1168     /**
1169      * Empties all the fields in the accounts edit view
1170      */
1171     clearInboundAccountEditScreen:function() {
1172
1173         document.getElementById('ie_id').value = '';
1174         document.getElementById('ie_name').value = '';
1175         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1176         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1177         document.getElementById('reply_to_addr').value = '';
1178         document.getElementById('server_url').value = '';
1179         document.getElementById('email_user').value = '';
1180         document.getElementById('email_password').value = '';
1181         document.getElementById('port').value = '';
1182         document.getElementById('inbound_mail_smtpuser').value = '';
1183         document.getElementById('inbound_mail_smtppass').value = '';
1184         document.ieAccount.protocol.options[0].selected = true;
1185         // handle SSL
1186         document.getElementById('ssl').checked = false;
1187
1188     },
1189
1190     /**
1191      * Populates an account's fields in Settings->Accounts
1192      */
1193     fillIeAccount:function(jsonstr) {
1194         var o = JSON.parse(jsonstr);
1195
1196         document.getElementById('ie_id').value = o.id;
1197         document.getElementById('ie_name').value = o.name;
1198         if (o.stored_options != null) {
1199                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1200                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1201                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1202                 if (o.stored_options.trashFolder != null) {
1203                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1204                 }
1205                 if (o.stored_options.sentFolder != null) {
1206                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1207                 }
1208         }
1209         document.getElementById('server_url').value = o.server_url;
1210         document.getElementById('email_user').value = o.email_user;
1211         document.getElementById('port').value = o.port;
1212         document.getElementById('group_id').value = o.group_id;
1213         document.getElementById('mailbox').value = o.mailbox;
1214
1215
1216         var i = 0;
1217
1218         // handle SSL
1219         if(typeof(o.service[2]) != 'undefined') {
1220             document.getElementById('ssl').checked = true;
1221         }
1222
1223         // handle protocol
1224         if(document.getElementById('protocol').value != o.protocol) {
1225             var prot = document.getElementById('protocol');
1226             for(i=0; i<prot.options.length; i++) {
1227                 if(prot.options[i].value == o.service[3]) {
1228                     prot.options[i].selected = true;
1229                     this.setPortDefault();
1230                 }
1231             }
1232         }
1233  // handle SMTP selection
1234         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1235             var opts = document.getElementById('outbound_email').options;
1236             for(i=0; i<opts.length; i++) {
1237                 if(opts[i].value == o.stored_options.outbound_email) {
1238                     opts[i].selected = true;
1239                 }
1240             }
1241         }
1242     },
1243
1244     deleteIeAccount : function(IeAccountID,IeGroupID) {
1245         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1246         {
1247             overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1248
1249             AjaxObject.target = 'frameFlex';
1250             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1251             SUGAR.email2.accounts.refreshInboundAccountTable();
1252          }
1253      },
1254
1255        // Null check for Outbound Settings.
1256     checkOutboundSettings: function() {
1257         var errorMessage = '';
1258         var isError = false;
1259         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1260             var mailName = document.getElementById('mail_name').value;
1261             var smtpServer = document.getElementById('mail_smtpserver').value;
1262             var smtpPort = document.getElementById('mail_smtpport').value;
1263
1264             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1265             if(trim(mailName) == '') {
1266                 isError = true;
1267                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1268             }
1269             if(trim(smtpServer) == '') {
1270                 isError = true;
1271                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1272             }
1273             if(trim(smtpPort) == '') {
1274                 isError = true;
1275                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1276             }
1277             if(mailsmtpauthreq.checked) {
1278                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1279                     isError = true;
1280                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1281                 }
1282             }
1283         }
1284         if(isError) {
1285             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1286             return false;
1287         } else {
1288             return true;
1289         }
1290     },
1291
1292     testOutboundSettings: function() {
1293         var errorMessage = '';
1294         var isError = false;
1295         var fromAddress = document.getElementById("outboundtest_from_address").value;
1296         if (trim(fromAddress) == "") {
1297             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1298             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1299             return false;
1300
1301         }
1302         else if (!isValidEmail(fromAddress)) {
1303             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1304             overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1305             return false;
1306         }
1307
1308         //Hide the dialogue and show an in progress indicator.
1309         SE.accounts.testOutboundDialog.hide();
1310         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1311
1312         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1313         //nothing is sent in the request.
1314         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1315         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1316
1317         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1318         if(outboundType == 'system-override')
1319             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1320
1321         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1322         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1323
1324     },
1325
1326     testOutboundSettingsDialog: function() {
1327         //Ensure that all settings are correct before proceeding to send test email.
1328         if(!SE.accounts.checkOutboundSettings())
1329             return;
1330
1331         // lazy load dialogue
1332         if(!SE.accounts.testOutboundDialog) {
1333                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1334                 modal:true,
1335                                 visible:true,
1336                 fixedcenter:true,
1337                 constraintoviewport: true,
1338                 width   : 600,
1339                 shadow  : true
1340             });
1341             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1342             Dom.removeClass("testOutboundDialog", "yui-hidden");
1343         } // end lazy load
1344         SE.accounts.testOutboundDialog.render();
1345         SE.accounts.testOutboundDialog.show();
1346     },
1347
1348     /**
1349      * Saves Outbound email settings
1350      */
1351     saveOutboundSettings : function() {
1352         if(SE.accounts.checkOutboundSettings()) {
1353             //Enable the form fields for the post.
1354             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1355             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1356             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1357         } else {
1358             return false;
1359         }
1360     },
1361
1362     saveIeAccount : function() {
1363
1364         //Before saving check if there are any error messages associated with the outbound account.
1365         var outboundID = document.getElementById('outbound_email').value;
1366
1367         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1368             'validateSMTPCreds':true}) )
1369         {
1370             document.getElementById('saveButton').disabled = true;
1371
1372             overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1373
1374             var formObject = document.getElementById('ieAccount');
1375             YAHOO.util.Connect.setForm(formObject);
1376
1377             AjaxObject._reset();
1378             AjaxObject.target = 'frameFlex';
1379             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1380         }
1381     },
1382
1383     testSettings : function() {
1384         form = document.getElementById('ieAccount');
1385
1386         if(SE.accounts.checkIeCreds()) {
1387             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");
1388         }
1389     },
1390
1391     getFoldersListForInboundAccountForEmail2 : function() {
1392         form = document.getElementById('ieAccount');
1393         if(SE.accounts.checkIeCreds()) {
1394                 var mailBoxValue = form.mailbox.value;
1395                 if (form.searchField.value.length > 0) {
1396                         mailBoxValue = "";
1397                 } // if
1398             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 );
1399         } // if
1400
1401     },
1402
1403     checkIeCreds : function(validateRules) {
1404         if(typeof(validateRules) == 'undefined')
1405             validateRules = {};
1406
1407         var errors = new Array();
1408         var out = new String();
1409
1410         var ie_name = Dom.get('ie_name').value;
1411         var fromAddress = Dom.get('ie_from_addr').value;
1412         var server_url = Dom.get('server_url').value;
1413         var email_user = Dom.get('email_user').value;
1414         var email_password = Dom.get('email_password').value;
1415         var protocol = Dom.get('protocol').value;
1416         var port = Dom.get('port').value;
1417         var oe = Dom.get('outbound_email');
1418         var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1419
1420         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1421         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1422
1423         //If the username and password were provided then ignore the error messge
1424
1425         var outboundCredentialsFound = false;
1426
1427         if(outboundUserName != "" && outboundPass != "")
1428             outboundCredentialsFound = true;
1429
1430         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1431
1432         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1433              && validateSMTPCreds)
1434         {
1435             if(trim(outboundUserName) == "") {
1436                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1437             }
1438             if(trim(outboundPass) == "") {
1439                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1440             }
1441         }
1442
1443         if(trim(ie_name) == "") {
1444             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1445         }
1446
1447         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1448         {
1449             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1450                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1451             }
1452         }
1453
1454
1455         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1456              || trim(oe_value) == "SYSTEM_ADD") ) {
1457             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1458         }
1459         if(trim(server_url) == "") {
1460             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1461         }
1462         if(trim(email_user) == "") {
1463             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1464         }
1465         if(protocol == "") {
1466             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1467         }
1468         if (protocol == 'imap') {
1469                 var mailbox = document.getElementById('mailbox').value;
1470                 if (trim(mailbox) == "") {
1471                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1472                 } // if
1473                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1474                         var trashFolder = document.getElementById('trashFolder').value;
1475                         if (trim(trashFolder) == "") {
1476                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1477                         } // if
1478                         } // if
1479         }
1480         if(port == "") {
1481             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1482         }
1483
1484         if(errors.length > 0) {
1485             out = app_strings.LBL_EMAIL_ERROR_DESC;
1486             for(i=0; i<errors.length; i++) {
1487                 if(out != "") {
1488                     out += "\n";
1489                 }
1490                 out += errors[i];
1491             }
1492
1493             alert(out);
1494             return false;
1495         } else {
1496
1497             return true;
1498         }
1499     },
1500
1501     getIeAccount : function(ieId) {
1502         if(ieId == '')
1503             return;
1504
1505         overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1506                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1507
1508         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1509     },
1510
1511     /**
1512      * Iterates through TreeView nodes to apply styles dependent nature of node
1513      */
1514     renderTree:function() {
1515         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1516         SE.tree.render();
1517     },
1518
1519     //Sets the style for any nodes that need it.
1520     setNodeStyle : function(node) {
1521         if (!node.data.origText) {
1522             node.data.origText = node.data.text;
1523         }
1524         //Set unread
1525         if (typeof(node.data.unseen) != 'undefined') {
1526                 if (node.data.unseen > 0) {
1527                                 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1528                         }
1529                         else {
1530                                 node.setUpLabel(node.data.origText);
1531                         }
1532         } else {
1533                 node.setUpLabel('<span>' + node.data.origText + '</span>');
1534         }
1535         SE.accounts.setupDDTarget(node);
1536     },
1537
1538     setupDDTarget : function(node) {
1539         if (node.ddTarget) {
1540                 node.ddTarget.removeFromGroup();
1541                 delete node.ddTarget;
1542         }
1543         var id = node.getElId();
1544         var num = id.substring(4);
1545         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1546                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1547                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1548
1549                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1550         }
1551         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1552                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1553         }
1554     },
1555
1556     /**
1557      * Async call to rebuild the folder list.  After a folder delete or account delete
1558      */
1559     rebuildFolderList : function() {
1560         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1561         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1562     },
1563
1564     /**
1565      * Returns the number of remote accounts the user has active.
1566      */
1567     getAccountCount : function() {
1568         var tree = SE.tree;
1569         var count = 0;
1570         for(i=0; i<tree._nodes.length; i++) {
1571             var node = tree._nodes[i];
1572
1573             if(typeof(node) != 'undefined' && node.data.ieId) {
1574                 count++;
1575             }
1576         }
1577         return count;
1578     }
1579 };
1580 ////    END ACCOUNTS
1581 ///////////////////////////////////////////////////////////////////////////////
1582
1583
1584
1585
1586 ///////////////////////////////////////////////////////////////////////////////
1587 ////    CONTEXT MENU CALLS
1588 SE.contextMenus = {
1589
1590     assignToDialogue : null,
1591     /**
1592      * Archives from context menu
1593      * @param Array uids
1594      * @param string ieId
1595      * @param string folder
1596      */
1597     _archiveToSugar : function(uids, ieId, folder) {
1598         var ser = '';
1599
1600         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1601             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1602             ser += uids[i];
1603         }
1604         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1605     },
1606
1607     /**
1608      * Archives from context menu
1609      */
1610     archiveToSugar : function(menuItem) {
1611         SE.contextMenus.emailListContextMenu.hide();
1612
1613         var rows = SE.grid.getSelectedRows();
1614         var uids = [];
1615         /* iterate through available rows JIC a row is deleted - use first available */
1616         for(var i=0; i<rows.length; i++) {
1617             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1618         }
1619         var data = SE.grid.getRecord(rows[0]).getData();
1620         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1621     },
1622
1623     /**
1624      * Popup the printable version and start system's print function.
1625      */
1626     viewPrintable : function(menuItem) {
1627         var rows = SE.grid.getSelectedRows();
1628         var data = SE.grid.getRecord(rows[0]).getData();
1629         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1630     },
1631
1632     /**
1633      * Marks email flagged on mail server
1634      */
1635     markRead : function(type, contextMenuId) {
1636         SE.contextMenus.markEmail('read');
1637     },
1638
1639     /**
1640      * Assign this emails to people based on assignment rules
1641      */
1642     assignEmailsTo : function(type, contextMenuId) {
1643         if(!SE.contextMenus.assignToDialogue)
1644         {
1645                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1646                 modal:true,
1647                                 visible:false,
1648                 fixedcenter:true,
1649                 constraintoviewport: true,
1650                 width   : "600px",
1651                 shadow  : true
1652             });
1653             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1654             enableQS(true);
1655         }
1656
1657         Dom.removeClass("assignToDiv", "yui-hidden");
1658         SE.contextMenus.assignToDialogue.render();
1659         SE.contextMenus.assignToDialogue.show();
1660     },
1661
1662     /**
1663      * Marks email flagged on mail server
1664      */
1665     markFlagged : function(contextMenuId) {
1666         SE.contextMenus.markEmail('flagged');
1667     },
1668
1669     /**
1670      * Marks email unflagged on mail server
1671      */
1672     markUnflagged : function(contextMenuId) {
1673         SE.contextMenus.markEmail('unflagged');
1674     },
1675
1676     /**
1677      * Marks email unread on mail server
1678      */
1679     markUnread : function() {
1680         SE.contextMenus.markEmail('unread');
1681     },
1682
1683     /**
1684      * Deletes an email from context menu
1685      */
1686     markDeleted : function() {
1687         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1688                 document.getElementById('_blank').innerHTML = "";
1689                 SE.contextMenus.markEmail('deleted');
1690         }
1691     },
1692
1693     /**
1694      * generic call API to apply a flag to emails on the server and on sugar
1695      * @param string type "read" | "unread" | "flagged" | "deleted"
1696      */
1697     markEmail : function(type) {
1698         SE.contextMenus.emailListContextMenu.hide();
1699
1700         //var dm = SE.grid.getStore();
1701         //var uids = SE.grid.getSelectedRowIds();
1702         //var indexes = SE.grid.getSelectedRowIndexes();
1703         var rows = SE.grid.getSelectedRows();
1704         if (rows.length == 0)
1705                 rows = [SE.contextMenus.currentRow];
1706         var ser = [ ];
1707
1708         for(var i=0; i<rows.length; i++) {
1709             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1710         }
1711
1712         ser = YAHOO.lang.JSON.stringify(ser);
1713
1714         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1715         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1716
1717
1718         var count = 0;
1719
1720
1721         if(type == 'read' || type == 'deleted') {
1722             // mark read
1723             for(var j=0; j<rows.length; j++) {
1724                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1725                     count = count + 1;
1726                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1727                 }
1728             }
1729            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1730             if(ieId){
1731             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1732             var unseenCount = node.data.unseen;
1733             if (isNaN(unseenCount)) {
1734                 unseenCount = 0;
1735             }
1736             var finalCount = parseInt(unseenCount) - count;
1737             node.data.unseen = finalCount;
1738
1739             SE.accounts.renderTree();
1740             }
1741         } else if(type == 'unread') {
1742             // mark unread
1743             for(var j=0; j<rows.length; j++) {
1744                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1745                     count = count + 1;
1746                 }
1747             }
1748
1749             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1750             var unseenCount = node.data.unseen;
1751             if (isNaN(unseenCount)) {
1752                 unseenCount = 0;
1753             }
1754             var finalCount = parseInt(unseenCount) + count;
1755             node.data.unseen = finalCount;
1756             SE.accounts.renderTree();
1757         }
1758
1759         if (type == 'unread') {
1760                 for(var i=0; i<rows.length; i++) {
1761                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1762                 } // for
1763         }
1764
1765                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1766         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1767     },
1768
1769     /**
1770      * refreshes the ListView to show changes to cache
1771      */
1772     markEmailCleanup : function() {
1773         SE.accounts.renderTree();
1774         hideOverlay();
1775         SE.listView.refreshGrid();
1776     },
1777
1778         showAssignmentDialog : function() {
1779                 if (SE.contextMenus.assignmentDialog == null) {
1780                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1781                 } else {
1782                         SE.contextMenus.assignmentDialog.show();
1783                 } // else
1784         },
1785
1786         /**
1787      * shows the import dialog with only relate visible.
1788      */
1789     relateTo : function() {
1790         SE.contextMenus.emailListContextMenu.hide();
1791
1792         var rows = SE.grid.getSelectedRows();
1793         var data = SE.grid.getRecord(rows[0]).getData();
1794         var ieId = data.ieId;
1795         var folder = data.mbox;
1796         var uids = [];
1797         /* iterate through available rows JIC a row is deleted - use first available */
1798         for(var i=0; i<rows.length; i++) {
1799             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1800         }
1801         var ser = JSON.stringifyNoSecurity(uids);
1802
1803         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1804     },
1805
1806         /**
1807      * shows the import dialog with only relate visible.
1808      */
1809     showDetailView : function() {
1810         SE.contextMenus.emailListContextMenu.hide();
1811         var rows = SE.grid.getSelectedRows();
1812         if (rows.length > 1) {
1813                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1814                 return;
1815         }
1816         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1817         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1818         /* iterate through available rows JIC a row is deleted - use first available */
1819         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1820         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1821     },
1822
1823     /**
1824      *
1825      */
1826     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1827         overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1828         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1829     },
1830
1831     /**
1832      * Opens multiple messages from ListView context click
1833      */
1834     openMultiple : function() {
1835         SE.contextMenus.emailListContextMenu.hide();
1836
1837         var rows = SE.grid.getSelectedRows();
1838         var uids = SE.listView.getUidsFromSelection();
1839
1840         if(uids.length > 0) {
1841             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1842             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1843             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1844         }
1845     },
1846
1847     /**
1848      * Replies/forwards email
1849      */
1850     replyForwardEmailContext : function() {
1851         SE.contextMenus.emailListContextMenu.hide();
1852
1853         var indexes = SE.grid.getSelectedRows();
1854         //var dm = SE.grid.getDataModel();
1855         var type = this.id;
1856
1857         for(var i=0; i<indexes.length; i++) {
1858             var row = SE.grid.getRecord(indexes[i]).getData();
1859             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1860         }
1861     },
1862
1863     //show menu functions
1864     showEmailsListMenu : function(grid, row) {
1865
1866        var data = row.getData();
1867        var draft = (data.type == "draft");
1868        var menu = SE.contextMenus.emailListContextMenu;
1869        var folderNode;
1870
1871        if (SE.tree)
1872        {
1873                if (data.mbox == 'sugar::Emails')
1874                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1875                else
1876                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1877
1878                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1879                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1880                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1881                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1882                else
1883                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1884        }
1885        else
1886            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1887
1888        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1889        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1890        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1891        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1892        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1893
1894
1895        if (data.mbox == "sugar::Emails")
1896        {
1897            //Allow users to reassign imported emails
1898            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1899            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1900            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1901            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1902        }
1903        else
1904        {
1905            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1906            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1907        }
1908     },
1909
1910     showFolderMenu : function(grid, rowIndex, event) {
1911        event.stopEvent();
1912        var coords = event.getXY();
1913        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1914     }
1915 };
1916
1917 SE.contextMenus.dv = {
1918     archiveToSugar : function(contextMenuId) {
1919
1920         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1921     },
1922
1923     replyForwardEmailContext : function(all) {
1924         SE.contextMenus.detailViewContextMenu.hide();
1925     }
1926
1927 };
1928
1929
1930
1931
1932
1933 ////    END SE.contextMenus
1934 ///////////////////////////////////////////////////////////////////////////////
1935
1936
1937
1938 ///////////////////////////////////////////////////////////////////////////////
1939 ////    DETAIL VIEW
1940 SE.detailView = {
1941     consumeMetaDetail : function(ret) {
1942         // handling if the Email drafts
1943         if(ret.type == 'draft') {
1944             SE.composeLayout.c0_composeDraft();
1945             return;
1946         }
1947
1948
1949         // cache contents browser-side
1950         SE._setDetailCache(ret);
1951
1952         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1953         // 2 below must be in global context
1954         meta = ret.meta;
1955         meta['panelId'] = SE.util.getPanelId();
1956
1957         email = ret.meta.email;
1958         var out = displayTemplate.exec({
1959             'app_strings' : app_strings,
1960             'theme' : theme,
1961             'idx' : targetDiv.id,
1962             'meta' : meta,
1963             'email' : meta.email,
1964             'linkBeans' : linkBeans
1965         });
1966         var tabLabel = meta.email.name;
1967         if (tabLabel != null && tabLabel.length > 25) {
1968                 tabLabel = tabLabel.substring(0, 25) + "...";
1969         } // if
1970         targetDiv.set("label", tabLabel);
1971         targetDiv.set("content", out);
1972
1973         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1974         if (SUGAR.email2.util.isIe()) {
1975                 displayEmailFrameDiv.style.height = "390px";
1976         } else {
1977                 displayEmailFrameDiv.style.height = "410px";
1978         }
1979
1980         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1981         displayFrame.contentWindow.document.write(email.description);
1982         displayFrame.contentWindow.document.close();
1983
1984         // hide archive links
1985         if(ret.meta.is_sugarEmail) {
1986                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1987             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1988         } else {
1989             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1990                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1991         } // else
1992
1993     },
1994
1995     consumeMetaPreview : function(ret) {
1996         // cache contents browser-side
1997         SE._setDetailCache(ret);
1998
1999
2000
2001         var currrow = SE.grid.getLastSelectedRecord();
2002         currrow = SE.grid.getRecord(currrow);
2003         if (!currrow) {
2004             document.getElementById('_blank').innerHTML = '';
2005             return;
2006         }
2007         // handling if the Email drafts
2008         if(ret.type == 'draft'){
2009             if (currrow.getData().uid == ret.uid) {
2010                 SE.composeLayout.c0_composeDraft();
2011             }
2012             return;
2013         }
2014
2015         if (currrow.getData().uid != ret.meta.uid) {
2016            return;
2017         }
2018
2019         // remove loading sprite
2020         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2021         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2022         meta = ret.meta;
2023         meta['panelId'] = SE.util.getPanelId();
2024         email = ret.meta.email;
2025
2026         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2027             'app_strings' : app_strings,
2028             'theme' : theme,
2029             'idx' : 'Preview',
2030             'meta' : meta,
2031             'email' :meta.email,
2032             'linkBeans' : linkBeans
2033         });
2034        // document.getElementById('_blank').innerHTML = meta.email;
2035        /* displayTemplate.append('_blank', {
2036             'app_strings' : app_strings,
2037             'theme' : theme,
2038             'idx' : 'Preview',
2039             'meta' : meta,
2040             'email' :meta.email,
2041             'linkBeans' : linkBeans
2042         });*/
2043
2044         var displayFrame = document.getElementById('displayEmailFramePreview');
2045         displayFrame.contentWindow.document.write(email.description);
2046         displayFrame.contentWindow.document.close();
2047
2048         SE.listViewLayout.resizePreview();
2049
2050         // hide archive links
2051         if(ret.meta.is_sugarEmail) {
2052             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2053             document.getElementById("btnEmailViewPreview").style.display = "none";
2054             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2055         } else {
2056           //hide view relationship link
2057                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2058         }
2059     },
2060
2061     /**
2062      * wraps emailDelete() for single messages, comes from preview or tab
2063      */
2064     emailDeleteSingle : function(ieId, uid, mbox) {
2065         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2066             // find active panel and close if the user double clicked the email to view.
2067             var activeTabId = SE.util.getPanelId();
2068             if(activeTabId != 'Preview')
2069                 SE.innerLayout.get("activeTab").close();
2070
2071             document.getElementById('_blank').innerHTML = "";
2072                 var ser = [ ];
2073                         ser.push(uid);
2074                 uid = JSON.stringifyNoSecurity(ser);
2075             this.emailDelete(ieId, uid, mbox);
2076         }
2077     },
2078
2079     /**
2080      * Sends async call to delete a given message
2081      * @param
2082      */
2083     emailDelete : function(ieId, uid, mbox) {
2084        overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2085        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2086            uid + "&ieId=" + ieId + "&folder=" + mbox);
2087     },
2088
2089     /**
2090      * retrieves one email to display in the preview pane.
2091      */
2092     getEmailPreview : function() {
2093         var row = SUGAR.email2.listView.currentRow;
2094         var data = row.getData();
2095             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2096                var setRead = (data['seen'] == 0) ? true : false;
2097                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2098                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2099             }
2100     },
2101
2102     /**
2103      * Imports one email into Sugar
2104      */
2105     importEmail : function(ieId, uid, mbox) {
2106         SE.util.clearHiddenFieldValues('emailUIForm');
2107
2108         overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2109
2110         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2111         AjaxObject.target = '';
2112         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2113     },
2114
2115     /**
2116      * Populates the frameFlex div with the contents of an email
2117      */
2118     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2119         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2120
2121         var mboxStr = new String(mbox);
2122         var compKey = mbox + uid;
2123
2124         if(setRead == true) {
2125                 SE.listView.boldUnreadRows()
2126                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2127         }
2128
2129         if(destination == SE.innerLayout) {
2130                 /*
2131              * loading email into a tab, peer with ListView
2132              * targetDiv must remain in the global namespace as it is used by AjaxObject
2133              */
2134                 //Check if we already have a tab of the email open
2135                 var tabs = SE.innerLayout.get("tabs");
2136                 for (var t in tabs) {
2137                         if (tabs[t].id && tabs[t].id == uid) {
2138                                 SE.innerLayout.set("activeTab", tabs[t]);
2139                                 return;
2140                         }
2141                 }
2142
2143                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2144                                 label: loadingSprite,
2145                                         scroll : true,
2146                                         content : "",
2147                                         active : true
2148                 }, SE.innerLayout);
2149                 targetDiv.id = uid;
2150                 SE.innerLayout.addTab(targetDiv);
2151
2152             // use cache if available
2153             if(SE.cache[compKey]) {
2154                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2155             } else {
2156                 // open email as peer-tab to listView
2157                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2158                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2159             }
2160         } else {
2161             // loading email into preview pane
2162             document.getElementById('_blank').innerHTML = loadingSprite;
2163
2164             // use cache if available
2165             if(SE.cache[compKey]) {
2166                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2167             } else {
2168                 AjaxObject.forceAbort = true;
2169                 // open in preview window
2170                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2171                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2172             }
2173         }
2174     },
2175
2176     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2177     {
2178         if(mboxStr.substring(0,7) == 'sugar::') {
2179             // display an email from Sugar
2180             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2181         } else {
2182             // display an email from an email server
2183             document.getElementById('emailUIAction').value = 'getSingleMessage';
2184         }
2185         document.getElementById('mbox').value = mbox;
2186         document.getElementById('ieId').value = ieId;
2187         document.getElementById('uid').value = uid;
2188
2189         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2190
2191         AjaxObject.forceAbort = true;
2192         AjaxObject.target = '_blank';
2193         AjaxObject.startRequest(callback, null);
2194     },
2195
2196     /**
2197      * Retrieves multiple emails for DetailView
2198      */
2199     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2200         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2201         SE.util.clearHiddenFieldValues('emailUIForm');
2202
2203         var mboxStr = new String(mbox);
2204
2205         uids = SE.util.cleanUids(uids);
2206
2207         if(mboxStr.substring(0,7) == 'sugar::') {
2208             // display an email from Sugar
2209             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2210             document.getElementById('uid').value = uids;
2211         } else {
2212             // display an email from an email server
2213             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2214             document.getElementById('mbox').value = mbox;
2215             document.getElementById('ieId').value = ieId;
2216             document.getElementById('uid').value = uids;
2217         }
2218
2219         var formObject = document.getElementById('emailUIForm');
2220         YAHOO.util.Connect.setForm(formObject);
2221
2222         AjaxObject.target = 'frameFlex';
2223         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2224
2225         if(setRead == true) {
2226             var c = uids.split(",");
2227             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2228         }
2229     },
2230
2231     /**
2232      * Makes async call to get QuickCreate form
2233      * Renders a modal edit view for a given module
2234      */
2235     quickCreate : function(module, ieId, uid, mailbox) {
2236         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2237
2238         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2239             get += "&sugarEmail=true";
2240         }
2241
2242         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2243     },
2244
2245     /**
2246      * Makes async call to save a quick create
2247      * @param bool
2248      */
2249     saveQuickCreate : function(action) {
2250         var qcd = SE.detailView.quickCreateDialog;
2251         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2252                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2253                 var theCallback = callbackQuickCreateSave;
2254                 var accountType = '&sugarEmail=true';
2255                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2256                    accountType = '&ieId=' + qcd.ieId;
2257                 }
2258
2259             if (action == 'reply') {
2260                    theCallback = callbackQuickCreateSaveAndReply;
2261                 } else if (action == true) {
2262                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2263                 }
2264                 formObject.action.value = 'EmailUIAjax';
2265                 YAHOO.util.Connect.setForm(formObject);
2266                 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2267                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2268                                        accountType + '&mbox=' + qcd.mbox);
2269         }
2270     },
2271
2272     /**
2273      * Code to show/hide long list of email address in DetailView
2274      */
2275     showCroppedEmailList : function(el) {
2276         el.style.display = 'none';
2277         el.previousSibling.style.display = 'inline'
2278     },
2279     showFullEmailList : function(el) {
2280         el.style.display = 'none';
2281         el.nextSibling.style.display = 'inline';
2282     },
2283
2284     /**
2285      * Shows the QuickCreate overlay
2286      * @param string ieId
2287      * @param string uid
2288      * @param string mailbox
2289      */
2290     showQuickCreate : function(ieId, uid, mailbox) {
2291         var panelId = SE.util.getPanelId();
2292         var context = document.getElementById("quickCreateSpan" + panelId);
2293
2294         if (!SE.detailView.cqMenus)
2295                 SE.detailView.cqMenus = {};
2296
2297         if (SE.detailView.cqMenus[context])
2298                 SE.detailView.cqMenus[context].destroy();
2299
2300             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2301                 lazyload:true,
2302                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2303         });
2304
2305             for (var i=0; i < this.qcmodules.length; i++) {
2306             var module = this.qcmodules[i];
2307             menu.addItem({
2308                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2309                 modulename: module,
2310                 value: module,
2311                 onclick: { fn: function() {
2312                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2313                         }
2314                 }
2315             });
2316         }
2317
2318                 menu.render(document.body);
2319                 menu.show();
2320     },
2321
2322     /**
2323      * Displays the "View" submenu in the detailView
2324      * @param string ieId
2325      * @param string uid
2326      * @param string mailbox
2327      */
2328     showViewMenu : function(ieId, uid, mailbox) {
2329         var panelId = SE.util.getPanelId();
2330         var context = "btnEmailView" + panelId;
2331         if (!SE.detailView.viewMenus)
2332                 SE.detailView.viewMenus = {};
2333
2334         if (SE.detailView.viewMenus[context])
2335                 SE.detailView.viewMenus[context].destroy();
2336
2337             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2338                 lazyload:true,
2339                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2340                 clicktohide: true
2341         });
2342                 menu.addItems(
2343                                 (ieId == 'null' || ieId == null) ?
2344                         //No ieId - Sugar Email
2345                         [{
2346                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2347                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2348             }]
2349                         :
2350                         //IeID exists, on a remote server
2351                         [{
2352                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2353                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2354             },{
2355                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2356                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2357             }]
2358         );
2359                 menu.render(document.body);
2360                 menu.show();
2361
2362
2363         /*
2364         //#23108 jchi@07/17/2008
2365         menu.render('quickCreateSpan'+ panelId);*/
2366         //this.viewMenu = menu;
2367         //this.viewMenu.show(context);
2368     },
2369     /**
2370      * Makes async call to get an email's headers
2371      */
2372     viewHeaders : function(ieId, uid, mailbox) {
2373         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2374         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2375     },
2376
2377     /**
2378      * Makes async call to get a printable version
2379      */
2380     viewPrintable : function(ieId, uid, mailbox) {
2381         if(mailbox == 'sugar::Emails') {
2382             // display an email from Sugar
2383             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2384         } else {
2385             // display an email from an email server
2386             var emailUIAction = '&emailUIAction=getSingleMessage';
2387         }
2388
2389         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2390         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2391     },
2392
2393     /**
2394      * Makes async call to get an email's raw source
2395      */
2396     viewRaw : function(ieId, uid, mailbox) {
2397         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2398         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2399     },
2400
2401     /**
2402      * Display all email addresses in detailview.
2403      */
2404     displayAllAddrs : function(el) {
2405         el.style.display = 'none';
2406         Dom.getNextSibling(el).style.display = 'inline';
2407     }
2408 };
2409 ////    END SE.detailView
2410 ///////////////////////////////////////////////////////////////////////////////
2411
2412
2413
2414 ///////////////////////////////////////////////////////////////////////////////
2415 ////    SE.folders
2416 SE.folders = {
2417     contextMenuFocus : new Object(),
2418
2419     /**
2420      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2421      * SugarFolder ID - folder strings
2422      */
2423     _createFolderId : function(node) {
2424         var ret = '';
2425
2426         if(!node.data.id)
2427             return ret;
2428
2429         if(node.data.ieId) {
2430             /* we have a local Sugar folder */
2431             if(node.data.ieId == 'folder') {
2432                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2433             } else if(node.data.ieId.match(SE.reGUID)) {
2434                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2435             }
2436         } else {
2437             ret = node.data.id;
2438         }
2439
2440         return ret;
2441     },
2442
2443     addChildNode : function(parentNode, childNode) {
2444         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2445         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2446         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2447
2448         if(childNode.nodes) {
2449             if(childNode.nodes.length > 0) {
2450                 for(j=0; j<childNode.nodes.length; j++) {
2451                     var newChildNode = childNode.nodes[j];
2452                     this.addChildNode(node, newChildNode);
2453                 }
2454             }
2455         }
2456     },
2457
2458     /**
2459      * Builds and returns a new TreeView Node
2460      * @param string name
2461      * @param string id
2462      * @param int is_group
2463      * @return object
2464      */
2465     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2466         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2467
2468         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2469         node.expanded = expanded;
2470         node.data = new Object;
2471         node.data['id'] = id;
2472         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2473         node.data['label'] = name;
2474         node.data['ieId'] = 'folder';
2475         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2476         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2477         node.data['unseen'] = unseen;
2478         return node;
2479     },
2480
2481     /**
2482      * ensures that a new folder has a valid name
2483      */
2484     checkFolderName : function(name) {
2485         if(name == "")
2486             return false;
2487
2488         this.folderAdd(name);
2489     },
2490
2491     /**
2492      * Pings email servers for new email - forces refresh of folder pane
2493      */
2494     checkEmailAccounts : function() {
2495         this.checkEmailAccountsSilent(true);
2496     },
2497
2498     checkEmailAccountsSilent : function(showOverlay) {
2499         if(typeof(SE.folders.checkingMail)) {
2500             clearTimeout(SE.folders.checkingMail);
2501         }
2502
2503         // don't stomp an on-going request
2504         if(AjaxObject.currentRequestObject.conn == null) {
2505             if(showOverlay) {
2506                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2507                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2508             }
2509             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2510         } else {
2511             // wait 5 secs before trying again.
2512             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2513         }
2514     },
2515
2516     /**
2517      * Starts check of all email Accounts using a loading bar for large POP accounts
2518      */
2519     startEmailAccountCheck : function() {
2520         // don't do two checks at the same time
2521        if(!AjaxObject.requestInProgress()) {
2522             overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2523             SE.accounts.ieIds = SE.folders.getIeIds();
2524             if (SE.accounts.ieIds.length > 0) {
2525                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2526                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2527             } else {
2528                hideOverlay();
2529             }
2530         } else {
2531             // wait 5 secs before trying again.
2532             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2533         }
2534     },
2535
2536     /**
2537      * Checks a single Account check based on passed ieId
2538      */
2539      startEmailCheckOneAccount : function(ieId, synch) {
2540             if (synch) {
2541                 synch = true;
2542             } else {
2543                 synch = false;
2544             }
2545             var mbox = "";
2546             var node = SE.clickedFolderNode;
2547             if (node && !synch) {
2548                 mbox = node.data.mbox;
2549             } // if
2550             overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2551             SE.accounts.ieIds = [ieId];
2552             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2553                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2554       },
2555
2556
2557     /**
2558      * Empties trash for subscribed accounts
2559      */
2560     emptyTrash : function() {
2561         SE.contextMenus.frameFoldersContextMenu.hide();
2562         overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2563         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2564     },
2565
2566     /**
2567      * Clears Cache files of the inboundemail account
2568      */
2569     clearCacheFiles : function(ieId) {
2570         SE.contextMenus.frameFoldersContextMenu.hide();
2571         overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2572         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2573     },
2574
2575
2576     /**
2577      * Returns an array of all the active accounts in the folder view
2578      */
2579     getIeIds : function() {
2580          var ieIds = [];
2581          var root = SE.tree.getRoot();
2582          for(i=0; i < root.children.length; i++) {
2583            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2584                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2585                ieIds.push(root.children[i].children[0].data.ieId);
2586            }
2587          }
2588          return ieIds;
2589      },
2590
2591     /**
2592      * loads folder lists in Settings->Folders
2593      */
2594     lazyLoadSettings : function() {
2595         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2596         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2597     },
2598
2599     /**
2600      * After the add new folder is done via folders tab on seetings, this function should get called
2601      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2602      */
2603     loadSettingFolder : function() {
2604         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2605         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2606     },
2607
2608     /**
2609      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2610      */
2611     removeSugarFolders : function() {
2612         var tree = SE.tree;
2613         var root = tree.getRoot();
2614         var folder = SE.util.findChildNode(root, "ieId", "folder");
2615         while(folder) {
2616             tree.removeNode(folder);
2617             folder = SE.util.findChildNode(root, "ieId", "folder");
2618         }
2619         if (!root.childrenRendered) {
2620                 root.childrenRendered = true;
2621         }
2622     },
2623
2624     rebuildFolders : function(silent) {
2625       if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2626        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2627     },
2628
2629
2630
2631     /**
2632      * Updates TreeView with Sugar Folders
2633      */
2634     setSugarFolders : function(delay) {
2635         this.removeSugarFolders();
2636                 //AjaxObject.forceAbort = true;
2637                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2638     },
2639
2640     /**
2641      * Takes async data object and creates the sugar folders in TreeView
2642      */
2643     setSugarFoldersEnd : function(o) {
2644         var root = SE.tree.getRoot();
2645         addChildNodes(root, {nodes: o});
2646         SE.accounts.renderTree();
2647         //If nothing is loaded in the grid, load "My Inbox"
2648         if (SE.grid.params.ieId == "undefined") {
2649                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2650         }
2651     },
2652
2653     startCheckTimer : function() {
2654         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2655             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2656
2657             if(typeof(SE.folders.checkTimer) != 'undefined') {
2658                 clearTimeout(SE.folders.checkTimer);
2659             }
2660
2661             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2662             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2663             {
2664                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2665                 SE.folders.checkEmailAccountsSilent(false);
2666             }
2667         }
2668     },
2669
2670     /**
2671      * makes an async call to save user preference and refresh folder view
2672      * @param object SELECT list object
2673      */
2674     setFolderSelection : function() {
2675         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2676
2677         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2678         var a_active_accnts = "";
2679         for(i=0;i<a_rs.length;i++)
2680         {
2681                 var t_record = a_rs[i];
2682                 var is_active = t_record.getData('is_active');
2683                 if(is_active)
2684                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2685         }
2686
2687         if(a_active_accnts == "")
2688                 a_active_accnts = "&ieIdShow[]=";
2689
2690         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2691
2692         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2693     },
2694
2695     /**
2696      * makes async call to save user preference for a given node's open state
2697      * @param object node YUI TextNode object
2698      */
2699     setOpenState : function(node) {
2700         SE.util.clearHiddenFieldValues('emailUIForm');
2701         var nodePath = node.data.id;
2702         var nodeParent = node.parent;
2703
2704         while(nodeParent != null) {
2705             // root node has no ID param
2706             if(nodeParent.data != null) {
2707                 nodePath = nodeParent.data.id + "::" + nodePath;
2708             }
2709
2710             var nodeParent = nodeParent.parent;
2711         }
2712
2713         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2714         document.getElementById('focusFolder').value = nodePath;
2715
2716         if(node.expanded == true) {
2717             document.getElementById('focusFolderOpen').value = 'open';
2718         } else {
2719             document.getElementById('focusFolderOpen').value = 'closed';
2720         }
2721
2722         var formObject = document.getElementById('emailUIForm');
2723         YAHOO.util.Connect.setForm(formObject);
2724
2725         AjaxObject.startRequest(null, null);
2726     },
2727
2728     getNodeFromMboxPath : function(path) {
2729         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2730         var a = JSON.parse(path);
2731
2732         var node = tree.getRoot();
2733
2734         var i = 0;
2735         while(i < a.length) {
2736             node = this.getChildNodeFromLabel(node, a[i]);
2737             i++;
2738         }
2739
2740         return node;
2741     },
2742
2743     getChildNodeFromLabel : function(node, nodeLabel) {
2744         for(i=0; i<node.children.length; i++) {
2745             if(node.children[i].data.id == nodeLabel) {
2746                 return node.children[i];
2747             }
2748         }
2749     },
2750
2751     /**
2752      * returns the node that presumably under the user's right-click
2753      */
2754     getNodeFromContextMenuFocus : function() {
2755         //// get the target(parent) node
2756         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2757         var index = -1;
2758         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2759
2760         // filter local folders
2761         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2762             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2763                 if(target.id == '') {
2764                     target = target.parentNode;
2765                 } else {
2766                     break;
2767                 }
2768             }
2769         }
2770
2771         var targetNode = document.getElementById(target.id);
2772         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2773
2774         try {
2775             var matches = re.exec(targetNode.id);
2776         } catch(ex) {
2777             return document.getElementById(ygtvlabelel1);
2778         }
2779
2780         if(matches) {
2781             index = matches[1];
2782         } else {
2783             // usually parent node
2784             matches = re.exec(targetNode.parentNode.id);
2785
2786             if(matches) {
2787                 index = matches[1];
2788             }
2789         }
2790
2791         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2792         parentNode.expand();
2793
2794         return parentNode;
2795     },
2796
2797     /**
2798      * Decrements the Unread Email count in folder text
2799      * @param string ieId ID to look for
2800      * @param string mailbox name
2801      * @param count how many to decrement
2802      */
2803     decrementUnreadCount : function(ieId, mbox, count) {
2804
2805         if(mbox == null)
2806             return;
2807
2808         if(mbox.indexOf("sugar::") === 0) {
2809             var node = this.getNodeFromId(ieId);
2810         } else {
2811             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2812         }
2813         if(node) {
2814             var unseen = node.data.unseen;
2815             if(unseen > 0) {
2816                 var check = unseen - count;
2817                 var finalCount = (check >= 0) ? check : 0;
2818                 node.data.unseen = finalCount;
2819             }
2820             SE.accounts.renderTree();
2821         }
2822     },
2823
2824     /**
2825      * gets the TreeView node with a given ID/ieId
2826      * @param string id ID to look for
2827      * @return object Node
2828      */
2829     getNodeFromId : function(id) {
2830         SE.folders.focusNode = null;
2831         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2832             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2833                 SE.folders.focusNode = this;
2834                 return false;
2835             }
2836         }, null, [id]);
2837         return SE.folders.focusNode;
2838     },
2839
2840     /**
2841      * Uses ieId and mailbox to try to find a node in the tree
2842      */
2843     getNodeFromIeIdAndMailbox : function(id, mbox) {
2844                 SE.folders.focusNode = null;
2845         if (mbox == "sugar::Emails") {
2846                 mbox = id;
2847                 id = "folder";
2848         } // if
2849         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2850                 if (varsarray instanceof Array) {
2851             if (this.data.ieId && this.data.ieId == varsarray[0]
2852                     && this.data.mbox == varsarray[1]) {
2853                 SE.folders.focusNode = this;
2854                 return false;
2855             } }
2856                 else {
2857                         if (this.data.ieId && this.data.ieId == varsarray) {
2858                                 SE.folders.focusNode = this;
2859                     return false;
2860                         }
2861                 }
2862         }, null, [id, mbox]);
2863         return SE.folders.focusNode;
2864     },
2865
2866     unhighliteAll : function() {
2867         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2868     },
2869
2870     /**
2871      * Displays a short form
2872      */
2873     folderAdd : function() {
2874         SE.contextMenus.frameFoldersContextMenu.hide();
2875
2876         var node = SE.clickedFolderNode;
2877
2878         if(node != null && node.data) {
2879             overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2880                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2881                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2882         } else {
2883             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2884         }
2885     },
2886
2887     folderAddRegisterEnter : function() {
2888         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2889                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2890                                                                                                                         this.buttons[1].handler);
2891
2892                 this.enterKeyListener.enable();
2893     },
2894
2895     folderRemoveRegisterEnter : function() {
2896         this.enterKeyListener.disable();
2897     },
2898
2899     folderAddXmlCall : function(name) {
2900         if (trim(name) == "") {
2901                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2902                 return false;
2903         }
2904         name = escape(name);
2905         var post = '';
2906         var type = 'sugar';
2907
2908         var parentNode = SE.clickedFolderNode;
2909
2910         this.contextMenuFocus = parentNode;
2911
2912         if(parentNode.data.ieId) {
2913             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2914                 type = 'imap';
2915             }
2916         }
2917         if(type == 'imap') {
2918                 // make an IMAP folder
2919             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2920             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2921         } else if(type == 'sugar') {
2922             // make a Sugar folder
2923             if(SE.folders.isUniqueFolderName(name)) {
2924                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2925                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2926             } else {
2927                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2928                 SE.folders.folderAdd();
2929                 return;
2930             }
2931         } else {
2932             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2933         }
2934
2935         // hide add-folder diaglogue
2936         SE.e2overlay.hide();
2937     },
2938
2939     /**
2940      * Removes either an IMAP folder or a Sugar Folder
2941      */
2942     folderDelete : function() {
2943         SE.contextMenus.frameFoldersContextMenu.hide();
2944
2945         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2946             var post = '';
2947             var parentNode = SE.clickedFolderNode;
2948
2949             if(parentNode != null && parentNode.data) {
2950                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2951                     overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2952                     return;
2953                 }
2954
2955                 AjaxObject.target = 'frameFlex';
2956
2957                 if(parentNode.data.ieId != 'folder') {
2958                     // delete an IMAP folder
2959                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2960                 } else {
2961                     // delete a sugar folder
2962                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2963                 }
2964                 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2965                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2966             } else {
2967                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2968             }
2969         }
2970     },
2971
2972     /**
2973      * Rename folder form
2974      */
2975      //EXT111
2976     folderRename : function() {
2977         SE.contextMenus.frameFoldersContextMenu.hide();
2978         var node = SE.clickedFolderNode;
2979
2980         if(node != null) {
2981             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2982                 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2983                 return;
2984             }
2985
2986                         overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2987                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2988                     'prompt',
2989                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2990         } else {
2991             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2992         }
2993     },
2994
2995     /**
2996      * fills an Object with key-value pairs of available folders
2997      */
2998     getAvailableFoldersObject : function() {
2999         var ret = new Object();
3000         var tree = SE.tree.root;
3001
3002         if(tree.children) {
3003             for(var i=0; i<tree.children.length; i++) {
3004                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3005             }
3006         } else {
3007             ret['none'] = app_strings.LBL_NONE;
3008         }
3009
3010         return ret;
3011     },
3012
3013     /**
3014      * Fills in key-value pairs for dependent dropdowns
3015      * @param object ret Associative array
3016      * @param object node TreeView node in focus
3017      * @param string currentPath Built up path thus far
3018      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3019      */
3020     getFolderFromChild : function(ret, node, currentPath, spacer) {
3021         if(node.data != null && node.depth > 0) {
3022             /* handle visual separtors differentiating b/t mailserver and local */
3023             if(node.data.ieId && node.data.ieId == 'folder') {
3024                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3025             }
3026
3027             if(!ret.spacer0) {
3028                 ret['spacer0'] = spacer;
3029             } else if(ret.spacer0 != spacer) {
3030                 ret['spacer1'] = spacer
3031             }
3032
3033             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3034             var depthMarker = currentPath;
3035             var retIndex = SE.folders._createFolderId(node);
3036             ret[retIndex] = depthMarker + theLabel;
3037         }
3038
3039         if(node.children != null) {
3040             if(theLabel) {
3041                 currentPath += theLabel + "/";
3042             }
3043
3044             for(var i=0; i<node.children.length; i++) {
3045                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3046             }
3047         }
3048
3049         return ret;
3050     },
3051
3052     /**
3053      * Wrapper to refresh folders tree
3054      */
3055     getFolders : function() {
3056         SE.accounts.rebuildFolderList();
3057     },
3058
3059     /**
3060      * handles events around folder-rename input field changes
3061      * @param object YUI event object
3062      */
3063     handleEnter : function(e) {
3064         switch(e.browserEvent.type) {
3065             case 'click':
3066                 e.preventDefault(); // click in text field
3067             break;
3068
3069             case 'blur':
3070                 SE.folders.submitFolderRename(e);
3071             break;
3072
3073             case 'keypress':
3074                 var kc = e.browserEvent.keyCode;
3075                 switch(kc) {
3076                     case 13: // enter
3077                         e.preventDefault();
3078                         SE.folders.submitFolderRename(e);
3079                     break;
3080
3081                     case 27: // esc
3082                         e.preventDefault(e);
3083                         SE.folders.cancelFolderRename(e);
3084                     break;
3085                 }
3086             break;
3087         }
3088     },
3089     /**
3090     * Called when a node is clicked on in the folder tree
3091     * @param node, The node clicked on
3092     * @param e, The click event
3093     */
3094     handleClick : function(o) {
3095         var node = o.node;
3096         //If the click was on a sugar folder
3097         if (node.data.ieId == "folder") {
3098             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3099         }
3100         else {
3101             SE.listView.populateListFrame(node, node.data.ieId, false);
3102         }
3103        //eval(node.data.click);
3104        //debugger;
3105     },
3106
3107     /**
3108     * Called when a node is right-clicked on in the folder tree
3109     */
3110     handleRightClick : function(e) {
3111         YAHOO.util.Event.preventDefault(e);
3112                 //Get the Tree Node
3113                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3114                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3115
3116                 //If the click was on a sugar folder
3117         SE.clickedFolderNode = node;
3118         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3119                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3120                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3121                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3122                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3123                 menu.getItem(3).cfg.setProperty("disabled", false);
3124                 menu.getItem(4).cfg.setProperty("disabled", false);
3125                 menu.getItem(5).cfg.setProperty("disabled", false);
3126                 menu.getItem(6).cfg.setProperty("disabled", true);
3127                 //Group folder
3128                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3129                         menu.getItem(0).cfg.setProperty("disabled", true);
3130                         menu.getItem(1).cfg.setProperty("disabled", true);
3131                         menu.getItem(2).cfg.setProperty("disabled", true);
3132                         menu.getItem(3).cfg.setProperty("disabled", true);
3133                         menu.getItem(4).cfg.setProperty("disabled", true);
3134                 }
3135         if (node.data.protocol != null) {
3136                 menu.getItem(6).cfg.setProperty("disabled", false);
3137         }
3138                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3139                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3140                         //Sent or Draft folders
3141                         menu.getItem(3).cfg.setProperty("disabled", true);
3142                         menu.getItem(4).cfg.setProperty("disabled", true);
3143                         menu.getItem(5).cfg.setProperty("disabled", true);
3144                 }
3145
3146                 //For group with auto inbound, disable everything.
3147                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3148                 {
3149                     menu.getItem(0).cfg.setProperty("disabled", true);
3150                 menu.getItem(1).cfg.setProperty("disabled", true);
3151                 menu.getItem(2).cfg.setProperty("disabled", true);
3152                 menu.getItem(3).cfg.setProperty("disabled", true);
3153                 menu.getItem(4).cfg.setProperty("disabled", true);
3154                 menu.getItem(5).cfg.setProperty("disabled", true);
3155                 menu.getItem(6).cfg.setProperty("disabled", true);
3156                 }
3157
3158                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3159                 menu.show();
3160     },
3161
3162     /**
3163     * Called when a row is dropped on a node
3164     */
3165     handleDrop : function(rows, targetFolder) {
3166         var rowData = rows[0].getData();
3167         if (rowData.mbox != targetFolder.data.mbox) {
3168             var srcIeId = rowData.ieId;
3169             var srcFolder = rowData.mbox;
3170             var destIeId = targetFolder.data.ieId;
3171             var destFolder = targetFolder.data.mbox;
3172             var uids = [];
3173             for(var i=0; i<rows.length; i++) {
3174                 uids[i] = rows[i].getData().uid;
3175             }
3176             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3177         }
3178     },
3179
3180     /**
3181     * Called when something is dragged over a Folder Node
3182     */
3183     dragOver : function(dragObject) {
3184        return true;
3185     },
3186
3187     /**
3188      * Determines if a folder name is unique to the folder tree
3189      * @param string name
3190      */
3191     isUniqueFolderName : function(name) {
3192         uniqueFolder = true;
3193         var root = SE.tree.getRoot();
3194         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3195             if (this.attributes && this.attributes.ieId == "folder") {
3196                 if (this.attributes.text == name) {
3197                     uniqueFolder = false;
3198                     return false;
3199                 }
3200             }
3201         }, null, [name]);
3202         return uniqueFolder;
3203     },
3204
3205     /**
3206      * Makes async call to rename folder in focus
3207      * @param object e Event Object
3208      */
3209     submitFolderRename : function(newName) {
3210         if (trim(newName) == "") {
3211                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3212                 return false;
3213         }
3214                 newName = escape(newName);
3215         var node = SE.clickedFolderNode;
3216         var origName = node.data.text
3217         //Ignore no change
3218         if (newName == origName) {
3219             return true;
3220         }
3221         if(SE.folders.isUniqueFolderName(newName)) {
3222             overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3223             if (node.data.ieId == "folder") {
3224                 //Sugar Folder
3225                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3226             }
3227             else {
3228                 //IMAP folder or POP mailbox
3229                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3230                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3231                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3232             }
3233             return true;
3234         } else {
3235             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3236             return false;
3237         }
3238     },
3239
3240     moveFolder : function(folderId, parentFolderId) {
3241         if (folderId != parentFolderId)
3242         {
3243                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3244                     + folderId + "&newParentId=" + parentFolderId);
3245         }
3246     },
3247
3248     /**
3249      * makes async call to do a full synchronization of all accounts
3250      */
3251     synchronizeAccounts : function() {
3252         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3253             overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3254             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3255         }
3256     },
3257
3258     /**
3259      * Updates user's folder subscriptsion (Sugar only)
3260      * @param object SELECT DOM object in focus
3261      * @param string type of Folder selection
3262      */
3263     updateSubscriptions : function() {
3264         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3265
3266         var active = "";
3267
3268         select = document.getElementById('userFolders');
3269
3270         for(i=0; i<select.options.length; i++) {
3271             var opt = select.options[i];
3272              if(opt.selected && opt.value != "") {
3273                  if(active != "") {
3274                      active += "::";
3275                  }
3276                  active += opt.value;
3277              }
3278         }
3279
3280         //Add the group folder ids.
3281         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3282         for(i=0; i<group_folders.length; i++)
3283         {
3284             active += ("::" + group_folders[i]);
3285         }
3286
3287         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3288     },
3289     /**
3290      * Updates user's group folder subscriptsion (Sugar only)
3291      * @param ieID The group folder to add to the tree view
3292      */
3293     retrieveGroupFolderSubscriptions : function() {
3294
3295         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3296         var activeGroupFolders = "";
3297         var activeGroupIds = [];
3298         for(i=0;i<a_rs.length;i++)
3299         {
3300                 var t_record = a_rs[i];
3301                 var is_active = t_record.getData('is_active');
3302                 var isGroupFolder = t_record.getData('has_groupfolder');
3303                 var ieID = t_record.getData('id');
3304                 if( isGroupFolder )
3305                 {
3306                     if(is_active)
3307                       activeGroupIds.push(ieID);
3308                 }
3309         }
3310
3311         return activeGroupIds;
3312     }
3313
3314 };
3315
3316 SE.folders.checkEmail2 = function() {
3317     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3318 }
3319 ////    END FOLDERS OBJECT
3320 ///////////////////////////////////////////////////////////////////////////////
3321
3322
3323 ///////////////////////////////////////////////////////////////////////////////
3324 ////    SE.keys
3325 /**
3326  * Keypress Event capture and processing
3327  */
3328 SE.keys = {
3329     overall : function(e) {
3330         switch(e.charCode) {
3331             case 119: // "w"
3332                 if(e.ctrlKey || e.altKey) {
3333                     var focusRegion = SE.innerLayout.regions.center;
3334                     if(focusRegion.activePanel.closable == true) {
3335                         focusRegion.remove(focusRegion.activePanel);
3336                     }
3337                 }
3338             break;
3339         }
3340     }
3341 };
3342 ////    END SE.keys
3343 ///////////////////////////////////////////////////////////////////////////////
3344
3345
3346 ///////////////////////////////////////////////////////////////////////////////
3347 ////    SE.listView
3348 /**
3349  * ListView object methods and attributes
3350  */
3351 SE.listView = {
3352     currentRowId : -1,
3353
3354     /**
3355      * Fills the ListView pane with detected messages.
3356      */
3357     populateListFrame : function(node, ieId, forceRefresh) {
3358         SE.innerLayout.selectTab(0);
3359                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3360
3361         Dom.get('_blank').innerHTML = "";
3362         SE.grid.params['emailUIAction'] = 'getMessageList';
3363         SE.grid.params['mbox'] = node.data.mbox;
3364         SE.grid.params['ieId'] = ieId;
3365         forcePreview = true; // loads the preview pane with first item in grid
3366         SE.listView.refreshGrid();
3367     },
3368
3369     /**
3370      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3371      */
3372     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3373         SE.innerLayout.selectTab(0);
3374         Dom.get('_blank').innerHTML = "";
3375         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3376         SE.grid.params['ieId'] = node.data.id;
3377         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3378         SE.listView.refreshGrid();
3379     },
3380
3381     /**Mac
3382      * Sets sort order as user preference
3383      * @param
3384      */
3385     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3386         ieId = ieIdPassed;
3387         ieName = ieNamePassed;
3388         focusFolder = focusFolderPassed;
3389
3390         SE.util.clearHiddenFieldValues('emailUIForm');
3391         var previousSort = document.getElementById('sortBy').value;
3392
3393         document.getElementById('sortBy').value = sortBy;
3394         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3395         document.getElementById('focusFolder').value = focusFolder;
3396         document.getElementById('ieId').value = ieId;
3397
3398         if(sortBy == previousSort) {
3399             document.getElementById('reverse').value = '1';
3400         }
3401
3402         var formObject = document.getElementById('emailUIForm');
3403         YAHOO.util.Connect.setForm(formObject);
3404
3405         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3406     },
3407
3408
3409     /**
3410      * Enables click/arrow select of grid items which then populate the preview pane.
3411      */
3412     selectFirstRow : function() {
3413         SE.grid.selModel.selectFirstRow();
3414     },
3415
3416     selectLastRow : function() {
3417         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3418     },
3419
3420     setEmailListStyles : function() {
3421         SE.listView.boldUnreadRows();
3422         return;
3423         var ds = SE.grid.getStore();
3424         if (SE.grid.getSelections().length == 0) {
3425             document.getElementById('_blank').innerHTML = '';
3426         }
3427
3428         var acctMbox = '';
3429         if(typeof(ds.baseParams.mbox) != 'undefined') {
3430             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3431             var cm = SE.grid.getColumnModel();
3432             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3433                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3434                 //SE.grid.render();
3435             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3436                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3437                 //SE.grid.render();
3438             }
3439         }
3440         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3441         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3442
3443
3444         // 4/20/2007 added to hide overlay after search
3445         //hideOverlay();
3446         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3447             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3448             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3449             if (node) node.data.unseen = unread;
3450         }
3451         SE.accounts.renderTree();
3452
3453
3454         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3455         if(forcePreview && ds.totalCount > 0) {
3456             SE.detailView.getEmailPreview();
3457             forcePreview = false;
3458         }
3459     },
3460
3461     /**
3462      * Removes a row if found via its UID
3463      */
3464     removeRowByUid : function(uid) {
3465         uid = new String(uid);
3466         uids = uid.split(',');
3467         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3468
3469         for(j=0; j<uids.length; j++) {
3470             var theUid = uids[j];
3471             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3472                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3473                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3474                 }
3475             } // for
3476         }
3477     },
3478
3479     displaySelectedEmails : function(rows) {
3480         var dm = SE.grid.getDataModel();
3481         var uids = '';
3482
3483         for(i=0; i<rows.length; i++) {
3484             var rowIndex = rows[i].rowIndex;
3485             var metadata = dm.data[rowIndex];
3486
3487             if(uids != "") {
3488                 uids += ",";
3489             }
3490             uids += metadata[5];
3491
3492             // unbold unseen email
3493             this.unboldRow(rowIndex);
3494         }
3495
3496         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3497     },
3498
3499     /**
3500      * exception handler for data load failures
3501      */
3502     loadException : function(dataModel, ex, response) {
3503         //debugger;
3504     },
3505
3506     /**
3507      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3508      * @param string sourceIeId Email's source I-E id
3509      * @param string sourceFolder Email's current folder
3510      * @param destinationIeId Destination I-E id
3511      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3512      *
3513      * @param array emailUids Array of email's UIDs
3514      */
3515     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3516         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3517             overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3518         } else {
3519             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3520             // remove rows from visibility
3521             for(row in selectedRows) {
3522                 //SE.grid.getStore().remove(row);
3523             }
3524
3525             var baseUrl =    '&sourceIeId=' + sourceIeId +
3526                             '&sourceFolder=' + sourceFolder +
3527                             '&destinationIeId=' + destinationIeId +
3528                             '&destinationFolder=' + destinationFolder;
3529             var uids = '';
3530
3531             for(i=0; i<emailUids.length; i++) {
3532                 if(uids != '') {
3533                     uids += app_strings.LBL_EMAIL_DELIMITER;
3534                 }
3535                 uids += emailUids[i];
3536             }
3537             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3538                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3539             } else {
3540                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3541             }
3542         }
3543     },
3544
3545     /**
3546      * Unbolds text in the grid view to denote read status
3547      */
3548     markRead : function(index, record) {
3549         // unbold unseen email
3550         var row = SE.grid.getRecord(record);
3551         row.getData().seen = 1;
3552         SE.grid.getTrEl(record).style.fontWeight = "normal";
3553     },
3554
3555     /**
3556      * grid row output, bolding unread emails
3557      */
3558     boldUnreadRows : function() {
3559         // bold unread emails
3560         var trEl = SE.grid.getFirstTrEl();
3561         while(trEl != null) {
3562                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3563                         trEl.style.fontWeight = "bold";
3564                 else
3565                         trEl.style.fontWeight = "";
3566                 trEl = SE.grid.getNextTrEl(trEl);
3567         }
3568     },
3569
3570     /**
3571      * Show preview for an email if 1 and only 1 is selected
3572      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3573      */
3574     handleRowSelect : function(e) {
3575         if(e.selectedRows.length == 1) {
3576             SE.detailView.getEmailPreview();
3577         }
3578     },
3579
3580     handleDrop : function(e, dd, targetId, e2) {
3581         switch(targetId) {
3582             case 'htmleditordiv':
3583                 var rows = SE.grid.getSelectedRows();
3584                 if(rows.length > 0) {
3585                     SE.listView.displaySelectedEmails(rows);
3586                 }
3587             break;
3588
3589             default:
3590                 var targetElId = new String(targetId);
3591                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3592                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3593                 var dm = SE.grid.getDataModel();
3594                 var emailUids = new Array();
3595                 var destinationIeId = targetNode.data.ieId;
3596                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3597
3598
3599                 var rows = SE.grid.getSelectedRows();
3600                 // iterate through dragged rows
3601                 for(i=0; i<rows.length; i++) {
3602                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3603                     var rowIndex = rows[i].rowIndex;
3604                     var dataModelRow = dm.data[rowIndex];
3605                     var sourceIeId = dataModelRow[7];
3606                     var sourceFolder = dataModelRow[6];
3607                     emailUids[i] = dataModelRow[5];
3608                 }
3609
3610                 // event wrapped call - need FQ
3611                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3612                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3613             break;
3614         }
3615     },
3616
3617     /**
3618      * Hack-around to get double-click and single clicks to work on the grid
3619      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3620      */
3621     handleClick : function(o) {
3622         SUGAR.email2.grid.clearTextSelection();
3623
3624         var el = SUGAR.email2.grid.getSelectedRows();
3625
3626         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3627         if ( el.length == 1)
3628         {
3629            var rowId = el[0];
3630            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3631            SUGAR.email2.listView.currentRowIndex = rowId;
3632            clearTimeout(SUGAR.email2.detailView.previewTimer);
3633            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3634         }
3635     },
3636
3637     /**
3638      * Custom handler for double-click/enter
3639      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3640      */
3641     getEmail : function(e) {
3642         var rows = SE.grid.getSelectedRows();
3643         var row = SE.grid.getRecord(rows[0]).getData();
3644
3645         clearTimeout(SE.detailView.previewTimer);
3646         document.getElementById("_blank").innerHTML = "";
3647
3648         if(row.type != "draft") {
3649             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3650         } else {
3651             // circumventing yui-ext tab generation, let callback handler build new view
3652             SE.util.clearHiddenFieldValues('emailUIForm');
3653             //function(uid, mbox, ieId, setRead, destination) {
3654             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3655             document.getElementById('uid').value = row.uid; // uid;
3656             document.getElementById('mbox').value = row.mbox; // mbox;
3657             document.getElementById('ieId').value = row.ieId; // ieId;
3658
3659             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3660             AjaxObject.target = '_blank';
3661             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3662         }
3663     },
3664
3665     /**
3666      * Retrieves a row if found via its UID
3667      * @param string
3668      * @return int
3669      */
3670     getRowIndexByUid : function(uid) {
3671         uid = new String(uid);
3672         uids = uid.split(',');
3673
3674         for(j=0; j<uids.length; j++) {
3675             var theUid = uids[j];
3676
3677             for(i=0; i<SE.grid.getStore().data.length; i++) {
3678                 if(SE.grid.getStore().data[i].id == theUid) {
3679                     return i;
3680                 }
3681             }
3682         }
3683     },
3684
3685     /**
3686      * Returns the UID's of the seleted rows
3687      *
3688      */
3689      getUidsFromSelection : function() {
3690          var rows = SE.grid.getSelectedRows();
3691          var uids = [];
3692          /* iterate through available rows JIC a row is deleted - use first available */
3693          for(var i=0; i<rows.length; i++) {
3694                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3695          }
3696          return uids;
3697      },
3698
3699     refreshGrid : function() {
3700         SE.grid.getDataSource().sendRequest(
3701             SUGAR.util.paramsToUrl(SE.grid.params),
3702                 SE.grid.onDataReturnInitializeTable,
3703                 SE.grid
3704         );
3705     }
3706
3707 };
3708 ////    END SE.listView
3709 ///////////////////////////////////////////////////////////////////////////////
3710
3711 ///////////////////////////////////////////////////////////////////////////////
3712 ////    SEARCH
3713 SE.search = {
3714     /**
3715      * sends search criteria
3716      * @param reference element search field
3717      */
3718     search : function(el) {
3719         var searchCriteria = new String(el.value);
3720
3721         if(searchCriteria == '') {
3722             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3723             return false;
3724         }
3725
3726         var safeCriteria = escape(searchCriteria);
3727
3728         var accountListSearch = document.getElementById('accountListSearch');
3729         //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3730
3731         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3732         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3733         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3734         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3735         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3736
3737     },
3738
3739     /**
3740      * sends advanced search criteria
3741      */
3742     searchAdvanced : function() {
3743         var formObject = document.getElementById('advancedSearchForm');
3744         var search = false;
3745
3746         //Set assigned user id to blank if name is not present.
3747         if (formObject.elements['assigned_user_name'].value == "")
3748             formObject.elements['assigned_user_id'].value = "";
3749
3750         for(i=0; i<formObject.elements.length; i++) {
3751             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3752                 search = true;
3753             }
3754             if(formObject.elements[i].type == 'text') {
3755                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3756             }
3757             if(formObject.elements[i].type == 'hidden') {
3758                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3759             }
3760              if(formObject.elements[i].type == 'select-one') {
3761                 var el = formObject.elements[i];
3762                 var v = el.options[el.selectedIndex].value;
3763
3764                 if(v != "")
3765                     SE.grid.params[el.name] = v;
3766                 else
3767                 {
3768                     //Clear previous search results if necessary
3769                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3770                         delete SE.grid.params[el.name]
3771                 }
3772              }
3773         }
3774
3775         if (search)
3776         {
3777             if(! this.validateSearchFormInput() )
3778                 return;
3779
3780                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3781                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3782                 var accountListSearch = document.getElementById('accountListSearch');
3783                 SE.listView.refreshGrid();
3784         } else {
3785             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3786         }
3787     },
3788
3789     /**
3790     *  Validates the search form inputs to ensure all parameters are valid
3791     *  @return bool
3792     */
3793     validateSearchFormInput: function()
3794     {
3795         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3796         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3797         var dateCheck = check_form('advancedSearchForm');
3798
3799         //If the parent type is selected ensure the user selected a parent_id.
3800         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3801             return true;
3802         else
3803             return false;
3804     },
3805     /**
3806     *   Toggles the advanced options, either hidding or showing the selection.
3807     */
3808     toggleAdvancedOptions: function()
3809     {
3810         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3811
3812         for(var i=0;i<el.length;i++)
3813         {
3814             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3815                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3816             else
3817                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3818         }
3819     },
3820     /**
3821      * clears adv search form fields
3822      */
3823     searchClearAdvanced : function() {
3824         var form = document.getElementById('advancedSearchForm');
3825
3826         for(i=0; i<form.elements.length; i++) {
3827             if(form.elements[i].type != 'button') {
3828                 form.elements[i].value = '';
3829             }
3830         }
3831     }
3832 };
3833 ////    END SE.search
3834 //////////////////////////////////////////////////////////////////////////////
3835
3836
3837 //////////////////////////////////////////////////////////////////////////////
3838 ////    SE.settings
3839 SE.settings = {
3840     /******************************************************************************
3841      * USER SIGNATURES calls stolen from Users module
3842      *****************************************************************************/
3843     createSignature : function(record, the_user_id) {
3844         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3845         if(record != "") {
3846             URL += "&record="+record;
3847         }
3848         if(the_user_id != "") {
3849             URL += "&the_user_id="+the_user_id;
3850         }
3851         var windowName = 'email_signature';
3852         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3853
3854         var win = window.open(URL, windowName, windowFeatures);
3855         if(win && win.focus) {
3856             // put the focus on the popup if the browser supports the focus() method
3857             win.focus();
3858         }
3859     },
3860
3861     deleteSignature : function() {
3862         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3863             overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3864                 var singature_id = document.getElementById('signature_id').value;
3865                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3866         } // if
3867     },
3868
3869     saveOptionsGeneral :  function(displayMessage) {
3870         var formObject = document.getElementById('formEmailSettingsGeneral');
3871         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3872                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3873                 return false;
3874         } // if
3875         YAHOO.util.Connect.setForm(formObject);
3876         SE.composeLayout.emailTemplates = null;
3877
3878         AjaxObject.target = 'frameFlex';
3879         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3880
3881         if(displayMessage)
3882             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3883
3884         SE.settings.settingsDialog.hide();
3885     },
3886
3887     /**
3888      * Shows settings container screen
3889      */
3890     showSettings : function() {
3891         if(!SE.settings.settingsDialog) {
3892                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3893                 modal:true,
3894                 visible:false,
3895                 fixedcenter:true,
3896                 draggable: false,
3897                 width:"800px",
3898                                 constraintoviewport: true
3899             });
3900                         dlg.showEvent.subscribe( function (){
3901                                 var el = this.element;
3902                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3903                 if (this.header && el && viewH - 50 < el.clientHeight) {
3904                     var body = this.header.nextElementSibling;
3905                                         body.style.overflow = "auto";
3906                     body.style.height = (viewH - 50) + "px";
3907                 }
3908             }, dlg);
3909                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3910                 dlg.setBody('<div id="settingsTabDiv"/>');
3911                 dlg.beforeRenderEvent.subscribe(function() {
3912                         var dd = new YAHOO.util.DDProxy(dlg.element);
3913                         dd.setHandleElId(dlg.header);
3914                         dd.on('endDragEvent', function() {
3915                                 dlg.show();
3916                         });
3917                 }, dlg, true);
3918                 dlg.render();
3919
3920                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3921                         var tabContent = Dom.get("tab_general");
3922                 tp.addTab(new YAHOO.widget.Tab({
3923                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3924                                 scroll : true,
3925                                 content :  tabContent.innerHTML,
3926                                 id : "generalSettings",
3927                                 active : true
3928                         }));
3929                 tabContent.parentNode.removeChild(tabContent);
3930                 tabContent = Dom.get("tab_accounts");
3931                 var accountTab = new YAHOO.widget.Tab({
3932                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3933                                 scroll : true,
3934                                 content : tabContent.innerHTML,
3935                                 id : "accountSettings"
3936                         });
3937                 tp.addTab(accountTab);
3938                 tabContent.parentNode.removeChild(tabContent);
3939
3940                         tp.appendTo(dlg.body);
3941         }
3942
3943         SE.settings.settingsDialog.show();
3944         SE.folders.lazyLoadSettings();
3945         SE.accounts.lazyLoad();
3946     },
3947
3948
3949     lazyLoadRules : function() {
3950         if(false/*!SE.settings.rules*/) {
3951             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3952         }
3953
3954     }
3955
3956 };
3957 ////    END SE.settings
3958 ///////////////////////////////////////////////////////////////////////////////
3959 })();
3960
3961 /******************************************************************************
3962  * UTILITIES
3963  *****************************************************************************/
3964 function removeHiddenNodes(nodes, grid) {
3965     var el;
3966         for(var i = nodes.length - 1; i > -1; i--) {
3967         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3968         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3969                 nodes.splice(i,1);
3970        }
3971     }
3972 }
3973
3974 function strpad(val) {
3975     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3976 };
3977
3978 function refreshTodos() {
3979     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3980     AjaxObject.target = 'todo';
3981     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3982 };
3983
3984 /******************************************************************************
3985  * MUST STAY IN GLOBAL NAMESPACE
3986  *****************************************************************************/
3987 function refresh_signature_list(signature_id, signature_name) {
3988     var field=document.getElementById('signature_id');
3989     var bfound=0;
3990     for (var i=0; i < field.options.length; i++) {
3991             if (field.options[i].value == signature_id) {
3992                 if (field.options[i].selected==false) {
3993                     field.options[i].selected=true;
3994                 }
3995                 bfound=1;
3996             }
3997     }
3998     //add item to selection list.
3999     if (bfound == 0) {
4000         var newElement=document.createElement('option');
4001         newElement.text=signature_name;
4002         newElement.value=signature_id;
4003         field.options.add(newElement);
4004         newElement.selected=true;
4005     }
4006
4007     //enable the edit button.
4008     var field1=document.getElementById('edit_sig');
4009     field1.style.visibility="inherit";
4010     var deleteButt = document.getElementById('delete_sig');
4011     deleteButt.style.visibility="inherit";
4012 };
4013
4014 function setDefaultSigId(id) {
4015     var checkbox = document.getElementById("signature_default");
4016     var default_sig = document.getElementById("signatureDefault");
4017
4018     if(checkbox.checked) {
4019         default_sig.value = id;
4020     } else {
4021         default_sig.value = "";
4022     }
4023 };
4024
4025 function setSigEditButtonVisibility() {
4026     var field = document.getElementById('signature_id');
4027     var editButt = document.getElementById('edit_sig');
4028     var deleteButt = document.getElementById('delete_sig');
4029     if(field.value != '') {
4030         editButt.style.visibility = "inherit";
4031         deleteButt.style.visibility = "inherit";
4032     } else {
4033         editButt.style.visibility = "hidden";
4034         deleteButt.style.visibility = "hidden";
4035     }
4036 }// End of File modules/Emails/javascript/EmailUI.js
4037                                 
4038 /*********************************************************************************
4039  * SugarCRM is a customer relationship management program developed by
4040  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4041  * 
4042  * This program is free software; you can redistribute it and/or modify it under
4043  * the terms of the GNU Affero General Public License version 3 as published by the
4044  * Free Software Foundation with the addition of the following permission added
4045  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4046  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4047  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4048  * 
4049  * This program is distributed in the hope that it will be useful, but WITHOUT
4050  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4051  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4052  * details.
4053  * 
4054  * You should have received a copy of the GNU Affero General Public License along with
4055  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4056  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4057  * 02110-1301 USA.
4058  * 
4059  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4060  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4061  * 
4062  * The interactive user interfaces in modified source and object code versions
4063  * of this program must display Appropriate Legal Notices, as required under
4064  * Section 5 of the GNU Affero General Public License version 3.
4065  * 
4066  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4067  * these Appropriate Legal Notices must retain the display of the "Powered by
4068  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4069  * technical reasons, the Appropriate Legal Notices must display the words
4070  * "Powered by SugarCRM".
4071  ********************************************************************************/
4072
4073  (function() {
4074         var sw = YAHOO.SUGAR,
4075                 Event = YAHOO.util.Event,
4076                 Connect = YAHOO.util.Connect,
4077             Dom = YAHOO.util.Dom
4078             SE = SUGAR.email2;
4079
4080 ///////////////////////////////////////////////////////////////////////////////
4081 ////    ADDRESS BOOK
4082 SE.addressBook = {
4083     _contactCache : new Array(), // cache of contacts
4084     _dd : new Array(), // filtered list, same format as _contactCache
4085     _ddLists : new Array(), // list of Lists
4086     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4087     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4088     clickBubble : true, // hack to get around onclick event bubbling
4089         relatedBeanId : '',
4090         relatedBeanType : '',
4091         idx : 0,
4092
4093     itemSpacing : 'white-space:nowrap; padding:2px;',
4094     reGUID : SE.reGUID,
4095
4096
4097
4098     /**
4099     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4100     */
4101     initFixForDatatableSort: function () {
4102         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4103         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4104             var oColumn = this._oColumnSet.getColumn(column);
4105
4106             if(!oColumn) {
4107                 // Validate TD element
4108                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4109                 if(elCell) {
4110                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4111                 }
4112                 // Validate TH element
4113                 else {
4114                     elCell = this.getThEl(column);
4115                     if(elCell) {
4116                         // Find by TH el ID
4117                         var allColumns = this._oColumnSet.flat;
4118                         for(var i=0, len=allColumns.length; i<len; i++) {
4119                             if(allColumns[i].getThEl().id === elCell.id) {
4120                                 oColumn = allColumns[i];
4121                             }
4122                         }
4123                     }
4124                 }
4125             }
4126
4127             return oColumn;
4128         };
4129     },
4130
4131     cancelEdit : function() {
4132         if(this.editContactDialog)
4133             this.editContactDialog.hide();
4134         if(this.editMailingListDialog)
4135             this.editMailingListDialog.hide();
4136     },
4137
4138     /**
4139      * Clears filter form
4140      */
4141     clear : function() {
4142         var t = document.getElementById('contactsFilter');
4143         t.value = '';
4144         this.filter(t);
4145     },
4146
4147     /**
4148      * handle context-menu Compose-to call
4149      * @param string type 'contacts' or 'lists'
4150      */
4151     composeTo : function(type, waited) {
4152         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4153         if (activePanel.substring(0, 10) != "composeTab") {
4154             SE.composeLayout.c0_composeNewEmail();
4155             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4156                 SE.contextMenus.contactsContextMenu.hide();
4157             return;
4158         }
4159         var idx = activePanel.substring(10);
4160         var rows = [ ];
4161         var id = '';
4162         // determine if we have a selection to work with
4163         if(type == 'contacts') {
4164             var ids = SE.contactView.getSelectedRows();
4165             for (var i in ids) {
4166                 rows[i] = SE.contactView.getRecord(ids[i]);
4167             }
4168             removeHiddenNodes(rows, SE.contactView);
4169         } 
4170                 else { return; }
4171
4172         if(rows.length > 0) {
4173             SE.composeLayout.handleDrop(
4174                 (type == 'contacts') ? SE.contactView : SE.emailListsView, 
4175                 null, rows, 'addressTO' + idx );
4176         } else {
4177             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4178         }
4179     },
4180
4181     editContact : function() {
4182         SE.contextMenus.contactsContextMenu.hide();
4183         var element = SE.contactView.getSelectedNodes()[0];
4184         var elementId = "";
4185         if (element.className.indexOf('address-contact') > -1) {
4186             elementId = element.id;
4187         } else if (element.className.indexOf('address-exp-contact') > -1) {
4188             elementId = element.id.substring(2);
4189         }
4190     },
4191     
4192
4193     /**
4194      * Filters contact entries based on user input
4195      */
4196     filter : function(inputEl) {
4197         var ret = new Object();
4198         var re = new RegExp(inputEl.value, "gi");
4199
4200         for(var i in this._contactCache) {
4201             if(this._contactCache[i].name.match(re)) {
4202                 ret[i] = this._contactCache[i];
4203             }
4204         }
4205
4206         this.buildContactList(ret);
4207     },
4208
4209     fullForm : function(id, module) {
4210         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4211     },
4212
4213     /**
4214      * returns a formatted email address from the addressBook cache
4215      */
4216     getFormattedAddress : function(id) {
4217         var o = this._contactCache[id];
4218         var primaryEmail = '';
4219
4220         for(var i=0; i<o.email.length; i++) {
4221             var currentEmail = o.email[i].email_address;
4222
4223             if(o.email[i].primary_address == 1) {
4224                 primaryEmail = o.email[i].email_address;
4225             }
4226         }
4227
4228         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4229         var name = new String(o.name);
4230         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4231         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4232
4233         return ret;
4234     },
4235     
4236     /**
4237      * Sets up async call to query for matching contacts, users, etc.
4238      */
4239     searchContacts : function() {
4240         var fn = document.getElementById('input_searchField').value;
4241         var pe = document.getElementById('input_searchPerson').value;
4242         
4243         var rb = document.getElementById('hasRelatedBean').checked;
4244         if (rb) {
4245                         var idx = this.idx;
4246                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4247                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4248                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4249                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4250         } else {
4251                 this.addressBookDataModel.params['related_bean_id'] = '';
4252         }
4253         
4254         this.addressBookDataModel.params['search_field'] = fn;
4255         this.addressBookDataModel.params['person'] = pe;
4256         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4257         this.grid._oDataSource = this.addressBookDataModel;
4258         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4259     },
4260     
4261     /**
4262      * Clear Search Crieteria For Addressbook
4263      */
4264     clearAddressBookSearch : function() {
4265         document.getElementById('input_searchField').value = "";
4266         document.getElementById('input_searchPerson').selectedIndex = 0;
4267     },
4268     
4269     /**
4270      * Opens modal select window to add contacts to addressbook
4271      */
4272     selectContactsDialogue : function(destId) {
4273         if(!this.contactsDialogue) {
4274                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4275                 modal:true,
4276                 visible:false,
4277                 draggable: false,
4278                 constraintoviewport: true,
4279                 width   : 980,
4280                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4281                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4282             });
4283                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4284                 
4285                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4286                 dlg.setBody(body.innerHTML);
4287                 dlg.renderEvent.subscribe(function() {
4288                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4289                 if (iev && !SUGAR.isIE) {
4290                         this.body.style.width = "950px";
4291                 }
4292             }, dlg);
4293                      
4294             
4295                 dlg.beforeRenderEvent.subscribe(function() { 
4296                         var dd = new YAHOO.util.DDProxy(dlg.element); 
4297                         dd.setHandleElId(dlg.header); 
4298                         dd.on('endDragEvent', function() { 
4299                                 dlg.show(); 
4300                         }); 
4301                 }, dlg, true); 
4302                 dlg.render();
4303                 
4304                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4305                         
4306                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4307                 tp.addTab(new YAHOO.widget.Tab({
4308                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4309                                 scroll : true,
4310                                 content : tabContent.innerHTML,
4311                                 id : "addressSearchTab",
4312                                 active : true
4313                         }));
4314                         
4315                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4316                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4317                         if (e.keyCode == 13) {
4318                                 YAHOO.util.Event.stopEvent(e);
4319                                 SUGAR.email2.addressBook.searchContacts();
4320                         }
4321                 });
4322
4323                 this.contactsDialogue.render();
4324                 dlg.center();
4325         }
4326         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4327         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4328             var idx = 0;
4329         else
4330         {
4331             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4332             var idx = activePanel.substring(10);
4333         }
4334         SE.addressBook.idx = idx;
4335         
4336                 var relatedBeanId;
4337         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4338                 document.getElementById('relatedBeanColumn').style.display = '';
4339                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4340                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4341                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4342                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4343                         SE.addressBook.relatedBeanType = relatedBeanType;
4344             } else {
4345                 document.getElementById('relatedBeanColumn').style.display = 'none';
4346                 document.getElementById('hasRelatedBean').checked = false;
4347             }
4348             
4349             if (!SE.addressBook.grid) 
4350             {
4351                 if (hasRelatedBeanId) {
4352                         document.getElementById('hasRelatedBean').checked = true;
4353                 }
4354                 AddressSearchGridInit();
4355                         SE.addressBook.relatedBeanId = relatedBeanId;
4356             } 
4357             else
4358             {
4359                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4360                 {
4361                         SE.addressBook.relatedBeanId = relatedBeanId;
4362                         document.getElementById('hasRelatedBean').checked = true;
4363                 }
4364                 if (document.getElementById('hasRelatedBean').checked == true)
4365                 {
4366                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4367                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4368                 } else {
4369                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4370                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4371                 }
4372                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4373                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4374                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4375             }
4376             
4377             //Remove any lingering rows in the result set table if the module was closed.
4378             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4379             //Repopulate
4380             SE.addressBook.populateResulstTableEmailAddresses();
4381             
4382         this.contactsDialogue.show();
4383     },
4384     /**
4385     *  Clear all email addresses from result table.
4386     *
4387     */
4388     clearAllEmailAddressFieldsFromResultTable: function () {
4389         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4390         //Unhighlight any rows currently selected if the emails were cleared.
4391         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4392         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4393     },
4394     /**
4395     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the 
4396     *  results table.  This function is called when the address book is displayed.
4397     */
4398     populateResulstTableEmailAddresses: function () {
4399       
4400         var idx = SE.addressBook.idx;
4401         var emailFields = ['to','cc','bcc'];
4402         
4403         for(var k=0;k<emailFields.length;k++)
4404         {
4405             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4406             var allEmails = document.getElementById(elKey).value;
4407             if(allEmails == '')
4408                 continue;
4409             
4410             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4411             
4412                 for (var i=0; i<formatedEmails.length; i++)
4413                 {
4414                     var t_name = formatedEmails[i].name;
4415                     var t_emailAddr = formatedEmails[i].email_address;
4416                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4417                     if(t_name == '')
4418                         t_name = displayEmail = t_emailAddr;
4419                 
4420                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4421                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4422                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4423                 }
4424         }  
4425     },
4426  
4427     /**
4428     * Checks all entries in the result table against a particular email address, returning true
4429     * if the email address is found, false otherwise.
4430     */
4431     doesEmailAdddressExistInResultTable: function(emailAddress)
4432     {
4433         if(trim(emailAddress) == '')
4434             return false;   
4435             
4436         var emailAddressFound = false;
4437         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4438         for (var i=0; i < contacts.length; i++) 
4439         {
4440             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4441             //If we are adding to cc or bcc fields, make them visible.
4442             if(data.email_address == emailAddress)    
4443             {
4444                 emailAddressFound = true;
4445                 break;
4446             }
4447         }
4448         
4449         return emailAddressFound;
4450     },
4451     /**
4452     *  Takes all email addresses that the users wishes to add from the address book and populates the To 
4453     *  fields on the compose tab. 
4454     */
4455     populateEmailAddressFieldsFromResultTable: function()
4456     {
4457         //Clear the fields first, all email addresses are stored in the address book
4458         var idx = SE.addressBook.idx;
4459         var emailFields = ['to','cc','bcc'];    
4460         for(var k=0;k<emailFields.length;k++)
4461         {
4462             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4463             document.getElementById(elKey).value = "";
4464         }
4465         
4466         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4467         for (var i=0; i < contacts.length; i++) 
4468         {
4469             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4470             
4471             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4472             //If we are adding to cc or bcc fields, make them visible.
4473             if(addressTypeKey =='cc' || addressTypeKey =='bcc')    
4474                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4475             //Construct the target id
4476             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4477            
4478             var target = document.getElementById(target_id);
4479             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4480         }
4481         
4482         //Delete all rows from the result set table
4483         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4484         
4485         //Hide the dialogue
4486         SE.addressBook.contactsDialogue.hide()
4487     },
4488     /**
4489     *  Insert contacts into the result table.
4490     */
4491     insertContactToResultTable : function(event,address_type) {
4492     
4493         var contactsDialogue = SE.addressBook.contactsDialogue;
4494         var contacts = SE.addressBook.grid.getSelectedRows();
4495         
4496         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4497         for (var i = 0; i < rows.length; i++) 
4498         {
4499                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4500                         {
4501                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4502                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4503                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4504                 rows[i].setData("selected",true);
4505                         }
4506         }
4507         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4508         for (var i = 0; i < checkBoxes.length; i++) {
4509             checkBoxes[i].checked = false;
4510         }
4511     },
4512     /**
4513     *
4514     */
4515     insertContactRowToResultTable : function(rowId, addressType) {
4516         var data = SE.addressBook.grid.getRecord(rowId).getData();
4517         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4518                 return;
4519         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4520         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4521         if(addressType == null)
4522             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4523         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});
4524     },
4525     /**
4526     * Remove a row from the gridsResult table.
4527     */
4528     removeRowFromGridResults : function(rowId,emailAddress)
4529     {
4530         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4531         for (var i=0; i < contacts.length; i++) 
4532         {
4533             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4534             var data = rec.getData();
4535             if(data.email_address == emailAddress)
4536             {
4537                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4538                 break;
4539             }
4540         }
4541         
4542        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4543     },
4544     /**
4545     * Translates between the addressType To|Cc|Bcc labels/keys.  
4546     */
4547     translateAddresType: function(addressType,fromKey)
4548     {
4549         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4550         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4551         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,''); 
4552         var mappingObject = {};
4553         
4554         if(fromKey)
4555             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4556         else
4557         {
4558             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4559             mappingObject[displayCc] = 'cc';
4560             mappingObject[displayBcc] = 'bcc';
4561         }
4562             
4563         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4564           
4565     },
4566     /**
4567     *
4568     */
4569     toggleSearchRowIcon : function(rowId,show) 
4570     {
4571         if(show)
4572         {
4573             var idToShow = rowId + '_add_img';
4574             var idToHide = rowId + '_rm_img';
4575         }
4576         else
4577         {
4578             var idToShow = rowId + '_rm_img';
4579             var idToHide = rowId + '_add_img';
4580         }
4581
4582
4583         Dom.addClass(idToHide, "yui-hidden");
4584         Dom.removeClass(idToShow, "yui-hidden");
4585     },
4586     /**
4587     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4588     */
4589     doesGridResultsEntryExist: function(emailAddrs)
4590     {
4591         
4592         var contactExists = false;
4593         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4594         for (var i=0; i < contacts.length; i++) 
4595         {
4596             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4597             if(data.email_address == emailAddrs)
4598             {
4599                 contactExists = true;
4600                 break;
4601             }
4602         }
4603         return contactExists;
4604     },
4605     
4606     /**
4607      * adds an email address to a string, but first checks if it exists
4608      * @param string concat The string we are appending email addresses to
4609      * @param string addr Email address to add
4610      * @return string
4611      */
4612     smartAddEmailAddressToComposeField : function(concat, addr) {
4613         var re = new RegExp(addr);
4614
4615         if(!concat.match(re)) {
4616             if(concat != "") {
4617                 concat += "; " + addr;
4618             } else {
4619                 concat = addr;
4620             }
4621         }
4622
4623         return concat;
4624     }
4625 };
4626 ////    END ADDRESS BOOK
4627 ///////////////////////////////////////////////////////////////////////////////
4628
4629
4630
4631 ///////////////////////////////////////////////////////////////////////////////
4632 ////    AUTOCOMPLETE
4633 /**
4634  * Auto-complete object
4635  */
4636 SE.autoComplete = {
4637     config : {
4638         delimChar : [";", ","],
4639         useShadow :    false,
4640         useIFrame : false,
4641         typeAhead : true,
4642         prehighlightClassName : "yui-ac-prehighlight",
4643         queryDelay : 0
4644     },
4645     instances : new Array(),
4646
4647     /**
4648      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4649      * @param object Contact from AddressBook
4650      * @return string
4651      */
4652     getPrimaryAddress : function(contact) {
4653         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4654
4655         for(var eIndex in contact.email) {
4656             address = contact.email[eIndex].email_address;
4657             if(contact.email[eIndex].primary_address == 1) {
4658                 return contact.email[eIndex].email_address;
4659             }
4660         }
4661         return address;
4662     },
4663     
4664
4665     /**
4666      * initializes autocomplete widgets for a given compose view
4667      * @param int idx
4668      */
4669     init : function(idx) {
4670         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4671             "queryMatchContains" : false,
4672             "queryMatchSubset" : true
4673         });
4674
4675         this.instances[idx] = {
4676             to : null,
4677             cc : null,
4678             bcc : null
4679         };
4680
4681    
4682         // instantiate the autoComplete widgets
4683         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4684         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4685         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4686
4687         // enable hiding of interfering textareas
4688         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4689         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4690         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4691
4692         // enable reshowing of hidden textareas
4693         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4694         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4695         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4696
4697         // enable refreshes of contact lists
4698         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4699         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4700         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4701     },
4702
4703     refreshDataSource : function(sType, aArgs) {
4704         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4705         var idx;
4706         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4707
4708         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4709             idx = textBoxId.substr(9);
4710         } else {
4711             idx = textBoxId.substr(10);
4712         }
4713
4714         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4715         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4716         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4717     },
4718
4719     /**
4720      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4721      */
4722     returnDataSource : function(contacts) {
4723         var ret = new Array();
4724         for(var id in contacts) {
4725             if (contacts[id].name) {
4726                     var primary = this.getPrimaryAddress(contacts[id]);
4727         
4728                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4729                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4730         
4731                     for(var emailIndex in contacts[id].email) {
4732                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4733                     }
4734             }
4735         }
4736
4737         return ret;
4738     },
4739
4740     /**
4741      * Hides address textareas to prevent autocomplete dropdown from being obscured
4742      */
4743     toggleTextareaHide : function(sType, aArgs) {
4744         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4745         var type = "";
4746         var idx = -1;
4747
4748         if(textBoxId.indexOf("addressTO") > -1) {
4749             type = "to";
4750         } else if(textBoxId.indexOf("addressCC") > -1) {
4751             type = "cc";
4752         }
4753         idx = textBoxId.substr(9);
4754
4755         // follow through if not BCC
4756         if(type != "") {
4757             var cc = document.getElementById("addressCC" + idx);
4758             var bcc = document.getElementById("addressBCC" + idx);
4759
4760             switch(type) {
4761                 case "to":
4762                     cc.style.visibility = 'hidden';
4763                 case "cc":
4764                     bcc.style.visibility = 'hidden';
4765                 break;
4766             }
4767         }
4768     },
4769
4770     /**
4771      * Redisplays the textareas after an address is commited
4772      */
4773     toggleTextareaShow : function(sType, aArgs) {
4774         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4775         var type = "";
4776         var idx = -1;
4777
4778         if(textBoxId.indexOf("addressTO") > -1) {
4779             type = "to";
4780         } else if(textBoxId.indexOf("addressCC") > -1) {
4781             type = "cc";
4782         }
4783         idx = textBoxId.substr(9);
4784
4785         // follow through if not BCC
4786         if(type != "") {
4787             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4788             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4789         }
4790     }
4791 };
4792
4793 ////    END AUTOCOMPLETE
4794 ///////////////////////////////////////////////////////////////////////////////
4795
4796 ///////////////////////////////////////////////////////////////////////////////
4797 ////    COMPOSE & SEND
4798 /**
4799  * expands the options sidebar
4800  */
4801 SE.composeLayout = {
4802     currentInstanceId : 0,
4803     ccHidden : true,
4804     bccHidden : true,
4805     outboundAccountErrors : null,
4806     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4807
4808     showAddressDetails : function(e) {
4809         var linkElement = document.getElementById("More"+e.id);
4810         var spanElement = document.getElementById("Detail"+e.id);
4811         var emailAddressList = e.value;
4812         if(e.value.length > 96) 
4813         {
4814                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4815             var displayArray = [];
4816                 for (var i=0; i<resultArray.length; i++)
4817                 {
4818                     var t_name = resultArray[i].name;
4819                     var t_emailAddr = resultArray[i].email_address;
4820                     if(t_name == '')
4821                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4822                     else
4823                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');     
4824                 }
4825                         
4826             var result = displayArray.join('<br/>');
4827                 // Display
4828             linkElement.style.display = "inline";
4829             linkElement.style.height="10px";
4830             linkElement.style.overflow="visible";
4831             spanElement.innerHTML = result;
4832         } 
4833         else 
4834                 linkElement.style.display = "none";
4835         
4836         },
4837
4838    /**
4839     *  Given a string of email address, return an array containing the name portion (if available)
4840     *  and email portion.
4841     */
4842     _getEmailArrayFromString : function (emailAddressList){
4843       
4844         var reg = /@.*?;/g;
4845         while ((results = reg.exec(emailAddressList)) != null) 
4846         {
4847             orignial = results[0];
4848             parsedResult = results[0].replace(';', ':::::');
4849             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4850         }
4851
4852         reg = /@.*?,/g;
4853         while ((results = reg.exec(emailAddressList)) != null) 
4854         {
4855             orignial = results[0];
4856             parsedResult = results[0].replace(',', ':::::');
4857             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4858         }
4859         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4860         var emailArr = emailAddressList.split(":::::");
4861         var resultsArray = [];
4862         var newArr = [];
4863         for (var i=0; i<emailArr.length; i++) 
4864         {
4865             var rposition = emailArr[i].indexOf('<');
4866             var lposition = emailArr[i].indexOf('>');
4867
4868             if(trim(emailArr[i]) != '')
4869             {
4870                 if(rposition != -1 && lposition != -1)
4871                 {
4872                     var t_name = emailArr[i].substr(0, rposition-1);
4873                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4874                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4875                 }
4876                 else
4877                 {
4878                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4879                 }
4880             }
4881         }
4882         return resultsArray;  
4883     },
4884     ///////////////////////////////////////////////////////////////////////////
4885     ////    COMPOSE FLOW
4886     /**
4887      * Prepare bucket DIV and yui-ext tab panels
4888      */
4889     _0_yui : function() {
4890         var idx = this.currentInstanceId;
4891
4892         var composeTab = new YAHOO.SUGAR.ClosableTab({
4893                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4894                                 scroll : true,
4895                                 content : "<div id='htmleditordiv" + idx + "'/>",
4896                                 id : "composeTab" + idx,
4897                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4898                                 active : true
4899         }, SE.innerLayout);
4900         SE.innerLayout.addTab(composeTab);
4901         
4902         // get template engine with template
4903         if (!SE.composeLayout.composeTemplate) {
4904                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4905         }
4906         
4907         // create Tab inner layout
4908         var composePanel =  this.getComposeLayout();
4909         composePanel.getUnitByPosition("right").collapse();
4910         composePanel.autoSize();
4911        
4912     },
4913         /**
4914      * Generate the quick compose layout
4915          * @method getQuickComposeLayout
4916          * @param {Pannel} parentPanel Parent pannel
4917          * @param {Object} o Options
4918          * @return {} none
4919          **/
4920     getQuickComposeLayout : function (parentPanel,o) {
4921          var idx = SE.composeLayout.currentInstanceId;
4922
4923          //Before rendering the parent pannel we need to initalize the grid layout
4924          parentPanel.beforeRenderEvent.subscribe(function() {
4925                 
4926                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4927                         SE.composeLayout._createComposeLayout(idx);
4928                         SE.composeLayout[idx].set('height', 350);
4929                         SE.composeLayout[idx].render();
4930            });
4931         });
4932
4933          //Wait until the Compose Layout has rendered, then add the 
4934          //options tab and perform the tiny initialization.
4935          parentPanel.renderEvent.subscribe(function() {
4936                 
4937                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4938                 SE.composeLayout._initComposeOptionTabs(idx);
4939                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4940                 //Initialize tinyMCE
4941                 if (!SUGAR.util.isTouchScreen())
4942                     SE.composeLayout._1_tiny();
4943                 //Init templates and address book
4944                 SE.composeLayout._2_final();
4945
4946             SE.composeLayout.quickCreateComposePackage(o);      
4947
4948                 });
4949          });
4950                 
4951             //Check if we have the div override for the shortcut bar
4952         if(typeof o.menu_id != 'undefined') {
4953                    parentPanel.render(o.menu_id);    
4954             } else {
4955                    parentPanel.render(document.body); 
4956             }
4957         
4958         return SE.composeLayout[idx];
4959     },
4960     /**
4961      * Fill in all fields into the quick compose layout.
4962          * @method quickCreateComposePackage
4963          * @param {Object} o Options
4964          * @return {} none
4965          **/
4966     quickCreateComposePackage: function(o)
4967     {
4968         //If we have a compose package fill in defaults.
4969         if (typeof(o.composePackage) != 'undefined')
4970         {
4971             composePackage = o.composePackage; //Set the compose data object
4972             //Hijack this method called by composePackage as it's not need for quick creates.
4973             SE.composeLayout.c0_composeNewEmail = function(){};
4974             SE.composeLayout.composePackage(); //Fill in defaults.
4975         }
4976     },
4977     getComposeLayout : function() {
4978         var idx = SE.composeLayout.currentInstanceId;
4979       
4980         this._createComposeLayout(idx); 
4981         SE.composeLayout[idx].render();
4982         this._initComposeOptionTabs(idx);
4983         
4984         return SE.composeLayout[idx];
4985         },
4986         
4987         /**
4988         *       Create the layout manager for the compose window.
4989         */
4990         _createComposeLayout : function(idx)
4991         {
4992                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4993                 parent: SE.complexLayout,
4994                 border:true,
4995             hideOnLayout: true,
4996             height: 400,
4997                         units: [{
4998                                         position: "center",
4999                         animate: false,
5000                         scroll: false,
5001                         split:true,
5002                         body:   
5003                                 SE.composeLayout.composeTemplate.exec({
5004                                 'app_strings':app_strings,
5005                                 'mod_strings':mod_strings,
5006                                 'theme': theme,
5007                                 'linkbeans_options' : linkBeans,
5008                                 'idx' : SE.composeLayout.currentInstanceId
5009                                 })
5010                     },{
5011                         position: "right",
5012                                     scroll:true,
5013                                     collapse: true,
5014                                     collapsed: true,
5015                                     resize: true,
5016                                     border:true,
5017                                     animate: false,
5018                                     width:'230',
5019                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5020                                     titlebar: true,
5021                                     split: true,
5022                                     header: app_strings.LBL_EMAIL_OPTIONS
5023                     }]
5024                 });
5025         },
5026         
5027         /**
5028         *  Create compose tab which will populate the 'right' container in the compose window.
5029         */
5030         _initComposeOptionTabs : function(idx) 
5031         {
5032                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5033                 var tab = new YAHOO.widget.Tab({ 
5034                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5035                                 scroll : true,
5036                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5037                                 id : "divAttachments" + idx,
5038                                 active : true
5039                         });
5040         
5041                 tab.layout = SE.composeLayout[idx];
5042
5043            tab.on("activeChange", function(o){ 
5044                         if (o.newValue) {
5045                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5046                         }
5047                 });
5048
5049                 cTabs.addTab(tab);
5050
5051                 tab = new YAHOO.widget.Tab({ 
5052                                 label: app_strings.LBL_EMAIL_OPTIONS,
5053                                 scroll : true,
5054                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5055                                 id : "divOptions" + idx,
5056                                 active : false
5057                         });
5058                 
5059                 tab.layout = SE.composeLayout[idx];
5060                 tab.on("activeChange", function(o){ 
5061                         if (o.newValue) {
5062                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5063                         }
5064                 });
5065                 cTabs.addTab(tab);
5066         
5067                 SE.composeLayout[idx].autoSize = function() {
5068                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5069                         this.set("height", pEl.clientHeight-30);
5070                         this.render();
5071                 }
5072         
5073                 SE.composeLayout[idx].rightTabs = cTabs;
5074     },
5075     isParentTypeValid : function(idx) {
5076                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5077                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5078                 if (trim(parentTypeValue) == ""){
5079                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5080                         return false;
5081                 } // if
5082                 return true;
5083     },
5084     
5085     isParentTypeAndNameValid : function(idx) {
5086                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5087                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5088                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5089                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") || 
5090                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5091                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5092                         return false;
5093                 } // if
5094                 return true;
5095     },
5096
5097     callopenpopupForEmail2 : function(idx,options) {
5098         
5099         var formName = 'emailCompose' + idx;
5100         
5101         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5102             formName = options.form_name;   
5103             
5104                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5105                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5106                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5107                         return;
5108                 } // if
5109                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5110                 {
5111                         call_back_function:"SE.composeLayout.popupAddEmail",
5112                         form_name:formName,
5113                         field_to_name_array:{
5114                                 id:'data_parent_id' + idx,
5115                                 name:'data_parent_name' + idx,
5116                                 email1:'email1'}
5117                 });     
5118         },    
5119         
5120         popupAddEmail : function(o)
5121         {
5122                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5123                 var data = o.name_to_value_array;
5124                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != "" 
5125                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5126         {
5127                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5128                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5129         }
5130                 set_return(o);
5131         },
5132     /**
5133      * Prepare TinyMCE
5134      */
5135     _1_tiny : function() {
5136         var idx = SE.composeLayout.currentInstanceId;
5137         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5138         SE.tinyInstances[elId] = { };
5139         SE.tinyInstances[elId].ready = false;
5140         var t = tinyMCE.getInstanceById(elId);
5141
5142         if(typeof(t) == 'undefined')  {
5143             tinyMCE.execCommand('mceAddControl', false, elId);
5144             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5145                 SE.composeLayout.resizeEditor(idx);
5146                 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5147             }, this);
5148         }
5149     },
5150     
5151     resizeEditor : function(idx)
5152     {
5153         var cof = Dom.get('composeOverFrame' + idx);
5154         var head = Dom.get('composeHeaderTable' + idx);
5155         var targetHeight = cof.clientHeight - head.clientHeight;
5156         var instance =  tinyMCE.get(SE.tinyInstances.currentHtmleditor);                
5157         
5158         var parentEl = Dom.get(instance.editorId + '_parent');
5159         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5160         var contentEl  = instance.contentAreaContainer;
5161         var iFrame = contentEl.firstChild;
5162         var tinMceToolbarOffset = 18;
5163         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5164     },
5165
5166     /**
5167      * Initializes d&d, auto-complete, email templates
5168      */
5169     _2_final : function() {
5170         var idx = SE.composeLayout.currentInstanceId;
5171
5172         if(this.emailTemplates) {
5173             this.setComposeOptions(idx);
5174         } else {
5175             //populate email template cache
5176             AjaxObject.target = '';
5177             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5178         }
5179
5180         // handle drop targets for addressBook
5181        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5182        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5183        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5184        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5185
5186         // auto-complete setup
5187         SE.autoComplete.init(idx);
5188
5189         // set focus on to:
5190         document.getElementById("addressTO" + idx).focus();
5191     },
5192
5193         /**
5194      * hide tinyMCE tool bar if send email as plaintext is checked
5195      */
5196     renderTinyMCEToolBar : function (idx, hide) {
5197         if (hide) {
5198                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5199         } else {
5200                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5201         }
5202     },
5203
5204     c1_composeEmail : function(isReplyForward, retry) {
5205         if (!retry) {
5206             this._0_yui();
5207         }
5208         if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5209             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5210         } else {
5211                 this._1_tiny();
5212                 this._2_final();
5213         
5214                 if(isReplyForward) {
5215                     this.replyForwardEmailStage2();
5216                 }
5217         }
5218     },
5219
5220     /**
5221      * takes draft info and prepopulates
5222      */
5223     c0_composeDraft : function() {
5224         this.getNewInstanceId();
5225         inCompose = true;
5226         document.getElementById('_blank').innerHTML = '';
5227         var idx = SE.composeLayout.currentInstanceId;
5228                 SE.composeLayout.draftObject = new Object();
5229                 SE.composeLayout.draftObject.id = idx;
5230                 SE.composeLayout.draftObject.isDraft = true;
5231         SE.composeLayout.currentInstanceId = idx;
5232         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5233         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5234         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5235
5236         SE.composeLayout._0_yui();
5237         SE.composeLayout._1_tiny();
5238
5239         // final touches
5240         SE.composeLayout._2_final();
5241
5242         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5243         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5244     },
5245
5246     /**
5247      * Strip & Prep editor hidden fields
5248      */
5249     c0_composeNewEmail : function() {
5250         this.getNewInstanceId();
5251         this.c1_composeEmail(false);
5252     },
5253
5254     /**
5255      * Sends async request to get the compose view.
5256      * Requests come from "reply" or "forwards"
5257      */
5258     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5259         SE.composeLayout.replyForwardObj = new Object();
5260         SE.composeLayout.replyForwardObj.ieId = ieId;
5261         SE.composeLayout.replyForwardObj.uid = uid;
5262         SE.composeLayout.replyForwardObj.mbox = mbox;
5263         SE.composeLayout.replyForwardObj.type = type;
5264
5265         if(mbox == 'sugar::Emails') {
5266             SE.composeLayout.replyForwardObj.sugarEmail = true;
5267         }
5268
5269         SE.composeLayout.getNewInstanceId();
5270         SE.composeLayout.c1_composeEmail(true);
5271     },
5272     ////    END COMPOSE FLOW
5273     ///////////////////////////////////////////////////////////////////////////
5274
5275     /**
5276      * Called when a contact, email, or mailinglist is dropped
5277      * into one of the compose fields.
5278      */
5279     handleDrop : function (source, event, data, target) {
5280         var nodes;
5281         if (!target) {
5282             target = event.getTarget();
5283             if (data.single) {
5284                 data.nodes = [data.nodes];
5285             }
5286             nodes = data.nodes;
5287         } else {
5288             target = document.getElementById(target);
5289             nodes = data;
5290         }
5291         
5292         if (target.id.indexOf('address') > -1) {
5293             // dropped onto email to/cc/bcc field
5294             for(var i in nodes) {
5295                 var node = nodes[i].getData();
5296                 var email = "";
5297                 if (node[1].indexOf('contact') > -1) {
5298                     email = SE.addressBook.getFormattedAddress(node[0]);
5299                 } else if (node[1].indexOf('address-email') > -1){
5300                     email = node[3].replace(/&nbsp;/gi, '');
5301                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5302                     var tr = source.getTrEl(nodes[i]);
5303                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5304                         tr = source.getPreviousTrEl(tr);
5305                     }
5306                     var CID = source.getRecord(tr).getData()[0];
5307                     var o = SE.addressBook._contactCache[CID];
5308                     var name = new String(o.name);
5309                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5310                     email = finalName + email;
5311                 }
5312                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);              
5313             }
5314         }
5315     },
5316
5317
5318     /*/////////////////////////////////////////////////////////////////////////////
5319     ///    EMAIL TEMPLATE CODE
5320      */
5321     applyEmailTemplate : function (idx, id) {
5322                 
5323         //bug #20680
5324         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5325                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5326                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5327                 //Bug #6224
5328                 var to_addr = document.getElementById('addressTO'+idx);
5329                 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1) {
5330                         box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5331                         box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5332                 }
5333                 
5334                 // id is selected index of email template drop-down
5335                 if(id == '' || id == "0") {
5336                         YAHOO.SUGAR.MessageBox.show({
5337                    title:box_title,
5338                    msg: box_none_msg,
5339                    type: 'confirm',
5340                    fn: function(btn){
5341                                 if(btn=='no'){return;};                         
5342                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5343                    modal:true,
5344                    scope:this
5345                });
5346                return;
5347                 } 
5348         
5349                 YAHOO.SUGAR.MessageBox.show({
5350            title:box_title,
5351            msg: box_msg,
5352            type: 'confirm',
5353            fn: function(btn){
5354                         if(btn=='no'){return;};
5355                         SUGAR.email2.composeLayout.processResult(idx, id);},
5356            modal:true,
5357            scope:this
5358        });
5359     },
5360     
5361     processNoneResult : function(idx, id) {
5362         var tiny = SE.util.getTiny('htmleditor' + idx);
5363         var tinyHTML = tiny.getContent();
5364         var openTag = '<div><span><span>';
5365         var htmllow = tinyHTML.toLowerCase();
5366         var start = htmllow.indexOf(openTag);
5367                 if (start > -1) {
5368                 tinyHTML = tinyHTML.substr(start);
5369                 tiny.setContent(tinyHTML);
5370                 } else {
5371                 tiny.setContent('');
5372                 }       
5373     },
5374         
5375         processResult : function(idx , id){
5376         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5377
5378         // get attachments if any
5379         AjaxObject.target = '';
5380         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5381     },
5382
5383     appendEmailTemplateJSON : function() {
5384         var idx = SE.composeLayout.currentInstanceId; // post increment
5385
5386         // query based on template, contact_id0,related_to
5387         //jchi 09/10/2008 refix #7743
5388         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5389             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5390         }
5391
5392         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,'"');
5393
5394         // cn: bug 14361 - text-only templates don't fill compose screen
5395         if(text == '') {
5396             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/>");
5397         }
5398
5399         var tiny = SE.util.getTiny('htmleditor' + idx);
5400         var tinyHTML = tiny.getContent();
5401         var openTag = '<div><span><span>';
5402         var closeTag = '</span></span></div>';
5403         var htmllow = tinyHTML.toLowerCase();
5404         var start = htmllow.indexOf(openTag);
5405                 if (start > -1) {
5406                 var htmlPart2 = tinyHTML.substr(start);
5407                 tinyHTML = text + htmlPart2;
5408                 tiny.setContent(tinyHTML);
5409                 } else {
5410                 tiny.setContent(text);
5411                 }
5412     },
5413
5414     /**
5415      * Writes out the signature in the email editor
5416      */
5417     setSignature : function(idx) {
5418         if (!tinyMCE)
5419             return false;
5420         var hide = document.getElementById('setEditor' + idx).checked;
5421         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5422         //wait for signatures to load before trying to set them
5423         if (!SE.composeLayout.signatures) {
5424             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5425                         return;
5426         }
5427             
5428         if(idx) {
5429             var sel = document.getElementById('signatures' + idx);
5430         } else {
5431             var sel = document.getElementById('signature_id');
5432             idx = SE.tinyInstances.currentHtmleditor;
5433         }
5434         
5435         //Ensure that the tinyMCE html has been rendered.
5436         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5437             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5438                     return;
5439                 }
5440             
5441         var signature = '';
5442
5443         try {
5444             signature = sel.options[sel.selectedIndex].value;
5445         } catch(e) {
5446
5447         }
5448
5449         var openTag = '<div><span><span>';
5450         var closeTag = '</span></span></div>';
5451         var t = SE.util.getTiny('htmleditor' + idx);
5452         //IE 6 Hack
5453         if(typeof(t) != 'undefined')
5454         {
5455             t.contentDocument = t.contentWindow.document;
5456             var html = t.getContent();
5457         }
5458         else
5459             var html = '';
5460             
5461         var htmllow = html.toLowerCase();
5462         var start = htmllow.indexOf(openTag);
5463         var end = htmllow.indexOf(closeTag) + closeTag.length;
5464
5465         // selected "none" - remove signature from email
5466         if(signature == '') {
5467             if (start > -1) {
5468                 var htmlPart1 = html.substr(0, start);
5469                 var htmlPart2 = html.substr(end, html.length);
5470     
5471                 html = htmlPart1 + htmlPart2;
5472                 t.setContent(html);
5473             }
5474             SE.signatures.lastAttemptedLoad = '';
5475             return false;
5476         }
5477
5478         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5479             SE.signatures.lastAttemptedLoad = '';
5480
5481         SE.signatures.lastAttemptedLoad = signature;
5482
5483         if(typeof(SE.signatures[signature]) == 'undefined') {
5484             //lazy load
5485             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5486             SE.signatures.targetInstance = (idx) ? idx : "";
5487             AjaxObject.target = '';
5488             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5489         } else {
5490             var newSignature = this.prepareSignature(SE.signatures[signature]);
5491
5492             // clear out old signature
5493             if(SE.signatures.lastAttemptedLoad && start > -1) {
5494                 var htmlPart1 = html.substr(0, start);
5495                 var htmlPart2 = html.substr(end, html.length);
5496
5497                 html = htmlPart1 + htmlPart2;
5498             }
5499             
5500             // [pre|ap]pend
5501                         start = html.indexOf('<div><hr></div>');
5502             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5503                                 var htmlPart1 = html.substr(0, start);
5504                                 var htmlPart2 = html.substr(start, html.length);
5505                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5506             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5507                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5508             } else {
5509                 var newHtml = html + openTag + newSignature + closeTag;
5510             }
5511             //tinyMCE.setContent(newHtml);
5512             t.setContent(newHtml);
5513         }
5514     },
5515
5516     prepareSignature : function(str) {
5517         var signature = new String(str);
5518
5519         signature = signature.replace(/&lt;/gi, '<');
5520         signature = signature.replace(/&gt;/gi, '>');
5521
5522         return signature;
5523     },
5524
5525
5526     showAttachmentPanel : function(idx) {
5527         var east = SE.composeLayout[idx].getUnitByPosition("right");
5528         var tabs = SE.composeLayout[idx].rightTabs;
5529         east.expand();
5530         tabs.set("activeTab", tabs.getTab(0));
5531     },
5532
5533     /**
5534      * expands sidebar and displays options panel
5535      */
5536     showOptionsPanel : function(idx) {
5537         var east = SE.composeLayout[idx].getUnitByPosition("right");
5538         var tabs = SE.composeLayout[idx].rightTabs;
5539         east.expand();
5540         tabs.set("activeTab", tabs.getTab(1));
5541     },
5542
5543     /**
5544      * Selects the Contacts tab
5545      */
5546     showContactsPanel : function() {
5547         SE.complexLayout.regions.west.showPanel("contactsTab");
5548     },
5549
5550     /**
5551      * Generates fields for Select Document
5552      */
5553     addDocumentField : function(idx) {
5554         var basket = document.getElementById('addedDocuments' + idx);
5555         if(basket) {
5556             var index = (basket.childNodes.length / 7) - 1;
5557             if(index < 0)
5558                 index = 0;
5559         } else {
5560             index = 0;
5561         }
5562
5563         var test = document.getElementById('documentId' + idx + index);
5564
5565         while(test != null) {
5566             index++;
5567             test = document.getElementById('documentId' + idx + index);
5568         }
5569         
5570         var documentCup = document.createElement("div");
5571         documentCup.id = 'documentCup' + idx + index;
5572         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5573                 // document id field
5574                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5575                 // document name field
5576                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5577                 // select button
5578                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" + 
5579                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5580                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5581                 // remove button
5582                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" + 
5583                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" + 
5584                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +   
5585                 "<br/>";
5586         
5587         basket.appendChild(documentCup);
5588         //basket.innerHTML += out;
5589         return index;
5590     },
5591
5592     /**
5593      * Makes async call to save a draft of the email
5594      * @param int Instance index
5595      */
5596     saveDraft : function(tinyInstance) {
5597         this.sendEmail(tinyInstance, true);
5598     },
5599
5600     selectDocument : function(target) {
5601         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5602         windowName = 'selectDocument';
5603         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5604
5605         win = window.open(URL, windowName, windowFeatures);
5606         if(window.focus) {
5607             // put the focus on the popup if the browser supports the focus() method
5608             win.focus();
5609         }
5610     },
5611
5612     /**
5613      * Modal popup for file attachment dialogue
5614      */
5615     addFileField : function() {
5616         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5617             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5618                 modal:true,
5619                 visible:false,
5620                 fixedcenter:true,
5621                 constraintoviewport: true,
5622                 scroll: true,
5623                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, { 
5624                         fn:function(){SE.addFileDialog.hide();}
5625                 })
5626             });
5627             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5628             SE.addFileDialog.render();
5629            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5630         }
5631         Dom.removeClass("addFileDialog", "yui-hidden");
5632         
5633         SE.addFileDialog.show();
5634     },
5635
5636     /**
5637      * Async upload of file to temp dir
5638      */
5639     uploadAttachment : function() {
5640         if(document.getElementById('email_attachment').value != "") {
5641             var formObject = document.getElementById('uploadAttachment');
5642             YAHOO.util.Connect.setForm(formObject, true, true);
5643             AjaxObject.target = '';
5644             AjaxObject.startRequest(callbackUploadAttachment, null);
5645         } else {
5646             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5647         }
5648     },
5649
5650     /**
5651      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5652      * @param string target in focus compose layout
5653      */
5654     setDocument : function(idx, target, documentId, documentName, docRevId) {
5655         // fields are named/id'd [fieldName][instanceId][index]
5656         var addedDocs = document.getElementById("addedDocuments" + idx);
5657         var docId = document.getElementById('documentId' + idx + target);
5658         var docName = document.getElementById('documentName' + idx + target);
5659         var docRevisionId = document.getElementById('document' + idx + target);
5660         docId.value = documentId;
5661         docName.value = documentName;
5662         docRevisionId.value = docRevId;
5663     },
5664
5665     /**
5666      * Removes the bucket div containing the document input fields
5667      */
5668     deleteDocumentField : function(documentCup) {
5669         var f0 = document.getElementById(documentCup);
5670         f0.parentNode.removeChild(f0);
5671     },
5672
5673     /**
5674      * Removes a Template Attachment field
5675      * @param int
5676      * @param int
5677      */
5678     deleteTemplateAttachmentField : function(idx, index) {
5679         // create not-in-array values for removal filtering
5680         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5681
5682         if(r != "") {
5683             r += "::";
5684         }
5685
5686         r += document.getElementById('templateAttachmentId' + idx + index).value;
5687         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5688
5689         var target = 'templateAttachmentCup' + idx + index;
5690         d =  document.getElementById(target);
5691         d.parentNode.removeChild(d);
5692     },
5693
5694     /**
5695      * Async removal of uploaded temp file
5696      * @param string index Should be a concatenation of idx and index
5697      * @param string
5698      */
5699     deleteUploadAttachment : function(index, file) {
5700         var d = document.getElementById('email_attachment_bucket' + index);
5701         d.parentNode.removeChild(d);
5702
5703         // make async call to delete cached file
5704         AjaxObject.target = '';
5705         AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5706     },
5707
5708     /**
5709      * Attaches files coming from Email Templates
5710      */
5711     addTemplateAttachmentField : function(idx) {
5712         // expose title
5713         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5714
5715         var basket = document.getElementById('addedTemplateAttachments' + idx);
5716
5717         if(basket) {
5718             var index = basket.childNodes.length;
5719             if(index < 0)
5720                 index = 0;
5721         } else {
5722             index = 0;
5723         }
5724
5725         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5726                                 // remove button        
5727                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5728                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" + 
5729                                         idx + "\",\"" + index + "\");'/>" +
5730                                 // file icon
5731                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5732                                 // templateAttachment field
5733                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5734                                 // docId field
5735                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5736                                 // file name
5737                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" + 
5738                                 "<br id='br" + index + "></br>" + 
5739                                 "<br id='brdoc" + index + "></br>" + 
5740                         "</div>";
5741                 basket.innerHTML = basket.innerHTML + out;
5742      
5743         return index;
5744     },
5745
5746     /**
5747      * Sends one email via async call
5748      * @param int idx Editor instance ID
5749      * @param bool isDraft
5750      */
5751     sendEmail : function(idx, isDraft) {
5752         
5753         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5754         var obAccountID = document.getElementById('addressFrom' + idx).value;
5755         
5756         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5757         {
5758             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5759             return false;
5760         }
5761         
5762         
5763         var form = document.getElementById('emailCompose' + idx);
5764         var composeOptionsFormName = "composeOptionsForm" + idx;
5765         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5766         var html = t.getContent();
5767         var subj = document.getElementById('emailSubject' + idx).value;
5768         var to = trim(document.getElementById('addressTO' + idx).value);
5769         var cc = trim(document.getElementById('addressCC' + idx).value);
5770         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5771         var email_id = document.getElementById('email_id' + idx).value;
5772         var composeType = document.getElementById('composeType').value;
5773         var parent_type = document.getElementById("parent_type").value;
5774         var parent_id = document.getElementById("parent_id").value;
5775         
5776         var el_uid = document.getElementById("uid");
5777         var uid = (el_uid == null) ? '' : el_uid.value;
5778         
5779         var el_ieId = document.getElementById("ieId");
5780         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5781         
5782         var el_mbox = document.getElementById("mbox");
5783         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5784         
5785         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5786                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5787                 return false;
5788         }
5789
5790         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5791                 return;
5792         } // if
5793                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5794                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5795         parent_id = parentIdValue;
5796         parent_type = parentTypeValue;
5797
5798         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5799         // baseline viability check
5800
5801         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5802             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5803             return false;
5804         } else if(subj == '' && !isDraft) {
5805             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5806                 return false;
5807             } else {
5808                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5809             }
5810         } else if(html == '' && !isDraft) {
5811             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5812                 return false; 
5813             }
5814         }
5815
5816         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5817                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5818                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5819         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5820         html = html.replace(/&lt;/ig, "sugarLessThan");       
5821         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5822         
5823         form.sendDescription.value = html;
5824         form.sendSubject.value = subj;
5825         form.sendTo.value = to;
5826         form.sendCc.value = cc;
5827         form.sendBcc.value = bcc;
5828         form.email_id.value = email_id;
5829         form.composeType.value = composeType;
5830         form.composeLayoutId.value = 'composeLayout' + idx;
5831         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5832         form.saveToSugar.value = 1;
5833         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5834         form.parent_type.value = parent_type;
5835         form.parent_id.value = parent_id;
5836         form.uid.value = uid;
5837         form.ieId.value = ieId;
5838         form.mbox.value = mbox;
5839
5840         // email attachments
5841         var addedFiles = document.getElementById('addedFiles' + idx);
5842         if(addedFiles) {
5843             for(i=0; i<addedFiles.childNodes.length; i++) {
5844                 var bucket = addedFiles.childNodes[i];
5845
5846                 for(j=0; j<bucket.childNodes.length; j++) {
5847                     var node = bucket.childNodes[j];
5848                     var nName = new String(node.name);
5849
5850                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5851                         if(form.attachments.value != '') {
5852                             form.attachments.value += "::";
5853                         }
5854                         form.attachments.value += node.value;
5855                     }
5856                 }
5857             }
5858         }
5859
5860         // sugar documents
5861         var addedDocs = document.getElementById('addedDocuments' + idx);
5862         if(addedDocs) {
5863             for(i=0; i<addedDocs.childNodes.length; i++) {
5864                 var cNode = addedDocs.childNodes[i];
5865                 for(j=0; j<cNode.childNodes.length; j++) {
5866                     var node = cNode.childNodes[j];
5867                     var nName = new String(node.name);
5868                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5869                         if(form.documents.value != '') {
5870                             form.documents.value += "::";
5871                         }
5872                         form.documents.value += node.value;
5873                     }
5874                 }
5875             }
5876         }
5877
5878         // template attachments
5879         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5880         if(addedTemplateAttachments) {
5881             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5882                 var cNode = addedTemplateAttachments.childNodes[i];
5883                 for(j=0; j<cNode.childNodes.length; j++) {
5884                     var node = cNode.childNodes[j];
5885                     var nName = new String(node.name);
5886                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5887                         if(form.templateAttachments.value != "") {
5888                             form.templateAttachments.value += "::";
5889                         }
5890                         form.templateAttachments.value += node.value;
5891                     }
5892                 }
5893             }
5894         }
5895
5896         // remove attachments
5897         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5898
5899         YAHOO.util.Connect.setForm(form);
5900
5901         AjaxObject.target = 'frameFlex';
5902
5903         // sending a draft email
5904         if(!isDraft && in_draft) {
5905             // remove row
5906             SE.listView.removeRowByUid(email_id);
5907         }
5908
5909         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5910         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5911
5912         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5913     },
5914
5915     /**
5916      * Handles clicking the email address link from a given view
5917      */
5918     composePackage : function() {
5919         if(composePackage != null) {
5920             SE.composeLayout.c0_composeNewEmail();
5921             
5922             
5923             if(composePackage.to_email_addrs) {
5924                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5925             } // if
5926             if (composePackage.subject != null && composePackage.subject.length > 0) {
5927                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5928             }
5929             
5930             //If no parent fields are set in the composePackage, ensure they are cleared.
5931             var parentFields = ['parent_type','parent_name','parent_id'];
5932             for(var i=0;i<parentFields.length;i++)
5933             {
5934                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5935                     composePackage[parentFields[i]] = "";
5936             }
5937                  
5938             document.getElementById("parent_type").value = composePackage.parent_type;
5939             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5940             document.getElementById("parent_id").value = composePackage.parent_id;
5941             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5942             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;  
5943                 
5944             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5945                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5946             } // if
5947             if (composePackage.body != null && composePackage.body.length > 0) {
5948                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5949                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5950                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5951             } // if
5952             if (composePackage.attachments != null) {
5953                                 SE.composeLayout.loadAttachments(composePackage.attachments);                   
5954             } // if
5955             
5956             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5957                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5958                         SE.util.emptySelectOptions(addressFrom);
5959                         var fromAccountOpts = composePackage.fromAccounts.data;
5960                         for(i=0; i<fromAccountOpts.length; i++) {
5961                               var key = fromAccountOpts[i].value;
5962                               var display = fromAccountOpts[i].text;
5963                               var opt = new Option(display, key);
5964                               if (fromAccountOpts[i].selected) {
5965                                 opt.selected = true;
5966                               }
5967                               addressFrom.options.add(opt);
5968                         }                       
5969                 
5970             } // if
5971         } // if
5972     },
5973
5974     setContentOnThisTiny : function() {
5975         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5976         var tinyHTML = tiny.getContent();
5977         composePackage.body = decodeURI(encodeURI(composePackage.body));
5978         // cn: bug 14361 - text-only templates don't fill compose screen
5979         if(composePackage.body == '') {
5980             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,'"');
5981         } // if
5982         //Flag determines if we should clear the tiny contents or just append
5983         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5984             SE.composeLayout.tinyHTML = '';
5985         else
5986             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;                 
5987         
5988          tiny.setContent(SE.composeLayout.tinyHTML);
5989          //Indicate that the contents has been loaded successfully.
5990          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5991     },
5992     /**
5993      * Confirms closure of a compose screen if "x" is clicked
5994      */
5995     confirmClose : function(panel) {
5996         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5997             SE.composeLayout.closeCompose(panel.id);
5998             return true;
5999         } else {
6000             return false;
6001         }
6002     },
6003
6004     /**
6005      * forces close of a compose screen
6006      */
6007     forceCloseCompose : function(id) {
6008         SE.composeLayout.closeCompose(id);
6009         
6010         // handle flow back to originating view
6011         if(composePackage) {
6012             // check if it's a module we need to return to
6013             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6014                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6015                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6016                     window.location = url;
6017                 }
6018             }
6019         }
6020     },
6021
6022     /**
6023      * closes the editor that just sent email
6024      * @param string id ID of composeLayout tab
6025      */
6026     closeCompose : function(id) {
6027         // destroy tinyMCE instance
6028         var idx = id.substr(13, id.length);
6029         var instanceId = "htmleditor" + idx;
6030         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6031
6032         // nullify DOM and namespace values.
6033         inCompose = false;
6034         SE.composeLayout[idx] = null;
6035         SE.tinyInstances[instanceId] = null;
6036         var tabsArray = SE.innerLayout.get("tabs");
6037         for (i = 0 ; i < tabsArray.length ; i++) {
6038                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6039                         tabsArray[i].close();
6040                         break;
6041                 }
6042         }
6043         //SE.innerLayout.getTab(idx).close();
6044     },
6045
6046     /**
6047     *  Enable the quick search for the compose relate field or search tab
6048     */
6049     enableQuickSearchRelate: function(idx,overides){
6050         
6051         if(typeof overides != 'undefined')
6052         {
6053             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6054             var newModule = document.getElementById(newModuleID).value; 
6055             var formName = overides['formName'];
6056             var fieldName = overides['fieldName'];
6057             var fieldId = overides['fieldId'];
6058             var fullName = formName + "_" + fieldName;
6059             var postBlurFunction = null;
6060         }
6061         else
6062         {
6063             var newModule = document.getElementById('data_parent_type'+idx).value;
6064             var formName = 'emailCompose'+idx;
6065             var fieldName = 'data_parent_name'+idx;
6066             var fieldId = 'data_parent_id'+idx;
6067             var fullName = formName + "_" + fieldName;
6068             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6069         }
6070         
6071         if(typeof sqs_objects == 'undefined')
6072             window['sqs_objects'] = new Array;
6073             
6074         window['sqs_objects'][fullName] = {
6075             form:formName,
6076                         method:"query",
6077                         modules:[newModule],
6078                         group:"or",
6079             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6080             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6081                         post_onblur_function: postBlurFunction,
6082             order:"name","limit":"30","no_match_text":"No Match"};
6083                                 
6084         
6085         if(typeof QSProcessedFieldsArray != 'undefined')
6086                 QSProcessedFieldsArray[fullName] = false;
6087         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6088                 QSFieldsArray[fullName].destroy();
6089                 delete QSFieldsArray[fullName];
6090         }
6091         if (Dom.get(fullName + "_results")) {
6092                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6093         }
6094             
6095         enableQS(false);
6096     },
6097     
6098         qsAddAddress : function(o) {
6099         if (o.name != "" && o.email1 != "")
6100         {
6101                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6102                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6103         }
6104     },
6105     /**
6106      * Returns a new instance ID, 0-index
6107      */
6108     getNewInstanceId : function() {
6109         this.currentInstanceId = this.currentInstanceId + 1;
6110         return this.currentInstanceId;
6111     },
6112
6113     /**
6114      * 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.
6115      */
6116     loadAttachments : function(result) {
6117         var idx = SE.composeLayout.currentInstanceId;
6118
6119         if(typeof(result) == 'object') {
6120                 //jchi #20680. Clean the former template attachments;
6121                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6122                         if(basket.innerHTML != ''){
6123                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6124                                         if (btn != 'yes'){
6125                                                 basket.innerHTML = '';
6126                                         }
6127                                 });
6128                         }
6129             for(i in result) {
6130                 if(typeof result[i] == 'object') {
6131                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6132                     var bean = result[i];
6133                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6134                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6135                 }
6136             }
6137         }
6138     },
6139
6140     /**
6141      * fills drop-down values for email templates and signatures
6142      */
6143     setComposeOptions : function(idx) {
6144         // send from accounts
6145         var addressFrom = document.getElementById('addressFrom' + idx);
6146         
6147         if (addressFrom.options.length <= 0) {
6148                 SE.util.emptySelectOptions(addressFrom);
6149                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6150                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6151                       var key = fromAccountOpts[id].value;
6152                       var display = fromAccountOpts[id].text;
6153                       var is_default = false;
6154                       if(key == SUGAR.default_inbound_accnt_id)
6155                         is_default = true;
6156                       var opt = new Option(display, key);
6157                       addressFrom.options.add(opt);
6158                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6159                 }
6160         }
6161
6162         // email templates
6163         var et = document.getElementById('email_template' + idx);
6164         SE.util.emptySelectOptions(et);
6165
6166         for(var key in this.emailTemplates) { // iterate through assoc array
6167             var display = this.emailTemplates[key];
6168             var opt = new Option(display, key);
6169             et.options.add(opt);
6170         }
6171
6172         // signatures
6173         var sigs = document.getElementById('signatures' + idx);
6174         SE.util.emptySelectOptions(sigs);
6175
6176         for(var key in this.signatures) { // iterate through assoc array
6177             var display = this.signatures[key];
6178             var opt = new Option(display, key);
6179
6180             if(key == SE.userPrefs.signatures.signature_default) {
6181                 opt.selected = true;
6182             }
6183
6184             sigs.options.add(opt);
6185         }
6186
6187         // html/plain email?
6188         var htmlEmail = document.getElementById('setEditor' + idx);
6189         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6190             htmlEmail.checked = true;
6191         } else {
6192                 htmlEmail.checked = false;
6193         }
6194
6195         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6196     },
6197
6198     /**
6199      * After compose screen is rendered, async call to get email body from Sugar
6200      */
6201     replyForwardEmailStage2 : function() {
6202         SE.util.clearHiddenFieldValues('emailUIForm');
6203         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6204
6205         var ieId = SE.composeLayout.replyForwardObj.ieId;
6206         var uid = SE.composeLayout.replyForwardObj.uid;
6207         var mbox = SE.composeLayout.replyForwardObj.mbox;
6208         var type = SE.composeLayout.replyForwardObj.type;
6209         var idx = SE.composeLayout.currentInstanceId;
6210
6211         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6212
6213         document.getElementById('emailSubject' + idx).value = type;
6214         document.getElementById('emailUIAction').value = 'composeEmail';
6215         document.getElementById('composeType').value = type;
6216         document.getElementById('ieId').value = ieId;
6217         document.getElementById('uid').value = uid;
6218         document.getElementById('mbox').value = mbox;
6219                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6220         var formObject = document.getElementById('emailUIForm');
6221         YAHOO.util.Connect.setForm(formObject);
6222
6223         var sendType = type;
6224         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6225     },
6226     
6227     /**
6228     *  Show the hidden cc or bcc fields
6229     */
6230     showHiddenAddress: function(addrType,idx){
6231
6232         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6233         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6234                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6235                 this[addrType+'Hidden'+idx] = false;
6236                 
6237                 //After bcc or cc is added, move options below last addr field
6238                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6239                 
6240                 //If both cc and bcc hidden, remove the empty row containing text.
6241                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6242                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6243                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");  
6244                 
6245                 SE.composeLayout.resizeEditor(idx);
6246     },
6247     /**
6248     *  Hide the cc and bcc fields if they were shown.
6249     */
6250     hideHiddenAddresses: function(idx){
6251         
6252         var addrTypes = ['cc','bcc'];
6253         for(var i = 0;i<addrTypes.length;i++)
6254         {
6255             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6256             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6257             this[addrTypes[i] + 'Hidden'+idx] = true
6258         }
6259         
6260         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6261         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6262         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6263     }
6264 };
6265
6266 ////    END SE.composeLayout
6267 ///////////////////////////////////////////////////////////////////////////////
6268 ///////////////////////////////////////////////////////////////////////////////
6269 ////    SE.util
6270 SE.util = {
6271     /**
6272      * Cleans serialized UID lists of duplicates
6273      * @param string
6274      * @return string
6275      */
6276     cleanUids : function(str) {
6277         var seen = new Object();
6278         var clean = "";
6279         var arr = new String(str).split(",");
6280
6281         for(var i=0; i<arr.length; i++) {
6282             if(seen[arr[i]]) {
6283                 continue;
6284             }
6285
6286             clean += (clean != "") ? "," : "";
6287             clean += arr[i];
6288             seen[arr[i]] = true;
6289         }
6290
6291         return clean;
6292     },
6293
6294     /**
6295      * Clears hidden field values
6296      * @param string id ID of form element to clear
6297      */
6298     clearHiddenFieldValues : function(id) {
6299         var form = document.getElementById(id);
6300
6301         for(i=0; i<form.elements.length; i++) {
6302             if(form.elements[i].type == 'hidden') {
6303                 var e = form.elements[i];
6304                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6305                     e.value = '';
6306                 }
6307             }
6308         }
6309     },
6310
6311     /**
6312      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6313      */
6314     emptySelectOptions : function(el) {
6315         if(el) {
6316             for(i=el.childNodes.length - 1; i >= 0; i--) {
6317                 if(el.childNodes[i]) {
6318                     el.removeChild(el.childNodes[i]);
6319                 }
6320             }
6321         }
6322     },
6323
6324     /**
6325      * Returns the MBOX path in the manner php_imap expects:
6326      * ie: INBOX.DEBUG.test
6327      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6328      */
6329     generateMboxPath : function(str) {
6330         var ex = str.split("::");
6331
6332         /* we have a serialized MBOX path */
6333         if(ex.length > 1) {
6334             var start = false;
6335             var ret = '';
6336             for(var i=0; i<ex.length; i++) {
6337                 if(ex[i] == 'INBOX') {
6338                     start = true;
6339                 }
6340
6341                 if(start == true) {
6342                     if(ret != "") {
6343                         ret += ".";
6344                     }
6345                     ret += ex[i];
6346                 }
6347             }
6348         } else {
6349             /* we have a Sugar folder GUID - do nothing */
6350             return str;
6351         }
6352
6353         return ret;
6354     },
6355
6356     /**
6357      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6358      * @param HTMLElement el
6359      * @return string GUID of found element or empty on failure
6360      */
6361     getGuidFromElement : function(el) {
6362         var GUID = '';
6363         var iterations = 4;
6364         var passedEl = el;
6365
6366         // upwards
6367         for(var i=0; i<iterations; i++) {
6368             if(el) {
6369                 if(el.id.match(SE.reGUID)) {
6370                     return el.id;
6371                 } else {
6372                     el = el.parentNode;
6373                 }
6374             }
6375         }
6376
6377         return GUID;
6378     },
6379
6380     /**
6381      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6382      * @return string
6383      */
6384     getPanelId : function() {
6385         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6386     },
6387     
6388     /**
6389      * wrapper to handle weirdness with IE
6390      * @param string instanceId
6391      * @return tinyMCE Controller object
6392      */
6393     getTiny : function(instanceId) {
6394         if(instanceId == '') {
6395             return null;
6396         }
6397
6398         var t = tinyMCE.getInstanceById(instanceId);
6399
6400         if(this.isIe()) {
6401             this.sleep(200);
6402             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6403         }
6404         return t;
6405     },
6406
6407     /**
6408      * Simple check for MSIE browser
6409      * @return bool
6410      */
6411     isIe : function() {
6412         var nav = new String(navigator.appVersion);
6413         if(nav.match(/MSIE/)) {
6414             return true;
6415         }
6416         return false;
6417     },
6418
6419     /**
6420      * Recursively removes an element from the DOM
6421      * @param HTMLElement
6422      */
6423     removeElementRecursive : function(el) {
6424         this.emptySelectOptions(el);
6425     },
6426     
6427     /**
6428      * Fakes a sleep
6429      * @param int
6430      */
6431     sleep : function(secs) {
6432         setTimeout("void(0);", secs);
6433     },
6434     
6435     /**
6436      * Converts a <select> element to an Ext.form.combobox
6437      */
6438      convertSelect : function(select) {
6439        alert('in convertSelect');
6440        if (typeof(select) == "string") {
6441            select = document.getElementById(select);
6442        }
6443      },
6444      
6445      findChildNode : function (parent, property, value) {
6446          for (i in parent.children) {
6447                  var child = parent.children[i];
6448                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6449                          return child;
6450                  var searchChild = SE.util.findChildNode(child, property, value);
6451                  if (searchChild) 
6452                          return searchChild;
6453          }
6454          return false;
6455      },
6456      
6457      cascadeNodes : function (parent, fn, scope, args) {
6458          for (i in parent.children) {
6459                  var child = parent.children[i];
6460                  var s = scope ? scope : child;
6461                  var a = args ? args : child;
6462                  fn.call(s, a);
6463                  SE.util.cascadeNodes(child, fn, scope, args);
6464          }
6465      }
6466 };
6467
6468
6469 ////    END UTIL
6470 ///////////////////////////////////////////////////////////////////////////////
6471
6472
6473 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6474                                 
6475 /*********************************************************************************
6476  * SugarCRM is a customer relationship management program developed by
6477  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6478  * 
6479  * This program is free software; you can redistribute it and/or modify it under
6480  * the terms of the GNU Affero General Public License version 3 as published by the
6481  * Free Software Foundation with the addition of the following permission added
6482  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6483  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6484  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6485  * 
6486  * This program is distributed in the hope that it will be useful, but WITHOUT
6487  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6488  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6489  * details.
6490  * 
6491  * You should have received a copy of the GNU Affero General Public License along with
6492  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6493  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6494  * 02110-1301 USA.
6495  * 
6496  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6497  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6498  * 
6499  * The interactive user interfaces in modified source and object code versions
6500  * of this program must display Appropriate Legal Notices, as required under
6501  * Section 5 of the GNU Affero General Public License version 3.
6502  * 
6503  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6504  * these Appropriate Legal Notices must retain the display of the "Powered by
6505  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6506  * technical reasons, the Appropriate Legal Notices must display the words
6507  * "Powered by SugarCRM".
6508  ********************************************************************************/
6509
6510
6511 if (typeof console == "undefined")
6512         console = { log: function(o) {alert(o)} };
6513
6514 var AjaxObject = {
6515         ret : '',
6516         currentRequestObject : null,
6517         //timeout : 30000, // 30 second timeout default
6518         timeout : 9999999999, // 30 second timeout default
6519         forceAbort : false,
6520         trail : new Array(),
6521
6522         /**
6523          */
6524         _reset : function() {
6525                 this.timeout = 30000;
6526                 this.forceAbort = false;
6527         },
6528
6529         folderRenameCleanup : function() {
6530                 SUGAR.email2.folders.setSugarFolders();
6531         },
6532
6533         fullSyncCleanup : function(o) {
6534                 this.folders.checkMailCleanup(o);
6535                 SUGAR.email2.settings.settingsDialog.hide();
6536         },
6537
6538         /**
6539          */
6540         composeCache : function(o) {
6541                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6542                 // get email templates and user signatures
6543                 var ret = JSON.parse(o.responseText);
6544
6545                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6546                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6547                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6548
6549                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6550
6551                 //Set the error array so we can notify the user when they try to hit send if any errors
6552                 //are present.  We will also notify them now (after hitting compose button).
6553                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6554
6555
6556                 //if error element is returning an array, then check the length to make sure we have error messages
6557                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6558                         //add error messages for display
6559                         for(i in ret.errorArray)
6560                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6561                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6562                         //if error element is returning an object, and the object value is not empty or null, then display error message
6563                         for(i in ret.errorArray)
6564                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6565                 }
6566
6567                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6568                 if(SUGAR.isIE) {
6569                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6570                         if(overlayPanel) {
6571                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6572                         }
6573                 }
6574         },
6575
6576
6577         handleDeleteSignature : function(o) {
6578                 hideOverlay();
6579                 var ret = JSON.parse(o.responseText);
6580                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6581         var field = document.getElementById('signature_id');
6582                 SUGAR.email2.util.emptySelectOptions(field);
6583
6584                 for(var i in ret.signatures) { // iterate through assoc array
6585                         var opt = new Option(ret.signatures[i], i);
6586                         field.options.add(opt);
6587                 }
6588                 setSigEditButtonVisibility();
6589         },
6590
6591         /**
6592          */
6593         handleDeleteReturn : function(o) {
6594                 // force refresh ListView
6595                 hideOverlay();
6596                 if(document.getElementById('focusEmailMbox')) {
6597                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6598                 }
6599
6600                 // need to display success message before calling next async call?
6601                 document.getElementById(this.target).innerHTML = o.responseText;
6602         },
6603
6604         /**
6605          */
6606     handleFailure : function(o) {
6607                 // Failure handler
6608                 overlay('Exception occurred...', o.statusText, 'alert');
6609                 if(document.getElementById('saveButton')) {
6610                         document.getElementById('saveButton').disabled = false;
6611                 }
6612         },
6613
6614         handleReplyForward : function(o) {
6615                 var a = JSON.parse(o.responseText);
6616                 globalA = a;
6617                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6618
6619                 document.getElementById('email_id' + idx).value = a.uid;
6620                 document.getElementById('emailSubject' + idx).value = a.name;
6621                 document.getElementById('addressTO' + idx).value = a.from;
6622                 document.getElementById('uid' + idx).value = a.uid;
6623                 if(a.cc) {
6624                         document.getElementById('addressCC' + idx).value = a.cc;
6625                         SE.composeLayout.showHiddenAddress('cc', idx);
6626                 }
6627
6628                 if(a.type) {
6629                         document.getElementById('type' + idx).value = a.type;
6630                 }
6631
6632                 // apply attachment values
6633                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6634
6635                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6636         },
6637
6638         handleReplyForwardForDraft : function(o) {
6639                 var a = JSON.parse(o.responseText);
6640                 globalA = a;
6641                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6642
6643                 document.getElementById('email_id' + idx).value = a.uid;
6644                 document.getElementById('emailSubject' + idx).value = a.name;
6645                 document.getElementById('addressTO' + idx).value = a.to;
6646
6647                 if(a.cc) {
6648                         document.getElementById('addressCC' + idx).value = a.cc;
6649                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6650                 }
6651
6652                 if(a.bcc) {
6653                         document.getElementById('addressBCC' + idx).value = a.bcc;
6654                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6655                 }
6656
6657
6658                 if(a.type) {
6659                         document.getElementById('type' + idx).value = a.type;
6660                 }
6661
6662
6663                 // apply attachment values
6664                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6665
6666                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6667         },
6668
6669         /**
6670          */
6671         handleSuccess : function(o) {
6672                 document.getElementById(this.target).innerHTML = o.responseText;
6673                 hideOverlay();
6674         },
6675
6676         /**
6677          */
6678         ieDeleteSuccess : function(o) {
6679                 hideOverlay();
6680
6681                 var ret = JSON.parse(o.responseText);
6682
6683                 SUGAR.email2.accounts.refreshInboundAccountTable();
6684                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6685                 SUGAR.email2.accounts.rebuildFolderList();
6686
6687         },
6688
6689         /**
6690          */
6691         ieSaveSuccess : function(o) {
6692                 document.getElementById('saveButton').disabled = false;
6693                 var a = JSON.parse(o.responseText);
6694                 if (a) {
6695                         if(a.error) {
6696                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6697                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6698                         } else {
6699                                 resp = JSON.parse(o.responseText);
6700                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6701                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6702                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6703                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6704                         }
6705                 } else {
6706                      hideOverlay();
6707                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6708                 }
6709
6710         },
6711
6712         /**
6713          */
6714         loadAttachments : function(o) {
6715                 var result = JSON.parse(o.responseText);
6716
6717                 SUGAR.email2.composeLayout.loadAttachments(result);
6718         },
6719
6720         /**
6721          */
6722         loadSignature : function(o) {
6723                 var ret = JSON.parse(o.responseText);
6724                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6725                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6726         },
6727
6728         /**
6729          * Follow up to mark email read|unread|flagged
6730          */
6731         markEmailCleanup : function(o) {
6732                 var ret = JSON.parse(o.responseText);
6733                 if (!ret['status']) {
6734                 hideOverlay();
6735                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6736                 } else {
6737                         SUGAR.email2.contextMenus.markEmailCleanup();
6738                 } // else
6739         },
6740
6741         /**
6742          */
6743         rebuildShowFolders : function(o) {
6744                 var t = JSON.parse(o.responseText);
6745                 var show = document.getElementById('ieAccountListShow');
6746
6747                 SUGAR.email2.util.emptySelectOptions(show);
6748
6749                 for(i=0; i<t.length; i++) { // iterate through assoc array
6750                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6751                         opt.selected = t[i].selected;
6752                         show.options.add(opt);
6753                 }
6754
6755                 SUGAR.email2.accounts.renderTree();
6756         },
6757         /**
6758          */
6759         saveListViewSortOrderPart2 : function() {
6760                 // create the JSON string the func expects
6761                 focusFolderPath = '[ "Home", "' + ieName + '"';
6762
6763                 var f = new String(focusFolder);
6764                 var fEx = f.split('.');
6765
6766                 for(i=0; i<fEx.length; i++) {
6767                         focusFolderPath += ', "' + fEx[i] +'"'
6768                 }
6769
6770                 focusFolderPath += ']';
6771
6772                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6773                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6774         },
6775
6776         /**
6777          *
6778          */
6779         sendEmailCleanUp : function(o) {
6780                 hideOverlay();
6781                 var ret = JSON.parse(o.responseText);
6782                 if (ret) {
6783                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6784                   //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6785                 } else if (o.responseText) {
6786                   overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6787                 }
6788
6789                 if (typeof(SE.grid) != 'undefined')
6790                         SE.listView.refreshGrid();
6791                 //Disabled while address book is disabled
6792
6793                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6794                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6795                 //close the shortcut bar menu
6796                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6797                         if(action_sugar_grp1 == 'DetailView') {
6798                                 showSubPanel('history',null,true);
6799                         } else if(action_sugar_grp1 == 'quickcreate') {
6800                                 closeEmailOverlay();
6801                         }
6802                 }
6803
6804         },
6805
6806         ieSendSuccess : function(o) {
6807                 hideOverlay();
6808                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6809         },
6810
6811         /**
6812          */
6813         settingsFolderRefresh : function(o) {
6814                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6815                 var ret = JSON.parse(o.responseText);
6816                 var user = document.getElementById('userFolders');
6817
6818                 SUGAR.email2.util.emptySelectOptions(user);
6819
6820                 for(i=0; i<ret.userFolders.length; i++) {
6821                         var display = ret.userFolders[i].name;
6822                         var value = ret.userFolders[i].id;
6823                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6824                         var opt = new Option(display, value, selected);
6825                         opt.selected = selected;
6826                         user.options.add(opt);
6827                 }
6828         },
6829
6830         /**
6831          */
6832         startRequest : function(callback, args, forceAbort) {
6833                 if(this.currentRequestObject != null) {
6834                         if(this.forceAbort == true) {
6835                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6836                         }
6837                 }
6838                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6839                 this._reset();
6840         },
6841
6842         requestInProgress : function() {
6843                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6844         },
6845
6846         /**
6847          */
6848         updateFolderSubscriptions : function() {
6849                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6850                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6851                 hideOverlay();
6852         },
6853
6854         /**
6855          */
6856         updateFrameFolder : function() {
6857                 SUGAR.email2.folders.checkEmailAccounts();
6858         },
6859
6860         /**
6861          */
6862         updateUserPrefs : function(o) {
6863                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6864                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6865         },
6866
6867         /**
6868          */
6869         uploadAttachmentSuccessful : function(o) {
6870                 // clear out field
6871                 document.getElementById('email_attachment').value = '';
6872
6873                 var ret = JSON.parse(o.responseText);
6874                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6875                 var overall = document.getElementById('addedFiles' + idx);
6876                 var index = overall.childNodes.length;
6877                 var out =
6878                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6879                                 // remove button
6880                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6881                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6882                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6883                                 // file icon
6884                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6885                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6886                                 // hidden id field
6887                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6888                                 // file name
6889                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6890                                 "<br/>" +
6891                         "</div>";
6892                 overall.innerHTML += out;
6893                 if(SUGAR.email2.util.isIe()) {
6894                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6895                 }
6896
6897                 // hide popup
6898                 SUGAR.email2.addFileDialog.hide();
6899                 // focus attachments
6900                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6901         }
6902 };
6903
6904
6905 ///////////////////////////////////////////////////////////////////////////
6906 ////    PER MODULE CALLBACK OBJECTS
6907 AjaxObject.accounts = {
6908         saveOutboundCleanup : function(o) {
6909                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6910                 SUGAR.email2.accounts.outboundDialog.hide();
6911                 var id = o.responseText;
6912                 SUGAR.email2.accounts.newAddedOutboundId = id;
6913                 },
6914         saveDefaultOutboundCleanup: function(o){
6915
6916         },
6917         callbackEditOutbound : {
6918                 success : function(o)
6919                 {
6920                         var ret = JSON.parse(o.responseText);
6921                         // show overlay
6922                         SUGAR.email2.accounts.showAddSmtp();
6923
6924                         // fill values
6925                         document.getElementById("mail_id").value = ret.id;
6926                         document.getElementById("type").value = ret.type;
6927                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6928                         document.getElementById("mail_name").value = ret.name;
6929                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6930                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6931                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6932                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6933                         //document.getElementById("mail_smtppass").value = ret.mail_smtppass;
6934                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6935                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6936                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6937
6938             if(ret.type == 'system-override') {
6939                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6940                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6941             }
6942             else {
6943                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6944                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6945             }
6946
6947
6948                 },
6949                 failure : AjaxObject.handleFailure,
6950                 timeout : AjaxObject.timeout,
6951                 scope   : AjaxObject
6952         },
6953         callbackDeleteOutbound : {
6954                 success : function(o) {
6955                     var ret = JSON.parse(o.responseText);
6956                     if(ret.is_error)
6957                     {
6958                         if(confirm(ret.error_message))
6959                 {
6960                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6961                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6962                 }
6963                 else
6964                     hideOverlay();
6965                     }
6966                     else
6967                     {
6968                              hideOverlay();
6969                              SUGAR.email2.accounts.refreshOuboundAccountTable();
6970                     }
6971                 },
6972
6973                 failure : AjaxObject.handleFailure,
6974                 timeout : AjaxObject.timeout,
6975                 scope   : AjaxObject
6976         },
6977
6978         callbackCheckMailProgress : {
6979            success : function(o) {
6980                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6981                    SUGAR.email2.accounts.totalMsgCount = -1;
6982                }
6983
6984                //Check for server timeout / errors
6985                var ret = JSON.parse(o.responseText);
6986                var done = false;
6987
6988                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6989                    hideOverlay();
6990                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6991                    SUGAR.email2.accounts.totalMsgCount = -1;
6992                //SUGAR.email2.folders.rebuildFolders();
6993                done = true;
6994                }
6995
6996                var currIeId = ret['ieid'];
6997
6998
6999                var serverCount = ret.count;
7000
7001                if (ret['status'] == 'done') {
7002                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7003                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7004                            //We are all done
7005                            done = true;
7006                            break;
7007                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7008                            //Go to next account
7009                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
7010                            ret.count = 0;
7011                            SUGAR.email2.accounts.totalMsgCount = -1;
7012                            break;
7013                        }
7014                    }
7015                }
7016                else if (ret.mbox && ret.totalcount && ret.count) {
7017                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7018                    if (ret.count >= ret.totalcount) {
7019                        serverCount = 0;
7020                    }
7021                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7022                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7023                } else {
7024                        hideOverlay();
7025                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7026                SUGAR.email2.accounts.totalMsgCount = -1;
7027                done = true;
7028                    }
7029
7030                if (done) {
7031                    SUGAR.email2.accounts.totalMsgCount = -1;
7032                    hideOverlay();
7033                    SUGAR.email2.folders.rebuildFolders();
7034                    SE.listView.refreshGrid();
7035                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7036                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7037                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7038                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7039            } else {
7040                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7041                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7042                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7043                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7044                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7045                }
7046            },
7047            failure : AjaxObject.handleFailure,
7048        timeout : AjaxObject.timeout,
7049        scope   : AjaxObject
7050         }
7051 };
7052
7053 ///////////////////////////////////////////////////////////////////////////////
7054 ////    COMPOSE LAYOUT
7055 AjaxObject.composeLayout = {
7056         /**
7057          * Populates the record id
7058          */
7059         saveDraftCleanup : function(o) {
7060                 hideOverlay();
7061                 var ret = JSON.parse(o.responseText);
7062                 if(ret)
7063                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7064                 else if (o.responseText)
7065                   overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7066         }
7067 };
7068
7069 AjaxObject.composeLayout.callback = {
7070         saveDraft : {
7071                 success : AjaxObject.composeLayout.saveDraftCleanup,
7072                 failure : AjaxObject.handleFailure,
7073                 timeout : AjaxObject.timeout,
7074                 scope   : AjaxObject
7075         }
7076 };
7077
7078 AjaxObject.detailView = {
7079         /**
7080          * Pops-up a printable view of an email
7081          */
7082         displayPrintable : function(o) {
7083                 var ret = JSON.parse(o.responseText);
7084                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7085                 // 2 below must be in global context
7086                 meta = ret.meta;
7087                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7088                 email = ret.meta.email;
7089                 if (typeof(email.cc) == 'undefined') {
7090                   email.cc = "";
7091                 }
7092
7093                 var out = displayTemplate.exec({
7094                         'app_strings'   : app_strings,
7095                         'theme'                 : theme,
7096                         'idx'                   : 'Preview',
7097                         'meta'                  : meta,
7098                         'email'                 : meta.email
7099                 });
7100
7101                 // open popup window
7102                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7103                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7104
7105                 popup.document.write(out);
7106                 popup.document.close();
7107         },
7108
7109         /**
7110          * Takes formatted response and creates a modal pop-over containing a title and content
7111          */
7112         displayView : function(o) {
7113                 var SED = SUGAR.email2.detailView;
7114                 var ret = JSON.parse(o.responseText);
7115
7116                 if(!SED.viewDialog) {
7117                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7118                                 modal:true,
7119                 visible:true,
7120                 fixedcenter:true,
7121                 constraintoviewport: true,
7122                                 shadow  : true
7123                         });
7124             SED.viewDialog.renderEvent.subscribe(function() {
7125                 var content = this.body.firstChild;
7126                 var viewH = YAHOO.util.Dom.getViewportHeight();
7127                 if (content) {
7128                         this.body.style.overflow = "auto";
7129                         this.body.style.width = "800px";
7130                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7131                 }
7132             }, SED.viewDialog);
7133                 } // end lazy load
7134                 SED.viewDialog.setHeader(ret.title);
7135                 SED.viewDialog.setBody(ret.html);
7136                 SED.viewDialog.render();
7137                 SED.viewDialog.show();
7138         },
7139
7140         /**
7141          * Generates a modal popup to populate with the contents of bean's full EditView
7142          */
7143         showQuickCreateForm : function(o) {
7144                 var SED = SUGAR.email2.detailView;
7145                 var ret = JSON.parse(o.responseText);
7146
7147                 if(!SED.quickCreateDialog) {
7148                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7149                                 modal:true,
7150                                 visible:true,
7151                 fixedcenter:true,
7152                 constraintoviewport: true,
7153                                 shadow  : true
7154                         });
7155
7156             SED.quickCreateDialog.renderEvent.subscribe(function() {
7157                 var viewH = YAHOO.util.Dom.getViewportHeight();
7158                 var contH = 0;
7159                 for (var i in this.body.childNodes) {
7160                         if (this.body.childNodes[i].clientHeight) {
7161                                 contH += this.body.childNodes[i].clientHeight;
7162                         } else if (this.body.childNodes[i].offsetHeight) {
7163                                 contH += this.body.childNodes[i].offsetHeight;
7164                         } // if
7165                 }
7166                         this.body.style.width = "800px";
7167                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7168                         this.body.style.overflow = "auto";
7169             }, SED.quickCreateDialog);
7170
7171             SED.quickCreateDialog.hideEvent.subscribe(function(){
7172                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7173                                 /*for(var qsField in qsFields){
7174                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7175                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7176                                 }*/
7177                         });
7178             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7179                 } // end lazy load
7180                 if (ret.html) {
7181                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7182                 }
7183                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7184                 SED.quickCreateDialog.render();
7185                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7186
7187                 SED.quickCreateDialog.ieId = ret.ieId;
7188                 SED.quickCreateDialog.uid = ret.uid;
7189         SED.quickCreateDialog.mbox = ret.mbox;
7190         SED.quickCreateDialog.qcmodule = ret.module;
7191
7192         SED.quickCreateDialog.show();
7193
7194                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7195                 if (editForm) {
7196                   editForm.module.value = 'Emails';
7197                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7198                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7199                   var instId = ret.module + count;
7200                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7201                   SED.quickCreateEmailCallback = function(instId, tableId) {
7202                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7203                           if (typeof(eaw) == "undefined")
7204                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7205                                                 + instId + "','" + tableId + "');", 100);
7206                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7207                   }
7208                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7209                                         + instId + "','" + tableId + "');", 100);
7210                 }
7211         },
7212
7213         saveQuickCreateForm : function(o) {
7214             hideOverlay();
7215                 SUGAR.email2.detailView.quickCreateDialog.hide();
7216                 validate['EditView'] = [ ];
7217         },
7218
7219         saveQuickCreateFormAndReply : function(o) {
7220             hideOverlay();
7221             var ret = JSON.parse(o.responseText);
7222         SUGAR.email2.detailView.quickCreateDialog.hide();
7223         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7224         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7225         if (ret) {
7226             var emailID = ret.id;
7227             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7228         } else {
7229             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7230         }
7231         //Cean the validate cache to prevent errors on the next call
7232         validate['EditView'] = [ ];
7233     },
7234
7235         saveQuickCreateFormAndAddToAddressBook : function(o) {
7236            hideOverlay();
7237                 SUGAR.email2.detailView.quickCreateDialog.hide();
7238                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7239                 validate['EditView'] = [ ];
7240         },
7241
7242         handleAssignmentDialogAssignAction : function() {
7243
7244
7245             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7246
7247             var dist = 'direct';
7248             var users = false;
7249             var rules = false;
7250             var get = "";
7251             var found_teams = false;
7252             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7253             if(!found_teams && assign_user_id == '' )
7254             {
7255                 alert(warning_message);
7256                 return;
7257             }
7258
7259             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7260             var uids = "";
7261             for(i=0; i<emailUids.length; i++) {
7262                 if(uids != '') {
7263                     uids += app_strings.LBL_EMAIL_DELIMITER;
7264                 }
7265                 uids += emailUids[i];
7266             }
7267
7268             var row = SUGAR.email2.grid.getSelectedRows()[0];
7269             var data = SUGAR.email2.grid.getRecord(row).getData();
7270             var ieid = data.ieId;
7271             var mbox = data.mbox;
7272             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7273             SUGAR.email2.contextMenus.assignToDialogue.hide();
7274             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7275
7276         },
7277
7278         handleAssignmentDialogDeleteAction : function() {
7279                 // TO pass list of UIDS/emailIds
7280                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7281                 var row = SUGAR.email2.grid.getSelections()[0];
7282                 var ieid = row.data.ieId;
7283             var mbox = row.data.mbox;
7284         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7285         SUGAR.email2.contextMenus.assignmentDialog.hide();
7286                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7287
7288                 // AJAX Call
7289
7290         },
7291
7292         showEmailDetailView : function(o) {
7293         hideOverlay();
7294         var SED = SUGAR.email2.detailView;
7295                 var ret = JSON.parse(o.responseText);
7296
7297                 if(!SED.quickCreateDialog) {
7298                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7299                                 modal:true,
7300                                 visible:true,
7301                 //fixedcenter:true,
7302                 constraintoviewport: true,
7303                 draggable: true,
7304                                 autofillheight: "body",
7305                                 shadow  : true
7306                         });
7307                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7308                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7309                 var contH = 0;
7310                 for (var i in this.body.childNodes) {
7311                         if (this.body.childNodes[i].offsetHeight)
7312                                 contH += this.body.childNodes[i].offsetHeight;
7313                 }
7314                         this.body.style.overflow = "auto";
7315                         this.body.style.width = "800px";
7316                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7317                         this.center();
7318             }, SED.quickCreateDialog);
7319                 }
7320                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7321                 SED.quickCreateDialog.setBody(ret.html);
7322                 SED.quickCreateDialog.render();
7323         SUGAR.util.evalScript(ret.html);
7324         SED.quickCreateDialog.show();
7325         },
7326
7327         showAssignmentDialogWithData : function(o) {
7328         var SEC = SUGAR.email2.contextMenus;
7329                 hideOverlay();
7330         var ret = JSON.parse(o.responseText);
7331         if (!SEC.assignmentDialog) {
7332                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7333                         visible:false,
7334                 fixedcenter:true,
7335                 constraintoviewport: true,
7336                         modal   : true
7337                 });
7338                 SEC.assignmentDialog.setBody("");
7339                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7340                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7341                 var iev = YAHOO.util.Dom.get("Distribute");
7342                 if (iev) {
7343                         this.body.style.width = "700px";
7344                 }
7345             },  SEC.assignmentDialog);
7346                 SEC.assignmentDialog.render();
7347         }
7348         SEC.assignmentDialog.setBody(ret);
7349         SEC.assignmentDialog.render();
7350         validate = [];
7351         SEC.assignmentDialog.show();
7352         SUGAR.util.evalScript(ret);
7353         },
7354
7355         showImportForm : function(o) {
7356                 var SED = SUGAR.email2.detailView;
7357                 var ret = JSON.parse(o.responseText);
7358
7359         document.getElementById('quickCreateContent').innerHTML = "";
7360         hideOverlay();
7361         if (!ret) {
7362             return false;
7363         }
7364
7365         if(!SED.importDialog) {
7366             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7367                 modal:true,
7368                 visible:false,
7369                 fixedcenter:true,
7370                 constraintoviewport: true,
7371                 buttons : [{
7372                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7373                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7374                 }]//,
7375                 //scroll : true
7376             });
7377             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7378             SED.importDialog.setBody("");
7379             SED.importDialog.hideEvent.subscribe(function(){
7380                 for(var i in QSFieldsArray) {
7381                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7382                                 QSFieldsArray[i].destroy();
7383                                 delete QSFieldsArray[i];
7384                         }
7385                         if (QSProcessedFieldsArray[i]) {
7386                                 QSProcessedFieldsArray[i] = false;
7387                         } // if
7388                                 }
7389             });
7390             SED.importDialog.renderEvent.subscribe(function() {
7391                 var iev = YAHOO.util.Dom.get("ImportEditView");
7392                 if (iev) {
7393                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7394                         this.body.style.width = "600px";
7395                 }
7396             }, SED.importDialog);
7397             SED.importDialog.render();
7398         } // end lazy load
7399         SED.importDialog.setBody(ret.html);
7400         SED.importDialog.ret = ret;
7401         SUGAR.util.evalScript(ret.html);
7402         SED.importDialog.render();
7403         validate = [];
7404         SED.importDialog.show();
7405         SED.importDialog.focusFirstButton();
7406     },
7407     getImportAction : function(ret) {
7408         if (!check_form('ImportEditView')) return false;
7409         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7410                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7411                 return false;
7412         } // if
7413                 var get = "";
7414         var editView = document.getElementById('ImportEditView');
7415         if (editView.assigned_user_id != null) {
7416             get = get + "&user_id=" + editView.assigned_user_id.value
7417             //var user_id = editView.assigned_user_id.value;
7418         }
7419         var parent_id = editView.parent_id.value;
7420         var parent_type = editView.parent_type.value;
7421         var row = SUGAR.email2.grid.getSelectedRows()[0];
7422         row = SUGAR.email2.grid.getRecord(row);
7423         var data = row.getData();
7424         var ieId = data.ieId;
7425         var mbox = data.mbox;
7426         var serverDelete = editView.serverDelete.checked;
7427         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7428         var uids = "";
7429         for(i=0; i<emailUids.length; i++) {
7430             if(uids != '') {
7431                 uids += app_strings.LBL_EMAIL_DELIMITER;
7432             }
7433             uids += emailUids[i];
7434         }
7435
7436         var action = 'importEmail&uid=';
7437         if (ret.move) {
7438             action = 'moveEmails';
7439             action = action + '&sourceFolder=' + ret['srcFolder'];
7440             action = action + '&sourceIeId=' + ret['srcIeId'];
7441             action = action + '&destinationFolder=' + ret['dstFolder'];
7442             action = action + '&destinationIeId=' + ret['dstIeId'];
7443             action = action + '&emailUids=';
7444         }
7445         if (action.search(/importEmail/) != -1) {
7446             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7447         } else {
7448             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7449         }
7450
7451         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7452         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7453         SUGAR.email2.detailView.importDialog.hide();
7454         document.getElementById('importDialogContent').innerHTML = "";
7455
7456     },
7457     showRelateForm : function(o) {
7458         var SED = SUGAR.email2.detailView;
7459         var ret = JSON.parse(o.responseText);
7460         document.getElementById('quickCreateContent').innerHTML = "";
7461         hideOverlay();
7462         if (!ret) {
7463             return false;
7464         }
7465         dialog_loaded = true;
7466
7467         if(!SED.relateDialog) {
7468             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7469                                 modal:true,
7470                                 visible:true,
7471                 fixedcenter:true,
7472                 width: '800px',
7473                 constraintoviewport: true,
7474                                 buttons : [{
7475                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7476                                         if (!check_form('RelateEditView')) return false;
7477                                         var get = "";
7478                         var editView = document.getElementById('RelateEditView');
7479                         var parent_id = editView.parent_id.value;
7480                         var parent_type = editView.parent_type.value;
7481                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7482                         row  = SUGAR.email2.grid.getRecord(row);
7483                         var ieId = row.getData().ieId;
7484                         var mbox = row.getData().mbox;
7485                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7486                         var uids = "";
7487                         for(i=0; i<emailUids.length; i++) {
7488                             if(uids != '') {
7489                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7490                             }
7491                             uids += emailUids[i];
7492                         }
7493                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7494                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7495                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7496                         SED.relateDialog.hide();
7497                         document.getElementById('relateDialogContent').innerHTML = "";
7498                         }
7499                 }]
7500                         });
7501
7502             SED.relateDialog.hideEvent.subscribe(function(){
7503                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7504                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7505                         delete QSFieldsArray['ImportEditView_parent_name'];
7506                 } // if
7507                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7508                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7509                                 } // if
7510             });
7511
7512             SED.relateDialog.renderEvent.subscribe(function() {
7513                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7514                 var contH = 0;
7515                 for (var i in this.body.childNodes) {
7516                         if (this.body.childNodes[i].clientHeight)
7517                                 contH += this.body.childNodes[i].clientHeight;
7518                 }
7519             }, SED.relateDialog);
7520             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7521                 } // end lazy load
7522
7523         SED.relateDialog.setBody(ret.html);
7524         SED.relateDialog.render();
7525         SUGAR.util.evalScript(ret.html);
7526         SED.relateDialog.show();
7527     }
7528 };
7529 /**
7530  * DetailView callbacks
7531  */
7532 AjaxObject.detailView.callback = {
7533         emailDetail : {
7534                 success : function(o) {
7535                         SUGAR.email2.o = o;
7536                         var ret = JSON.parse(o.responseText);
7537                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7538                 },
7539                 argument: [targetDiv],
7540                 failure : AjaxObject.handleFailure,
7541                 timeout : 0,
7542                 scope   : AjaxObject
7543         },
7544         emailPreview : {
7545                 success : function(o) {
7546                         SUGAR.email2.o = o;
7547                         var ret = JSON.parse(o.responseText);
7548                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7549                 },
7550                 failure : AjaxObject.handleFailure,
7551                 timeout : 0,
7552                 scope   : AjaxObject
7553         },
7554         viewPrint : {
7555                 success : AjaxObject.detailView.displayPrintable,
7556                 failure : AjaxObject.handleFailure,
7557                 timeout : AjaxObject.timeout,
7558                 scope   : AjaxObject
7559         },
7560         viewRaw : {
7561                 success : AjaxObject.detailView.displayView,
7562                 failure : AjaxObject.handleFailure,
7563                 timeout : AjaxObject.timeout,
7564                 scope   : AjaxObject
7565         }
7566 };
7567
7568
7569
7570
7571
7572 AjaxObject.folders = {
7573         /**
7574          * check-mail post actions
7575          */
7576         checkMailCleanup : function(o) {
7577                 hideOverlay();
7578                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7579
7580                 // refresh focus ListView
7581                 SE.listView.refreshGrid();
7582                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7583         },
7584
7585         /**
7586          */
7587         rebuildFolders : function(o) {
7588                 hideOverlay();
7589
7590                 var data = JSON.parse(o.responseText);
7591
7592                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7593                 SUGAR.email2.folders.setSugarFolders();
7594         }
7595 };
7596 AjaxObject.folders.callback = {
7597         checkMail : {
7598                 success : AjaxObject.folders.checkMailCleanup,
7599                 failure : AjaxObject.handleFailure,
7600                 timeout : 600000, // 5 mins
7601                 scope   : AjaxObject
7602         }
7603 }
7604
7605 AjaxObject.rules = {
7606         loadRulesForSettings : function(o) {
7607                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7608                 // assume we have the class we need
7609                 SUGAR.routing.getStrings();
7610                 SUGAR.routing.getDependentDropdowns();
7611         }
7612 };
7613 ////    END PER MODULE CALLBACK OBJECTS
7614 ///////////////////////////////////////////////////////////////////////////
7615
7616
7617 var callback = {
7618         success : AjaxObject.handleSuccess,
7619         failure : AjaxObject.handleFailure,
7620         timeout : AjaxObject.timeout,
7621         scope   : AjaxObject
7622 };
7623 var callbackAccount = {
7624         success : AjaxObject.ieSaveSuccess,
7625         failure : AjaxObject.handleFailure,
7626         timeout : AjaxObject.timeout,
7627         scope   : AjaxObject
7628 };
7629 var callbackAccountDelete = {
7630         success : AjaxObject.ieDeleteSuccess,
7631         failure : AjaxObject.handleFailure,
7632         timeout : AjaxObject.timeout,
7633         scope   : AjaxObject
7634 };
7635 var callbackOutboundTest = {
7636         success : AjaxObject.ieSendSuccess,
7637         failure : AjaxObject.handleFailure,
7638         timeout : AjaxObject.timeout,
7639         scope   : AjaxObject
7640 };
7641
7642
7643
7644 var callbackTeamInfoForSettings = {
7645 success : function (o) {
7646         var data = JSON.parse(o.responseText);
7647         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7648 },
7649 failure : AjaxObject.handleFailure,
7650 timeout : AjaxObject.timeout,
7651 scope   : AjaxObject
7652
7653 };
7654
7655 var callbackStatusForImport = {
7656 success : function (o) {
7657         hideOverlay();
7658         if (o.responseText != "")  {
7659                 var statusString = "";
7660                 var data = JSON.parse(o.responseText);
7661                 for(i=0; i<data.length; i++) {
7662                         statusString = statusString + data[i] + '<br/>';
7663                 }
7664                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7665         }
7666         SE.listView.refreshGrid();
7667
7668 },
7669 failure : AjaxObject.handleFailure,
7670 timeout : AjaxObject.timeout,
7671 scope   : AjaxObject
7672
7673 };
7674 var callbackComposeCache = {
7675         success : AjaxObject.composeCache,
7676         failure : AjaxObject.handleFailure,
7677         timeout : AjaxObject.timeout,
7678         scope   : AjaxObject
7679 };
7680 var callbackDelete = {
7681         success : AjaxObject.handleDeleteReturn,
7682         failure : AjaxObject.handleFailure,
7683         timeout : AjaxObject.timeout,
7684         scope   : AjaxObject
7685 };
7686 var callbackEmailDetailMultiple = {
7687         success : function(o) {
7688                 hideOverlay();
7689                 var retMulti = JSON.parse(o.responseText);
7690                 var ret = new Object();
7691
7692                 for(var i=0; i<retMulti.length; i++) {
7693                         ret = retMulti[i];
7694
7695                         SUGAR.email2._setDetailCache(ret);
7696                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7697                 }
7698         },
7699         failure : AjaxObject.handleFailure,
7700         timeout : 0,
7701         scope   : AjaxObject
7702 };
7703 var callbackListViewSortOrderChange = {
7704         success : AjaxObject.saveListViewSortOrderPart2,
7705         failure : AjaxObject.handleFailure,
7706         timeout : AjaxObject.timeout,
7707         scope   : AjaxObject,
7708         argument        : [ieId, ieName, focusFolder]
7709 };
7710 var callbackEmptyTrash = {
7711         success : function(o) {
7712                 hideOverlay();
7713                 AjaxObject.folderRenameCleanup;
7714         },
7715         failure : AjaxObject.handleFailure,
7716         timeout : AjaxObject.timeout,
7717         scope   : AjaxObject
7718 };
7719 var callbackClearCacheFiles = {
7720         success : function(o) {
7721                 hideOverlay();
7722         },
7723         failure : AjaxObject.handleFailure,
7724         timeout : AjaxObject.timeout,
7725         scope   : AjaxObject
7726 };
7727 var callbackFolderRename = {
7728         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7729         failure : AjaxObject.handleFailure,
7730         timeout : AjaxObject.timeout,
7731         scope   : AjaxObject
7732 };
7733 var callbackFolderDelete = {
7734         success : function(o) {
7735                 var ret = JSON.parse(o.responseText);
7736                 if (ret.status) {
7737                     if (ret.folder_id) {
7738                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7739                         if(node)
7740                                 SUGAR.email2.tree.removeNode(node, true);
7741                     } else if (ret.ieId && ret.mbox) {
7742                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7743                         if(node)
7744                                 SUGAR.email2.tree.removeNode(node, true);
7745                     }
7746                         hideOverlay();
7747                         //SUGAR.email2.folders.loadSettingFolder();
7748                 } else {
7749                         hideOverlay();
7750                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7751                 } // else
7752         },
7753         failure : AjaxObject.handleFailure,
7754         timeout : AjaxObject.timeout,
7755         scope   : AjaxObject
7756 };
7757 var callbackFolderSave = {
7758         success : function(o) {
7759                 var ret = JSON.parse(o.responseText);
7760
7761                 switch(ret.action) {
7762                         case 'newFolderSave':
7763                                 SUGAR.email2.folders.rebuildFolders();
7764                         break;
7765                 }
7766         },
7767         failure : AjaxObject.handleFailure,
7768         timeout : AjaxObject.timeout,
7769         scope   : AjaxObject
7770 };
7771 var callbackFolderSubscriptions = {
7772         success : AjaxObject.updateFolderSubscriptions,
7773         failure : AjaxObject.handleFailure,
7774         timeout : AjaxObject.timeout,
7775         scope   : AjaxObject
7776 };
7777 var callbackFolderUpdate = {
7778         success : AjaxObject.updateFrameFolder,
7779         failure : AjaxObject.handleFailure,
7780         timeout : AjaxObject.timeout,
7781         scope   : AjaxObject
7782 };
7783 var callbackFolders = {
7784         success : AjaxObject.folders.rebuildFolders,
7785         //success : void(true),
7786         failure : AjaxObject.handleFailure,
7787         timeout : AjaxObject.timeout,
7788         scope   : AjaxObject
7789 };
7790 var callbackFullSync = {
7791         success : AjaxObject.fullSyncCleanup,
7792         failure : AjaxObject.handleFailure,
7793         timeout : 9999999999999,
7794         scope   : AjaxObject
7795 };
7796 var callbackGeneric = {
7797         success : function() {
7798                 hideOverlay();
7799         },
7800         failure : AjaxObject.handleFailure,
7801         timeout : AjaxObject.timeout,
7802         scope   : AjaxObject
7803 };
7804 var callbackIeAccountRetrieve = {
7805         success : function(o) {
7806                 // return JSON encoding
7807                 hideOverlay();
7808                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7809                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7810         },
7811         failure : AjaxObject.handleFailure,
7812         timeout : AjaxObject.timeout,
7813         scope   : AjaxObject
7814 };
7815 var callbackImportOneEmail = {
7816         success :  AjaxObject.detailView.showImportForm,
7817         failure : AjaxObject.handleFailure,
7818         timeout : AjaxObject.timeout,
7819         scope   : AjaxObject
7820 };
7821 var callbackRelateEmail = {
7822     success : AjaxObject.detailView.showRelateForm,
7823     failure : AjaxObject.handleFailure,
7824     timeout : AjaxObject.timeout,
7825     scope   : AjaxObject
7826 }
7827 var callbackEmailDetailView = {
7828     success : AjaxObject.detailView.showEmailDetailView,
7829     failure : AjaxObject.handleFailure,
7830     timeout : AjaxObject.timeout,
7831     scope   : AjaxObject
7832 }
7833 var callbackAssignmentDialog = {
7834         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7835         failure : AjaxObject.handleFailure,
7836         timeout : AjaxObject.timeout,
7837         scope   : AjaxObject
7838 };
7839 var callbackAssignmentAction = {
7840         success :  function(o) {
7841                 SE.listView.refreshGrid();
7842                 hideOverlay();
7843                 if(o.responseText != '') {
7844                overlay('Assignment action result', o.responseText, 'alert');
7845             } // if
7846         } ,
7847         failure : AjaxObject.handleFailure,
7848         timeout : AjaxObject.timeout,
7849         scope   : AjaxObject
7850 };
7851 var callbackMoveEmails = {
7852         success :  function(o) {
7853             SE.listView.refreshGrid();
7854                 hideOverlay();
7855                 if(o.responseText != '') {
7856                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7857             } // if
7858         } ,
7859         failure : AjaxObject.handleFailure,
7860         timeout : AjaxObject.timeout,
7861         scope   : AjaxObject
7862 };
7863 var callbackLoadAttachments = {
7864         success : AjaxObject.loadAttachments,
7865         failure : AjaxObject.handleFailure,
7866         timeout : AjaxObject.timeout,
7867         scope   : AjaxObject
7868 };
7869 var callbackLoadRules = {
7870         success : AjaxObject.rules.loadRulesForSettings,
7871         failure : AjaxObject.handleFailure,
7872         timeout : AjaxObject.timeout,
7873         scope   : AjaxObject
7874 };
7875 var callbackLoadSignature = {
7876         success : AjaxObject.loadSignature,
7877         failure : AjaxObject.handleFailure,
7878         timeout : AjaxObject.timeout,
7879         scope   : AjaxObject
7880 };
7881 var callbackDeleteSignature = {
7882         success : AjaxObject.handleDeleteSignature,
7883         failure : AjaxObject.handleFailure,
7884         timeout : AjaxObject.timeout,
7885         scope   : AjaxObject
7886 };
7887 /*var callbackMoveEmails = {
7888     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7889     failure : AjaxObject.handleFailure,
7890     timeout : AjaxObject.timeout,
7891     scope   : AjaxObject
7892 }*/
7893 var callbackOutboundSave = {
7894         success : AjaxObject.accounts.saveOutboundCleanup,
7895         failure : AjaxObject.handleFailure,
7896         timeout : AjaxObject.timeout,
7897         scope   : AjaxObject
7898 };
7899 var callbackDefaultOutboundSave = {
7900         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7901         failure : AjaxObject.handleFailure,
7902         timeout : AjaxObject.timeout,
7903         scope   : AjaxObject
7904 };
7905 var callbackQuickCreate = {
7906         success : AjaxObject.detailView.showQuickCreateForm,
7907         failure : AjaxObject.handleFailure,
7908         timeout : AjaxObject.timeout,
7909         scope   : AjaxObject
7910 };
7911 var callbackQuickCreateSave = {
7912         success : AjaxObject.detailView.saveQuickCreateForm,
7913         failure : AjaxObject.handleFailure,
7914         timeout : AjaxObject.timeout,
7915         scope   : AjaxObject
7916 };
7917 var callbackQuickCreateSaveAndAddToAddressBook = {
7918         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7919         failure : AjaxObject.handleFailure,
7920         timeout : AjaxObject.timeout,
7921         scope   : AjaxObject
7922 };
7923 var callbackQuickCreateSaveAndReply = {
7924     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7925     failure : AjaxObject.handleFailure,
7926     timeout : AjaxObject.timeout,
7927     scope   : AjaxObject
7928 }
7929 var callbackQuickCreateSaveAndReplyCase = {
7930     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7931     failure : AjaxObject.handleFailure,
7932     timeout : AjaxObject.timeout,
7933     scope   : AjaxObject
7934 }
7935 var callbackRebuildShowAccountList = {
7936         success : AjaxObject.rebuildShowFolders,
7937         failure : AjaxObject.handleFailure,
7938         timeout : AjaxObject.timeout,
7939         scope   : AjaxObject
7940 };
7941
7942 var callbackRefreshSugarFolders = {
7943         success : function(o) {
7944                 var t = JSON.parse(o.responseText);
7945                 SUGAR.email2.folders.setSugarFoldersEnd(t);
7946         },
7947         failure : AjaxObject.handleFailure,
7948         timeout : AjaxObject.timeout,
7949         scope   : AjaxObject
7950 };
7951 var callbackReplyForward = {
7952         success : AjaxObject.handleReplyForward,
7953         finish : function(a, retryCount) {
7954                 if (typeof(retryCount) == 'undefined') {
7955                         retryCount = 0;
7956                 } else {
7957                         retryCount++;
7958                 }
7959                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7960                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7961         try {
7962                         var html = t.getContent();
7963
7964             if (a.type != 'draft') {
7965                         if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7966                                 html += "&nbsp;<div><hr></div>" + a.description;
7967                         } else {
7968                                 html =  "&nbsp;<div><hr></div>" + a.description + html;
7969                         }
7970             }else {
7971                 html = a.description;
7972             }
7973
7974                         t.setContent(html);//
7975
7976                 } catch(e) {
7977                         if (retryCount < 5) {
7978                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7979                                 return;
7980                         }
7981                 }
7982                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7983                 if (tabArray != null && tabArray.length > 0) {
7984                         for (i = 0 ; i < tabArray.length ; i++) {
7985                                 var tabObject = tabArray[i];
7986                                 if (tabObject.get("id") == ("composeTab" + idx)) {
7987                                         var tabLabel = a.name;
7988                                 if (tabLabel != null && tabLabel.length > 25) {
7989                                         tabLabel = tabLabel.substring(0, 25) + "...";
7990                                 } // if
7991                                         tabObject.get("labelEl").firstChild.data = tabLabel;
7992                                         break;
7993                                 }
7994                         }
7995                 }
7996
7997                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7998                 if (a.parent_name != null && a.parent_name != "") {
7999                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
8000                 }
8001                 if (a.parent_type != null && a.parent_type != "") {
8002                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
8003                 }
8004                 if (a.parent_id != null && a.parent_id != "") {
8005                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
8006                 }
8007                 if (a.fromAccounts.status) {
8008                         var addressFrom = document.getElementById('addressFrom' + idx);
8009                 SUGAR.email2.util.emptySelectOptions(addressFrom);
8010                 var fromAccountOpts = a.fromAccounts.data;
8011                 for(i=0; i<fromAccountOpts.length; i++) {
8012                       var key = fromAccountOpts[i].value;
8013                       var display = fromAccountOpts[i].text;
8014                       var opt = new Option(display, key);
8015                       if (fromAccountOpts[i].selected) {
8016                         opt.selected = true;
8017                       }
8018                       addressFrom.options.add(opt);
8019                 }
8020                 } // if
8021                 hideOverlay();
8022
8023         },
8024         failure : AjaxObject.handleFailure,
8025         timeout : AjaxObject.timeout,
8026         scope   : AjaxObject,
8027         argument        : [sendType]
8028 };
8029 var callbackSendEmail = {
8030         success : AjaxObject.sendEmailCleanUp,
8031         failure : AjaxObject.handleFailure,
8032         timeout : AjaxObject.timeout,
8033         scope   : AjaxObject
8034 };
8035 var callbackSettings = {
8036         success : AjaxObject.updateUserPrefs,
8037         failure : AjaxObject.handleFailure,
8038         timeout : AjaxObject.timeout,
8039         scope   : AjaxObject
8040 };
8041 var callbackSettingsFolderRefresh = {
8042         success : AjaxObject.settingsFolderRefresh,
8043         failure : AjaxObject.handleFailure,
8044         timeout : AjaxObject.timeout,
8045         scope   : AjaxObject
8046 };
8047 var callbackLoadSettingFolder = {
8048         success : function(o) {
8049                 AjaxObject.settingsFolderRefresh(o);
8050                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8051         },
8052         failure : AjaxObject.handleFailure,
8053         timeout : AjaxObject.timeout,
8054         scope   : AjaxObject
8055
8056 };
8057 var callbackUploadAttachment = {
8058         success : AjaxObject.uploadAttachmentSuccessful,
8059         upload  : AjaxObject.uploadAttachmentSuccessful,
8060         failure : AjaxObject.handleFailure,
8061         timeout : AjaxObject.timeout,
8062         scope   : AjaxObject
8063 };
8064 var callbackUserPrefs = {
8065         success : function(o) {
8066                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8067         },
8068         failure : AjaxObject.handleFailure,
8069         timeout : AjaxObject.timeout,
8070         scope   : AjaxObject
8071 };
8072
8073 var callbackContextmenus = {
8074         markUnread : {
8075                 success : AjaxObject.markEmailCleanup,
8076                 failure : AjaxObject.handleFailure,
8077                 timeout : AjaxObject.timeout,
8078                 scope   : AjaxObject
8079         }
8080 };
8081
8082 var callbackCheckEmail2 = {
8083         success : function(o) {
8084                 var ret = JSON.parse(o.responseText);
8085                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8086
8087
8088         },
8089         failure : AjaxObject.handleFailure,
8090         timeout : AjaxObject.timeout,
8091         scope   : AjaxObject
8092 }// End of File modules/Emails/javascript/ajax.js
8093                                 
8094 /*********************************************************************************
8095  * SugarCRM is a customer relationship management program developed by
8096  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8097  * 
8098  * This program is free software; you can redistribute it and/or modify it under
8099  * the terms of the GNU Affero General Public License version 3 as published by the
8100  * Free Software Foundation with the addition of the following permission added
8101  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8102  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8103  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8104  * 
8105  * This program is distributed in the hope that it will be useful, but WITHOUT
8106  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8107  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8108  * details.
8109  * 
8110  * You should have received a copy of the GNU Affero General Public License along with
8111  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8112  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8113  * 02110-1301 USA.
8114  * 
8115  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8116  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8117  * 
8118  * The interactive user interfaces in modified source and object code versions
8119  * of this program must display Appropriate Legal Notices, as required under
8120  * Section 5 of the GNU Affero General Public License version 3.
8121  * 
8122  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8123  * these Appropriate Legal Notices must retain the display of the "Powered by
8124  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8125  * technical reasons, the Appropriate Legal Notices must display the words
8126  * "Powered by SugarCRM".
8127  ********************************************************************************/
8128
8129 function gridInit() {
8130         if(SUGAR.email2.grid) {
8131                 SUGAR.email2.grid.destroy();
8132         }
8133         
8134         e2Grid = {
8135                 init : function() {
8136                 
8137                         var Ck = YAHOO.util.Cookie;
8138                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8139
8140                         if (Ck.get("EmailGridWidths")) {
8141                                 for (var i=0; i < widths.length; i++) {
8142                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8143                                 }
8144                         } else {
8145                                 for (var i=0; i < widths.length; i++) {
8146                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8147                                 }
8148                         }
8149                         
8150                         // changes "F" to an icon
8151                         function flaggedIcon(cell, record, column, value) {
8152                                 if(value != "") {
8153                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8154                                 }
8155                         }
8156                         // changes "A" to replied icon
8157                         function repliedIcon(cell, record, column, value) {
8158                                 if(value != "") {
8159                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8160                                 }
8161                         }
8162                 function attachIcon(cell, record, column, value) {
8163                                 if(value == "1") {
8164                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8165                                 }
8166                         }
8167
8168                         var colModel = 
8169                                 [
8170                                         {
8171                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8172                                                 width: 10, 
8173                                                 sortable: false, 
8174                                                 fixed: true,
8175                                                 resizeable: true,
8176                                                 formatter: attachIcon,
8177                                                 key: 'hasAttach'
8178                                         }, 
8179                                     {
8180                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8181                                                 width: widths[0], 
8182                                                 sortable: true, 
8183                                                 fixed: true,
8184                                                 resizeable: true,
8185                                                 formatter: flaggedIcon,
8186                                                 key: 'flagged'
8187                                         }, 
8188                                         {
8189                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8190                                                 width: widths[1], 
8191                                                 sortable: true, 
8192                                                 fixed: true,
8193                                                 resizeable: true,
8194                                                 formatter: repliedIcon,
8195                                                 key: 'status'
8196                                         },
8197                                         {
8198                                                 label: app_strings.LBL_EMAIL_FROM, 
8199                                                 width: widths[2],
8200                                                 sortable: true,
8201                                                 resizeable: true,
8202                                                 key: 'from'
8203                                         }, 
8204                                         {
8205                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8206                                                 width: widths[3], 
8207                                                 sortable: true,
8208                                                 resizeable: true,
8209                                                 key: 'subject'
8210                                         }, 
8211                                         {
8212                                                 label: mod_strings.LBL_LIST_DATE,
8213                                                 width: widths[4], 
8214                                                 sortable: true,
8215                                                 resizeable: true,
8216                         key: 'date'
8217                                         }, 
8218                                         {
8219                                                 label: app_strings.LBL_EMAIL_TO,
8220                                                 width: widths[5], 
8221                                                 sortable: false,
8222                                                 resizeable: true,
8223                         key: 'to_addrs'
8224                                         }, 
8225                                         {
8226                                                 label: 'uid',
8227                                                 hidden: true,
8228                         key: 'uid'
8229                                         }, 
8230                                         {
8231                                                 label: 'mbox',
8232                                                 hidden: true,
8233                         key: 'mbox'
8234                                         }, 
8235                                         {
8236                                                 label: 'ieId',
8237                                                 hidden: true,
8238                         key: 'ieId'
8239                                         }, 
8240                                         {       
8241                                                 label: 'site_url',
8242                                                 hidden: true,
8243                         key: 'site_url'
8244                                         },
8245                                         {       label: 'seen',
8246                                                 hidden: true,
8247                         key: 'seen'
8248                                         },
8249                                         {       label: 'type',
8250                                                 hidden: true,
8251                         key: 'type'
8252                                         }
8253                                 ];
8254                         
8255                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8256                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8257                                 responseSchema: {
8258                                     resultsList: 'Email',
8259                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8260                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8261                                 }
8262                     });
8263                         var params = {
8264                                         to_pdf : "true",
8265                                         module : "Emails",
8266                                         action : "EmailUIAjax",
8267                                         emailUIAction : "getMessageList",
8268                                         mbox : "INBOX",
8269                                         ieId : "",
8270                                         forceRefresh : "false"
8271                         };
8272                         if(lazyLoadFolder != null) {
8273                                 params['mbox'] = lazyLoadFolder.folder;
8274                                 params['ieId'] = lazyLoadFolder.ieId;
8275                                 //Check if the folder is a Sugar Folder
8276                                 var test = new String(lazyLoadFolder.folder);
8277                                 if(test.match(/SUGAR\./)) {
8278                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8279                                         params['mbox'] = test.substr(6);
8280                                 }
8281                         }
8282                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8283         
8284                         // create the Grid
8285                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8286                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8287                                 dynamicData: true,
8288                                 paginator: new YAHOO.widget.Paginator({ 
8289                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8290                                         containers : ["dt-pag-nav"],
8291                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8292                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8293                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8294                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8295                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8296                                 }),
8297                                 initialRequest:SUGAR.util.paramsToUrl(params),
8298                                 width:  "800px",
8299                                 height: "400px"
8300                         });
8301
8302                         initRowDD();
8303
8304                         //Override Paging request construction
8305                         grid.set("generateRequest", function(oState, oSelf) {
8306                     oState = oState || {pagination:null, sortedBy:null};
8307                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8308                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8309                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8310                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8311                     // Build the request 
8312                     var ret = 
8313                             SUGAR.util.paramsToUrl(oSelf.params) + 
8314                             "&sort=" + sort +
8315                         "&dir=" + dir +
8316                         "&start=" + startIndex +
8317                         ((results !== null) ? "&limit=" + results : "");
8318                     return  ret;
8319                 });
8320                         
8321                         
8322                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8323                                 oPayload = oPayload || { };
8324                                 
8325                                 oPayload.totalRecords = oResponse.meta.total;
8326                                 oPayload.unreadRecords = oResponse.meta.unread;
8327                                 
8328                         var tabObject = SE.innerLayout.get("tabs")[0];
8329                         var mboxTitle = "";
8330                         if (this.params.mbox != null) {
8331                                 mboxTitle = this.params.mbox;
8332                         }
8333                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8334                         tabObject.get("labelEl").firstChild.data = tabtext;
8335                         
8336                         if (SE.tree) {
8337                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8338                                 if (node) {
8339                                         node.data.unseen = oResponse.meta.unread;
8340                                         SE.accounts.renderTree();
8341                                 }
8342                         }
8343                                 return oPayload; 
8344                         }
8345                         
8346                         var resize = grid.resizeGrid = function () {
8347                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8348                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8349                         }
8350                         grid.convertDDRows = function() {
8351                                 var rowEl = this.getFirstTrEl();
8352                                 while (rowEl != null) {
8353                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8354                                         rowEl = this.getNextTrEl(rowEl);
8355                                 }
8356                         }
8357                         
8358                         
8359                         grid.on("columnResizeEvent", function(o) {
8360                                 //Find the index of the column
8361                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8362                                 for (var i=0; i < colSet.length; i++) {
8363                                         if (o.column == colSet[i]) {
8364                                                 //Store it in the cookie
8365                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8366                                         }
8367                                 }
8368                                 //this.resizeGrid();
8369                         }, null, grid); 
8370                         
8371                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8372                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8373                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8374                         grid.render();
8375                         SUGAR.email2.listViewLayout.on("render", resize);
8376                         resize();
8377                         
8378                         //Setup the default load parameters
8379                         SUGAR.email2.grid.params = params;
8380                         
8381                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8382                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8383                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8384                 }
8385         };
8386         e2Grid.init();
8387 };
8388
8389
8390 function initRowDD() {
8391         var sg = SUGAR.email2.grid,
8392         Dom = YAHOO.util.Dom;
8393         sg.DDRow = function(oDataTable, oRecord, elTr) {
8394                 if(oDataTable && oRecord && elTr) {
8395                         this.ddtable = oDataTable;
8396                 this.table = oDataTable.getTableEl();
8397                 this.row = oRecord;
8398                 this.rowEl = elTr;
8399                 this.newIndex = null;
8400                 this.init(elTr);
8401                 this.initFrame(); // Needed for DDProxy
8402                 this.invalidHandleTypes = {};
8403             }   
8404         };
8405         
8406         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8407             _resizeProxy: function() {
8408                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8409                 var dragEl = this.getDragEl(),
8410                     el = this.getEl();
8411                 var xy = Dom.getXY(el);
8412                 
8413                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8414                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8415                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8416                 Dom.setStyle(dragEl, 'display', "");
8417             },
8418             
8419             startDrag: function(x, y) { 
8420                 //Check if we should be dragging a set of rows rather than just the one.
8421                 var selectedRows = this.ddtable.getSelectedRows();
8422                 var iSelected = false;
8423                 for (var i in selectedRows) {
8424                         if (this.rowEl.id == selectedRows[i]) {
8425                                 iSelected = true;
8426                                 break
8427                         }
8428                 }
8429                 if (iSelected) {
8430                         this.rows = [];
8431                         for (var i in selectedRows) {
8432                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8433                         }
8434                 } else {
8435                         this.rows = [this.row];
8436                         this.ddtable.unselectAllRows();
8437                         this.ddtable.selectRow(this.row);
8438                 }
8439                 
8440                 //Initialize the dragable proxy
8441                 var dragEl = this.getDragEl(); 
8442                 var clickEl = this.getEl(); 
8443                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8444                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8445                 Dom.addClass(dragEl, "yui-dt-liner");
8446                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8447                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8448                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8449                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8450             },
8451             
8452             clickValidator: function(e) {
8453                 if (this.row.getData()[0] == " ")
8454                         return false;
8455                 var target = YAHOO.util.Event.getTarget(e);
8456                 return ( this.isValidHandleChild(target) && 
8457                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8458             },
8459             /**
8460              * This funciton checks that the target of the drag is a table row in this
8461              * DDGroup and simply moves the sourceEL to that location as a preview.
8462              */
8463             onDragOver: function(ev, id) {
8464                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8465                 if (node && node != this.targetNode) {
8466                         this.targetNode = node;
8467                         SUGAR.email2.folders.unhighliteAll();
8468                         node.highlight();
8469                 }
8470             },
8471             
8472             onDragOut: function(e, id) {
8473                 if (this.targetNode) {
8474                         SUGAR.email2.folders.unhighliteAll();
8475                         this.targetNode = false;
8476                 }
8477             },
8478             endDrag: function() {
8479                 Dom.setStyle(this.getEl(), "opacity", "");
8480                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8481                 if (this.targetNode) {
8482                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8483                 }
8484                 SUGAR.email2.folders.unhighliteAll();
8485                 this.rows = null;
8486             }
8487         });
8488 }
8489
8490 function AddressSearchGridInit() {
8491     function moduleIcon(elCell, oRecord, oColumn, oData) {
8492         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8493     };
8494     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8495         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8496     };
8497     var checkHeader = '<input type="checkbox" ';
8498     if (SUGAR.email2.util.isIe()) {
8499         checkHeader += 'style="top:-5px" ';
8500     }
8501     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8502     var colModel = 
8503             [{
8504                 label: checkHeader,
8505             width: 30,
8506             formatter: selectionCheckBox,
8507             key: 'bean_id'
8508         },
8509             {
8510                 label: mod_strings.LBL_LIST_TYPE,
8511                 width: 25,
8512                 formatter: moduleIcon,
8513                 key: 'bean_module'
8514         },
8515             {
8516                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8517                 width: 180,
8518                 sortable: true,
8519                 key: 'name'
8520             }, 
8521             {
8522                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8523                 width: 300, 
8524                 sortable: true,
8525                 key: 'email'
8526             }];
8527     
8528     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8529                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8530         responseSchema: {
8531             resultsList: 'Person',
8532             fields: ['name', 'email', 'bean_id', 'bean_module'],
8533                     metaFields: {total: 'TotalCount'}
8534         },
8535         //enable sorting on the server accross all data
8536         remoteSort: true
8537     });
8538     dataModel.params = {
8539                 to_pdf          : true,
8540                 module          : "Emails",
8541                 action          : "EmailUIAjax",
8542                 emailUIAction:"getAddressSearchResults"
8543     }
8544     var rb = document.getElementById('hasRelatedBean').checked;
8545         if (rb) {
8546                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8547                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8548                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8549                 dataModel.params['related_bean_id'] = relatedBeanId;
8550                 dataModel.params['related_bean_type'] = relatedBeanType;
8551                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8552         }
8553     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8554     
8555     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8556         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8557                 dynamicData: true,
8558                 paginator: new YAHOO.widget.Paginator({ 
8559                         rowsPerPage: 25,  
8560                         containers : ["dt-pag-nav-addressbook"],
8561                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8562                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8563                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8564                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8565                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8566                 }),
8567                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8568                 width:  "560px",
8569                 height: "250px"
8570     });
8571         //Override Paging request construction
8572         grid.set("generateRequest", function(oState, oSelf) {
8573         oState = oState || {pagination:null, sortedBy:null};
8574         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8575         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8576         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8577         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8578         // Build the request 
8579         var ret = 
8580             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8581             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8582             ((results !== null) ? "&limit=" + results : "");
8583         return  ret;
8584     });
8585     
8586         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8587                 oPayload = oPayload || { };
8588                 oPayload.totalRecords = oResponse.meta.total;
8589                 return oPayload; 
8590         }
8591         
8592         grid.clickToggleSelect= function(args) {
8593                 var isIE = (args.event.target == null);
8594                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8595                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8596                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8597                 }
8598         }
8599         
8600         grid.reSelectRowsOnRender = function (){
8601             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8602         for (var i = 0; i < rows.length; i++) 
8603         {
8604                 var emailAddress = rows[i].getData("email");
8605             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8606             if(alreadyAdded)
8607             {
8608                 rows[i].setData("selected",  true);
8609                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8610             }
8611             else
8612             {
8613                 rows[i].setData("selected",  false);
8614                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8615             }
8616         }
8617         }
8618         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8619         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8620         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8621     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8622     
8623     grid.render();
8624     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8625     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8626     
8627     grid.toggleSelectCheckbox = function(id,checked){
8628         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8629         row.setData("checked",checked);
8630     };
8631     grid.toggleSelect = function(id, checked) {
8632         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8633         checked = row.getData("selected");
8634         if (!checked)
8635         {
8636             SUGAR.email2.addressBook.grid.selectRow(row);
8637             SE.addressBook.insertContactRowToResultTable(id,null)
8638         } else 
8639         {
8640             SUGAR.email2.addressBook.grid.unselectRow(row);
8641             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8642         }
8643         row.setData("selected", !checked);
8644     };
8645     
8646     grid.toggleSelectAll = function(checked) {
8647         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8648         for (var i = 0; i < rows.length; i++) {
8649                         if (typeof(rows[i]) != "undefined")
8650                                 rows[i].setData("checked",  checked);
8651         }
8652         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8653         for (var i = 0; i < checkBoxes.length; i++) {
8654             checkBoxes[i].checked = checked;
8655         }
8656     };
8657     
8658     //Initialize the grid result table.
8659     AddressSearchResultsGridInit();
8660 }
8661
8662
8663
8664 /**
8665 *  Initalize the results table for the address book selection.
8666 *
8667 */
8668 function AddressSearchResultsGridInit()
8669 {
8670     
8671     /* Full name sort funciton to compare by last name if available */
8672     var fullNameSort = function(a, b, desc) {
8673         // Deal with empty values
8674         if(!YAHOO.lang.isValue(a))
8675             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8676         else if(!YAHOO.lang.isValue(b))
8677             return -1;
8678
8679         var aNames = a.getData("name").split(' ');
8680         var bNames = b.getData("name").split(' ');
8681
8682         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8683         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8684
8685         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8686
8687     };
8688     
8689     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8690                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8691                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8692               
8693     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})},
8694                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8695      
8696      var myDataSource = new YAHOO.util.DataSource([]); 
8697          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8698          myDataSource.responseSchema = { 
8699                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8700                 };                                                                 
8701     
8702          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8703                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8704     
8705      var highlightEditableCell = function(oArgs) {
8706             var elCell = oArgs.target;
8707             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8708                 this.highlightCell(elCell);
8709             }
8710         };
8711       
8712      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8713      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8714      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8715      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8716          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8717      
8718      //Setup the context menus
8719      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8720              var task = p_aArgs[1]; 
8721              if(task) 
8722              { 
8723                  var elRow = this.contextEventTarget; 
8724                  elRow = p_myDataTable.getTrEl(elRow); 
8725          
8726                  if(elRow) 
8727                  { 
8728                      switch(task.index) 
8729                      { 
8730                          case 0:     
8731                              var oRecord = p_myDataTable.getRecord(elRow); 
8732                              p_myDataTable.deleteRow(elRow);  
8733                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8734                      } 
8735                  } 
8736              } 
8737          };
8738      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8739                         {trigger:gridResults.getTbodyEl()}); 
8740          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8741          contextMenu.render("addrSearchResultGrid"); 
8742          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8743 }
8744 // End of File modules/Emails/javascript/grid.js
8745                                 
8746 /*********************************************************************************
8747  * SugarCRM is a customer relationship management program developed by
8748  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8749  * 
8750  * This program is free software; you can redistribute it and/or modify it under
8751  * the terms of the GNU Affero General Public License version 3 as published by the
8752  * Free Software Foundation with the addition of the following permission added
8753  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8754  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8755  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8756  * 
8757  * This program is distributed in the hope that it will be useful, but WITHOUT
8758  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8759  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8760  * details.
8761  * 
8762  * You should have received a copy of the GNU Affero General Public License along with
8763  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8764  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8765  * 02110-1301 USA.
8766  * 
8767  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8768  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8769  * 
8770  * The interactive user interfaces in modified source and object code versions
8771  * of this program must display Appropriate Legal Notices, as required under
8772  * Section 5 of the GNU Affero General Public License version 3.
8773  * 
8774  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8775  * these Appropriate Legal Notices must retain the display of the "Powered by
8776  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8777  * technical reasons, the Appropriate Legal Notices must display the words
8778  * "Powered by SugarCRM".
8779  ********************************************************************************/
8780
8781 /**
8782   Complex layout init
8783  */
8784 function complexLayoutInit() {
8785         var se = SUGAR.email2;
8786         var Dom = YAHOO.util.Dom;
8787         se.e2Layout = {
8788         getInnerLayout : function(rows) {
8789                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8790                 parent: se.complexLayout,  
8791                         border:true,
8792                     hideOnLayout: true,
8793                     height: 400,
8794                                 units: [{
8795                                         position: "center",
8796                                     scroll:false, // grid should autoScroll itself
8797                                     split:true,
8798                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8799                                 },{
8800                                         position: "bottom",
8801                                     scroll:true,
8802                                     collapse: false,
8803                                     resize: true,
8804                                     useShim:true,
8805                                     height:'250',
8806                                     body: "<div id='listBottom' />"
8807                                 },{
8808                                     position: "right",
8809                                     scroll:true,
8810                                     collapse: false,
8811                                     resize: true,
8812                                     useShim:true,
8813                                     width:'250',
8814                                     body: "<div id='listRight' />",
8815                                     titlebar: false //,header: "right"
8816                                 }]
8817             });
8818                 se.complexLayout.on("render", function(){
8819                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8820                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8821                                 SUGAR.email2.listViewLayout.set("height", height);
8822                                 SUGAR.email2.listViewLayout.render();
8823                 });
8824             se.listViewLayout.render();
8825             //CSS hack for now
8826             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8827             var rp = se.listViewLayout.resizePreview = function() {
8828                 var pre = Dom.get("displayEmailFramePreview");
8829                 if (pre) {
8830                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8831                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8832                 }
8833             };
8834             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8835             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8836             se.e2Layout.setPreviewPanel(rows);
8837             se.previewLayout = se.listViewLayout;
8838             return se.listViewLayout;
8839         },
8840         
8841         getInnerLayout2Rows : function() {
8842             return this.getInnerLayout(true);
8843         },
8844         getInnerLayout2Columns : function() {
8845             return this.getInnerLayout(false);
8846         },
8847         
8848         init : function(){
8849             // initialize state manager, we will use cookies
8850 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8851                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8852                 se.complexLayout = new YAHOO.widget.Layout("container", {
8853                         border:true,
8854                 hideOnLayout: true,
8855                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8856                 width: Dom.getViewportWidth() - 40,
8857                 units: [{
8858                         position: "center",
8859                     scroll:false,
8860                     body: "<div id='emailtabs'></div>"
8861                 },
8862                 {
8863                         position: "left",
8864                         scroll: true,
8865                         body: "<div id='lefttabs'></div>",
8866                     collapse: true,
8867                     width: 210,
8868                     minWidth: 100,
8869                     resize:true,
8870                     useShim:true,
8871                     titlebar: true,
8872                     header: "&nbsp;"
8873                 },
8874                 {
8875                     header: Dom.get('footerLinks').innerHTML,
8876                                         position: 'bottom',
8877                                         id: 'mbfooter',
8878                                         height: 22,
8879                                         border: false
8880                 }]
8881             });
8882                 se.complexLayout.render();
8883                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8884                         tp.addTab(new YAHOO.widget.Tab({ 
8885                                 label: "Inbox",
8886                                 scroll : true,
8887                                 content : "<div id='listViewDiv'/>",
8888                                 id : "center",
8889                                 active : true
8890                         }));
8891                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8892                         tp.appendTo(centerEl);
8893                         //CSS hack for now
8894                         tp.get("element").style.borderRight = "1px solid #666"
8895                         
8896                         var listV =  this.getInnerLayout2Rows();
8897                         listV.set("height", tp.get("element").clientHeight - 25);
8898                         listV.render();
8899                 
8900             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8901             var folderTab = new YAHOO.widget.Tab({ 
8902                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8903                                 scroll : true,
8904                                 content : "<div id='emailtree'/>",
8905                                 id : "tree",
8906                                 active : true
8907                         });
8908             folderTab.on("activeChange", function(o){ 
8909                 if (o.newValue) {
8910                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8911                 }
8912             });
8913             se.leftTabs.addTab(folderTab);
8914             
8915             var tabContent = SUGAR.util.getAndRemove("searchTab");
8916             var searchTab = new YAHOO.widget.Tab({ 
8917                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8918                                 scroll : true,
8919                                 content : tabContent.innerHTML,
8920                                 id : tabContent.id
8921                         });
8922             searchTab.on("activeChange", function(o){ 
8923                 if (o.newValue) 
8924                 {
8925                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8926                    //Setup the calendars if needed
8927                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
8928                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
8929                    
8930                        //Initalize sqs object for assigned user name 
8931                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
8932                        
8933                        //Attach event handler for when the relate module option is selected for the correct sqs object
8934                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8935                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8936                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
8937                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8938                        
8939                        //If enter key is pressed, perform search
8940                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8941                        for(var i=0; i < addKeyPressFields.length;i++)
8942                        {
8943                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8944                                 if (e.keyCode == 13) {
8945                                         YAHOO.util.Event.stopEvent(e);
8946                                         SUGAR.email2.search.searchAdvanced();
8947                                 }
8948                        });
8949                        }
8950                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
8951                        enableQS(true);
8952                        //Clear parent values if selecting another parent type.
8953                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
8954                            function(){ 
8955                                document.getElementById('data_parent_id_search').value =''; 
8956                                document.getElementById('data_parent_name_search').value =''; 
8957                            });
8958                 
8959                 }
8960             });
8961             se.leftTabs.addTab(searchTab);
8962             
8963             var resizeTabBody = function() {
8964                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8965                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8966             }
8967             resizeTabBody();
8968             se.complexLayout.on("render", resizeTabBody);
8969             se.leftTabs.on("activeTabChange", resizeTabBody);
8970                         //hack to allow left pane scroll bar to fully show
8971                 var lefttabsDiv = document.getElementById('lefttabs');
8972                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8973                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8974                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8975           
8976         },
8977         initSQSObject: function(formName,fieldName)
8978         {
8979             var fullFieldName = formName + '_' + fieldName; //SQS Convention
8980             var resultName = fullFieldName + '_' + 'results';
8981             
8982             if (QSFieldsArray[fullFieldName] != null) 
8983             {
8984                 QSFieldsArray[fullFieldName].destroy();
8985                 delete QSFieldsArray[fullFieldName];
8986             }
8987             if (QSProcessedFieldsArray[fullFieldName])
8988             QSProcessedFieldsArray[fullFieldName] = false;
8989
8990             if( Dom.get(resultName) )
8991             {
8992                 var obj = document.getElementById(resultName);
8993                 obj.parentNode.removeChild(obj);
8994             }
8995         },
8996         setPreviewPanel: function(rows) {
8997                 if (rows) {
8998                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8999                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9000                 Dom.get("listRight").innerHTML = "";
9001                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9002             } else {
9003                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9004                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9005                 Dom.get("listBottom").innerHTML = "";
9006                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9007             }
9008         }
9009     };
9010         se.e2Layout.init();
9011 }
9012
9013 var myBufferedListenerObject = new Object();
9014 myBufferedListenerObject.refit = function() {
9015     if(SUGAR.email2.grid) {
9016         SUGAR.email2.grid.autoSize();
9017     }
9018 }
9019 // End of File modules/Emails/javascript/complexLayout.js
9020                                 
9021 /*********************************************************************************
9022  * SugarCRM is a customer relationship management program developed by
9023  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9024  * 
9025  * This program is free software; you can redistribute it and/or modify it under
9026  * the terms of the GNU Affero General Public License version 3 as published by the
9027  * Free Software Foundation with the addition of the following permission added
9028  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9029  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9030  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9031  * 
9032  * This program is distributed in the hope that it will be useful, but WITHOUT
9033  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9034  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9035  * details.
9036  * 
9037  * You should have received a copy of the GNU Affero General Public License along with
9038  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9039  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9040  * 02110-1301 USA.
9041  * 
9042  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9043  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9044  * 
9045  * The interactive user interfaces in modified source and object code versions
9046  * of this program must display Appropriate Legal Notices, as required under
9047  * Section 5 of the GNU Affero General Public License version 3.
9048  * 
9049  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9050  * these Appropriate Legal Notices must retain the display of the "Powered by
9051  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9052  * technical reasons, the Appropriate Legal Notices must display the words
9053  * "Powered by SugarCRM".
9054  ********************************************************************************/
9055
9056
9057 /******************************************************************************
9058  * Initialize Email 2.0 Application
9059  */
9060
9061 //Override Sugar Languge so quick creates work properly
9062
9063
9064 function email2init() {
9065
9066         //Init Tiny MCE
9067     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9068     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9069     if (!SUGAR.util.isTouchScreen()) {
9070          tinyMCE.init({
9071                  convert_urls : false,
9072          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9073          width: tinyConfig.width,
9074          theme: tinyConfig.theme,
9075          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9076          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9077          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9078          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9079          plugins : tinyConfig.plugins,
9080          elements : tinyConfig.elements,
9081          language : tinyConfig.language,
9082          extended_valid_elements : tinyConfig.extended_valid_elements,
9083          mode: tinyConfig.mode,
9084          strict_loading_mode : true,
9085                  force_br_newlines : true,
9086          forced_root_block : '',
9087          directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
9088      });
9089     }
9090
9091     // initialze message overlay
9092     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9093             //iframe        : true,
9094             modal       : false,
9095             autoTabs    : true,
9096             width       : 300,
9097             height      : 120,
9098             shadow      : true
9099         }
9100     );
9101         // Hide Sugar menu
9102         if (SUGAR.themes.tempHideLeftCol)
9103         SUGAR.themes.tempHideLeftCol();
9104
9105         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9106 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9107
9108         // set defaults for YAHOO.util.DragDropManager
9109         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9110
9111         SUGAR.email2.nextYear = new Date();
9112         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9113
9114         
9115     // initialize and display UI framework (complexLayout.js)
9116     complexLayoutInit();
9117     
9118     // initialize and display grid (grid.js)
9119     gridInit();
9120     
9121     // initialize treeview for folders
9122         //onloadTreeinit();
9123         SUGAR.email2.folders.rebuildFolders(true);
9124         
9125         
9126     //Setup the Message Box overlay
9127     /*Ext.MessageBox.maxWidth = 350;
9128     Ext.MessageBox.minProgressWidth = 350;
9129
9130         ///////////////////////////////////////////////////////////////////////////
9131         ////    CONTEXT MENUS
9132         // detailView array
9133         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9134 */
9135         var SEC = SUGAR.email2.contextMenus; 
9136         
9137         //Grid menu
9138         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9139                 trigger: SUGAR.email2.grid.get("element"),
9140                 lazyload: true
9141         });
9142         emailMenu.subscribe("beforeShow", function() {
9143                 var oTarget = this.contextEventTarget;
9144                 if (typeof(oTarget) == "undefined")
9145                   return;
9146                 var grid = SUGAR.email2.grid;
9147                 var selectedRows = grid.getSelectedRows();
9148                 var multipleSelected = (selectedRows.length > 1) ? true: false;
9149                 if (!multipleSelected)
9150                 {
9151                         grid.unselectAllRows();
9152                         grid.selectRow(oTarget);
9153                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
9154                 }
9155                 else if(multipleSelected)
9156                 {
9157                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9158                 }
9159         });
9160         
9161         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9162         //us to access individual elements easier by name rather than by index
9163         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
9164                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9165         emailMenu.addItems([
9166         {
9167             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9168             id: 'showDetailView',
9169             onclick: { fn: SEC.showDetailView }
9170         },
9171         {
9172             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9173             onclick: { fn: SEC.openMultiple }
9174         },
9175         {
9176             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9177             onclick: { fn: SEC.archiveToSugar }
9178         },
9179         {
9180             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9181             id: 'reply',
9182             onclick: { fn: SEC.replyForwardEmailContext }
9183         },
9184         {
9185             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9186             id: 'replyAll',
9187             onclick: { fn: SEC.replyForwardEmailContext }
9188         },
9189         {
9190             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9191             id: 'forward',
9192             onclick: { fn: SEC.replyForwardEmailContext }
9193         },
9194         {
9195             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9196             id: 'delete',
9197             onclick: { fn: SEC.markDeleted }
9198         },
9199         {
9200             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9201             id: 'print',
9202             onclick: { fn: SEC.viewPrintable }
9203         },                
9204         // Mark... submenu
9205         {
9206             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9207             submenu: {
9208                         id: "markEmailMenu",
9209                 itemdata : [
9210                     {
9211                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9212                         onclick: { fn: SEC.markUnread }
9213                     },
9214                     {
9215                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9216                         onclick: { fn: SEC.markRead }
9217                     },
9218                     {
9219                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9220                         onclick: { fn: SEC.markFlagged }
9221                     },
9222                     {
9223                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9224                         onclick: {  fn: SEC.markUnflagged }
9225                     }
9226                 ]
9227             }
9228          },
9229         {
9230             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9231                 id: 'assignTo',
9232                 onclick: { fn: SEC.assignEmailsTo }
9233          },
9234          {
9235             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9236             id: 'relateTo',
9237             onclick: { fn: SEC.relateTo }
9238          }
9239     ]);
9240         SEC.emailListContextMenu.render();
9241         
9242         //Handle the Tree folder menu trigger ourselves
9243         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9244
9245         
9246         //Folder Menu
9247     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9248                 trigger: "",
9249                 lazyload: true 
9250         });
9251     SEC.frameFoldersContextMenu.addItems([
9252                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9253                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9254                         onclick: {  fn: function() {
9255                         var node = SUGAR.email2.clickedFolderNode;
9256                         if (node.data.ieId) {
9257                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9258                     }}
9259                 },
9260                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9261                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9262                         onclick: {  fn: function() {
9263                         var node = SUGAR.email2.clickedFolderNode;
9264                         if (node.data.ieId) {
9265                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9266                     }}
9267                 },
9268                 {
9269                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9270                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9271                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9272                 },
9273                 {
9274                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9275                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9276                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9277                 },
9278                 {
9279                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9280                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9281                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9282                  },
9283                  {
9284                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9285                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9286                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9287                   },
9288                  {
9289                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9290                     onclick: {  fn: function() {
9291                         var node = SUGAR.email2.clickedFolderNode;
9292                         if (node.data.ieId) {
9293                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9294                     }}
9295                   } 
9296         ]);
9297     SEC.frameFoldersContextMenu.render();
9298     
9299     SEC.initContactsMenu = function() {
9300         // contacts
9301         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9302                 trigger: "contacts",
9303                 lazyload: true
9304         });
9305         SEC.contactsContextMenu.addItems([
9306                 {
9307                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9308                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9309                 },
9310                 {
9311                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9312                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9313                 }
9314         ]);
9315         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9316                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9317                 if (oTarget && !grid.isSelected(oTarget)) {
9318                         grid.unselectAllRows();
9319                         grid.selectRow(oTarget);
9320                 }
9321         });
9322         SEC.contactsContextMenu.render();
9323         }
9324         
9325         
9326         // set auto-check timer
9327         SUGAR.email2.folders.startCheckTimer();
9328         // check if we're coming from an email-link click
9329         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9330         
9331         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9332         
9333         //Init fix for YUI 2.7.0 datatable sort.
9334         SUGAR.email2.addressBook.initFixForDatatableSort();
9335 }
9336
9337 function createTreePanel(treeData, params) {
9338         var tree = new YAHOO.widget.TreeView(params.id);
9339         var root = tree.getRoot();
9340         
9341         //if (treeData.nodes && treeData[0].id == "Home")
9342         //      treeData = treeData[0];
9343
9344         addChildNodes(root, treeData);
9345         
9346         return tree;
9347 }
9348
9349 function addChildNodes(parentNode, parentData) {
9350         var Ck = YAHOO.util.Cookie;
9351         var nextyear = SUGAR.email2.nextYear;
9352         var nodes = parentData.nodes || parentData.children;
9353         for (i in nodes) {
9354                 if (typeof(nodes[i]) == 'object') {
9355                         if (nodes[i].data) {
9356                                 nodes[i].data.href = '#';
9357                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9358                                 node.action = nodes[i].data.action;
9359                         } else {
9360                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9361                                         addChildNodes(parentNode, nodes[i]);
9362                                         return;
9363                                 }
9364                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9365                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9366                                 if (nodes[i].cls) {
9367                                         nodes[i].className = nodes[i].cls;
9368                                 }
9369                                 nodes[i].href = "#";
9370                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9371                                 //Override YUI child node creation
9372                                 if (nodes[i].children) {
9373                                         nodes[i].nodes = nodes[i].children;
9374                                         nodes[i].children = [ ];
9375                                 }
9376                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9377                         }
9378                         
9379                         if (typeof(nodes[i].nodes) == 'object') {
9380                                 addChildNodes(node, nodes[i]);
9381                         }
9382                 }
9383         }
9384 }
9385
9386 /**
9387  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9388  */
9389 function email2treeinit(tree, treedata, treediv, params) {
9390         //ensure the tree data is not corrupt
9391         if (!treedata) {
9392            return;
9393         }
9394         if (SUGAR.email2.tree) {
9395                 SUGAR.email2.tree.destroy();
9396                 SUGAR.email2.tree = null;
9397         }
9398         
9399         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9400                 id: 'emailtree'
9401         });
9402         
9403         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9404         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9405         tree.subscribe("expandComplete", function(node){
9406                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9407                 for (var i in node.children) {
9408                         SE.accounts.setupDDTarget(node.children[i]);
9409                 }
9410         });
9411         tree.setCollapseAnim("TVSlideOut");
9412         tree.setExpandAnim("TVSlideIn");
9413         var root = tree.root;
9414         while (root.hasChildren()) {
9415                 var node = root.children[0];
9416                 node.destroy();
9417                 tree.removeNode(root.children[0], false);
9418         }
9419         addChildNodes(root, treedata);
9420         tree.render();
9421         SUGAR.email2.accounts.renderTree();
9422 }
9423
9424 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9425         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9426 };
9427
9428
9429 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9430     startDrag: function(x, y) {
9431                 var Dom = YAHOO.util.Dom;       
9432                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9433                 
9434                 this.dragId = "";
9435                 var dragEl = this.getDragEl();  
9436         var clickEl = this.getEl(); 
9437         Dom.setStyle(clickEl, "color", "#AAA");
9438         Dom.setStyle(clickEl, "opacity", "0.25"); 
9439         dragEl.innerHTML = clickEl.innerHTML; 
9440          
9441         Dom.addClass(dragEl, "ygtvcell");
9442         Dom.addClass(dragEl, "ygtvcontent");
9443         Dom.addClass(dragEl, "folderDragProxy");
9444         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9445         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9446         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9447         Dom.setStyle(dragEl, "opacity", "0.5"); 
9448             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9449     },
9450     
9451     onDragOver: function(ev, id) {
9452         var Dom = YAHOO.util.Dom;
9453         if (id != this.dragId)
9454         {
9455                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9456                 if(node.data.cls != "sugarFolder") {
9457                         SUGAR.email2.folders.unhighliteAll();
9458                         return;
9459                 }
9460                 this.dragId = id;
9461                 this.targetNode = node;
9462                 SUGAR.email2.folders.unhighliteAll();
9463                 node.highlight();
9464         }
9465     },
9466     
9467     onDragOut: function(e, id) {
9468         if (this.targetNode) {
9469                 SUGAR.email2.folders.unhighliteAll();
9470                 this.targetNode = false;
9471                 this.dragId = false;
9472         }
9473     },
9474     
9475     endDrag: function() { 
9476         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9477         if (this.targetNode) {
9478                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9479         }
9480     }
9481 });// End of File modules/Emails/javascript/init.js
9482                                 
9483 /*********************************************************************************
9484  * SugarCRM is a customer relationship management program developed by
9485  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9486  * 
9487  * This program is free software; you can redistribute it and/or modify it under
9488  * the terms of the GNU Affero General Public License version 3 as published by the
9489  * Free Software Foundation with the addition of the following permission added
9490  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9491  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9492  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9493  * 
9494  * This program is distributed in the hope that it will be useful, but WITHOUT
9495  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9496  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9497  * details.
9498  * 
9499  * You should have received a copy of the GNU Affero General Public License along with
9500  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9501  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9502  * 02110-1301 USA.
9503  * 
9504  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9505  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9506  * 
9507  * The interactive user interfaces in modified source and object code versions
9508  * of this program must display Appropriate Legal Notices, as required under
9509  * Section 5 of the GNU Affero General Public License version 3.
9510  * 
9511  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9512  * these Appropriate Legal Notices must retain the display of the "Powered by
9513  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9514  * technical reasons, the Appropriate Legal Notices must display the words
9515  * "Powered by SugarCRM".
9516  ********************************************************************************/
9517
9518 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9519 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9520 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9521 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9522 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9523 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9524 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9525 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9526 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9527 '               <input type="hidden" id="composeType" name="composeType">' +
9528 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9529 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9530 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9531 '               <input type="hidden" id="sendTo" name="sendTo">' +
9532 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9533 '               <input type="hidden" id="sendCc" name="sendCc">' +
9534 '               <input type="hidden" id="setEditor" name="setEditor">' +
9535 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9536 '               <input type="hidden" id="parent_id" name="parent_id">' +
9537 '               <input type="hidden" id="parent_type" name="parent_type">' +
9538 '               <input type="hidden" id="attachments" name="attachments">' +
9539 '               <input type="hidden" id="documents" name="documents">' +
9540 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9541 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9542 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9543 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9544 '                       <tr>' +
9545 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9546 '                                       <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>' +
9547 '                                       <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>' +
9548 '                                       <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>' +
9549 '                                       <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>' +
9550 '</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>' + 
9551 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9552 '<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>' +
9553 '                       </td></tr></tbody></table></th>'     +
9554 '                       </tr>' +
9555 '                       <tr>' +
9556 '                               <td>' +
9557 '                                       <div style="margin:5px;">' +
9558 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9559 '                                               <tr>' +
9560 '                                                       <td class="emailUILabel" NOWRAP >' +
9561 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9562 '                                                       </td>' +
9563 '                                                       <td class="emailUIField" NOWRAP>' +
9564 '                                                               <div>' +
9565 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9566 '                                                               </div>' +
9567 '                                                       </td>' +
9568 '                                               </tr>' +
9569 '                                               <tr>' +
9570 '                                                       <td class="emailUILabel" NOWRAP>' +
9571 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9572 '                                   {app_strings.LBL_EMAIL_TO}:' +
9573 '                               </button>' + 
9574 '                                                       </td>' +
9575 '                                                       <td class="emailUIField" NOWRAP>' +
9576 '                                                               <div class="ac_autocomplete">' +
9577 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9578 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9579 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9580 '                                                               </div>' +
9581 '                                                       </td>' +
9582 '                                               </tr>' +
9583 '                                               <tr id="add_addr_options_tr{idx}">' +
9584 '                                                       <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>'+
9585 '                                               </tr>'+
9586 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9587 '                                                       <td class="emailUILabel" NOWRAP>' +
9588 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9589 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9590 '                               </button>' + 
9591 '                                                       </td>' +
9592 '                                                       <td class="emailUIField" NOWRAP>' +
9593 '                                                               <div class="ac_autocomplete">' +
9594 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9595 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9596 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9597 '                                                               </div>' +
9598 '                                                       </td>' +
9599 '                                               </tr>' +
9600 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9601 '                                                       <td class="emailUILabel" NOWRAP>' +
9602 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9603 '                               {app_strings.LBL_EMAIL_BCC}:' +
9604 '                               </button>' + 
9605 '                                                       </td>' +
9606 '                                                       <td class="emailUIField" NOWRAP>' +
9607 '                                                               <div class="ac_autocomplete">' +
9608 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9609 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9610 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9611 '                                                               </div>' +
9612 '                                                       </td>' +
9613 '                                               </tr>' +
9614 '                                               <tr>' +
9615 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9616 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9617 '                                                       </td>' +
9618 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9619 '                                                               <div class="ac_autocomplete">' +
9620 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9621 '                                                               </div>' +
9622 '                                                       </td>' +
9623 '                                               </tr>' +
9624 '                                       </table>' +
9625 '                                       </div>' +
9626 '                               </td>'   +
9627 '                       </tr>' +
9628 '               </table>' +
9629 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9630 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9631 '                       <div style="padding:5px;">' +
9632 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9633 '                                       <tr>' +
9634 '                                               <th>' +
9635 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9636 '                                                       <br />' +
9637 '                                                       &nbsp;' +
9638 '                                               </th>' +
9639 '                                       </tr>' +
9640 '                                       <tr>' +
9641 '                                               <td>' +
9642 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9643 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9644 '                                               </td>' +
9645 '                                       </tr>' +
9646 '                                       <tr>' +
9647 '                                               <td>' +
9648 '                                                       &nbsp;' +
9649 '                                                       <br />' +
9650 '                                                       &nbsp;' +
9651 '                                               </td>' +
9652 '                                       </tr>' +
9653 '                                       <tr>' +
9654 '                                               <th>' +
9655 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9656 '                                                       <br />' +
9657 '                                                       &nbsp;' +
9658 '                                               </th>' +
9659 '                                       </tr>' +
9660 '                                       <tr>' +
9661 '                                               <td>' +
9662 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9663 '                                                       <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>' +
9664 '                                               </td>' +
9665 '                                       </tr>' +
9666 '                                       <tr>' +
9667 '                                               <td>' +
9668 '                                                       &nbsp;' +
9669 '                                                       <br />' +
9670 '                                                       &nbsp;' +
9671 '                                               </td>' +
9672 '                                       </tr>' +
9673 '                                       <tr>' +
9674 '                                               <th>' +
9675 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9676 '                                                       <br />' +
9677 '                                                       &nbsp;' +
9678 '                                               </th>' +
9679 '                                       </tr>' +
9680 '                                       <tr>' +
9681 '                                               <td>' +
9682 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9683 '                                               </td>' +
9684 '                                       </tr>' +
9685 '                               </table>' +
9686 '                       </div>' +
9687 '               </div>' +
9688 '       </form>' +
9689 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9690 '             <div style="padding:5px;">' +
9691 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9692 '                               <table border="0" width="100%">' +
9693 '                                       <tr>' +
9694 '                                               <td NOWRAP style="padding:2px;">' +
9695 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9696 '                                               </td>' +
9697 '                                       </tr>' +
9698 '                                       <tr>' +
9699 '                                               <td NOWRAP style="padding:2px;">' +
9700 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9701 '                                               </td>' +
9702 '                                       </tr>' +
9703 '                               </table>' +
9704 '                               <br />' +
9705 '                               <table border="0" width="100%">' +
9706 '                                       <tr>' +
9707 '                                               <td NOWRAP style="padding:2px;">' +
9708 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9709 '                                               </td>' +
9710 '                                       </tr>' +
9711 '                                       <tr>' +
9712 '                                               <td NOWRAP style="padding:2px;">' +
9713 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9714 '                                               </td>' +
9715 '                                       </tr>' +
9716 '                               </table>' +
9717 '                               <table border="0" width="100%">' +
9718 '                                       <tr>' +
9719 '                                               <td NOWRAP style="padding:2px;">' +
9720 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9721 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9722 '                                               </td>' +
9723 '                                       </tr>' +
9724 '                               </table>' +
9725 '         </form>' +
9726 '                       </div> ' +
9727 '               </div>' +
9728 '</div>';
9729 // End of File modules/Emails/javascript/composeEmailTemplate.js
9730                                 
9731 /*********************************************************************************
9732  * SugarCRM is a customer relationship management program developed by
9733  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9734  * 
9735  * This program is free software; you can redistribute it and/or modify it under
9736  * the terms of the GNU Affero General Public License version 3 as published by the
9737  * Free Software Foundation with the addition of the following permission added
9738  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9739  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9740  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9741  * 
9742  * This program is distributed in the hope that it will be useful, but WITHOUT
9743  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9744  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9745  * details.
9746  * 
9747  * You should have received a copy of the GNU Affero General Public License along with
9748  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9749  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9750  * 02110-1301 USA.
9751  * 
9752  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9753  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9754  * 
9755  * The interactive user interfaces in modified source and object code versions
9756  * of this program must display Appropriate Legal Notices, as required under
9757  * Section 5 of the GNU Affero General Public License version 3.
9758  * 
9759  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9760  * these Appropriate Legal Notices must retain the display of the "Powered by
9761  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9762  * technical reasons, the Appropriate Legal Notices must display the words
9763  * "Powered by SugarCRM".
9764  ********************************************************************************/
9765
9766 SUGAR.email2.templates['displayOneEmail'] = 
9767 '<div class="emailDetailTable" style="height:100%">' +
9768 '<div id="viewMenuDiv{idx}"></div>' + 
9769 '<div width="100%" class="displayEmailValue">' +
9770 '                                       <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>' +
9771 '                                       <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>' +
9772 '                                       <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>' +
9773 '                                       <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>' +
9774 '                                       <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>' +
9775 '                                       <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>' +
9776 '                                       <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>' +
9777 '                                       <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>' +
9778 '                                       <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>' +
9779 '</div>' +
9780 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9781 '                               <tr>' +
9782 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9783 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9784 '                                       </td>' +
9785 '                                       <td width="99%" class="displayEmailValue">' +
9786 '                                               {email.from_addr}' +
9787 '                                       </td>' +
9788 '                               </tr>' +
9789 '                               <tr>' +
9790 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9791 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9792 '                                       </td>' +
9793 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9794 '                                               <b>{email.name}</b>' +
9795 '                                       </td>' +
9796 '                               </tr>' +
9797 '                               <tr>' +
9798 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9799 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9800 '                                       </td>' +
9801 '                                       <td class="displayEmailValue">' +
9802 '                                               {email.date_start} {email.time_start}' +
9803 '                                       </td>' +
9804 '                               </tr>' +
9805 '                               <tr>' +
9806 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9807 '                                               {app_strings.LBL_EMAIL_TO}:' +
9808 '                                       </td>' +
9809 '                                       <td class="displayEmailValue">' +
9810 '                                               {email.toaddrs}' +
9811 '                                       </td>' +
9812 '                               </tr>' +
9813 '                               <tr>{meta.cc}</tr>' +
9814 '                               <tr>{email.attachments}</tr>' +
9815 '                       </table>' +
9816 '                       <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>' +
9817 //'                           {email.description}' +
9818 '</div>'
9819 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9820                                 
9821 /*********************************************************************************
9822  * SugarCRM is a customer relationship management program developed by
9823  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9824  * 
9825  * This program is free software; you can redistribute it and/or modify it under
9826  * the terms of the GNU Affero General Public License version 3 as published by the
9827  * Free Software Foundation with the addition of the following permission added
9828  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9829  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9830  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9831  * 
9832  * This program is distributed in the hope that it will be useful, but WITHOUT
9833  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9834  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9835  * details.
9836  * 
9837  * You should have received a copy of the GNU Affero General Public License along with
9838  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9839  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9840  * 02110-1301 USA.
9841  * 
9842  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9843  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9844  * 
9845  * The interactive user interfaces in modified source and object code versions
9846  * of this program must display Appropriate Legal Notices, as required under
9847  * Section 5 of the GNU Affero General Public License version 3.
9848  * 
9849  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9850  * these Appropriate Legal Notices must retain the display of the "Powered by
9851  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9852  * technical reasons, the Appropriate Legal Notices must display the words
9853  * "Powered by SugarCRM".
9854  ********************************************************************************/
9855
9856 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9857 '<body onload="javascript:window.print();">' + 
9858 '<style>' + 
9859 'body {' + 
9860 '       margin: 0px;' + 
9861 '       font-family: helvetica, impact, sans-serif;' +
9862 '       font-size : 12pt;' +
9863 '} ' +
9864 'table {' +
9865 '       padding:10px;' +
9866 '}' +
9867 '</style>' +
9868 '<div>' +
9869 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9870 '       <tr>' +
9871 '               <td>' +
9872 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9873 '                               <tr>' +
9874 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9875 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9876 '                                       </td>' +
9877 '                                       <td width="99%" class="displayEmailValue">' +
9878 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9879 '                                       </td>' +
9880 '                               </tr>' +
9881 '                               <tr>' +
9882 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9883 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9884 '                                       </td>' +
9885 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9886 '                                               <b>{email.name}</b>' +
9887 '                                       </td>' +
9888 '                               </tr>' +
9889 '                               <tr>' +
9890 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9891 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9892 '                                       </td>' +
9893 '                                       <td class="displayEmailValue">' +
9894 '                                               {email.date_start} {email.time_start}' +
9895 '                                       </td>' +
9896 '                               </tr>' +
9897 '                               <tr>' +
9898 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9899 '                                               {app_strings.LBL_EMAIL_TO}:' +
9900 '                                       </td>' +
9901 '                                       <td class="displayEmailValue">' +
9902 '                                               {email.toaddrs}' +
9903 '                                       </td>' +
9904 '                               </tr>' +
9905 '                               {email.cc}' +
9906 '                               {email.attachments}' +
9907 '                       </table>' +
9908 '               </td>' +
9909 '       </tr>' +
9910 '       <tr>' +
9911 '               <td>' +
9912 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9913 '                               <tr>' +
9914 '                                       <td style="border-top: 1px solid #333;">' +
9915 '                                               <div style="padding:5px;">' +
9916                                                         '{email.description}' +
9917 '                                               </div>' +
9918 '                                       </td>' +
9919 '                               </tr>' +
9920 '                       </table>' +
9921 '               </td>' +
9922 '       </tr>' +
9923 '</table>' +
9924 '</div>' +
9925 '</body></html>';
9926 // End of File modules/Emails/javascript/viewPrintable.js
9927                                 
9928 /*********************************************************************************
9929  * SugarCRM is a customer relationship management program developed by
9930  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9931  *
9932  * This program is free software; you can redistribute it and/or modify it under
9933  * the terms of the GNU Affero General Public License version 3 as published by the
9934  * Free Software Foundation with the addition of the following permission added
9935  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9936  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9937  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9938  *
9939  * This program is distributed in the hope that it will be useful, but WITHOUT
9940  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9941  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9942  * details.
9943  *
9944  * You should have received a copy of the GNU Affero General Public License along with
9945  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9946  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9947  * 02110-1301 USA.
9948  *
9949  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9950  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9951  *
9952  * The interactive user interfaces in modified source and object code versions
9953  * of this program must display Appropriate Legal Notices, as required under
9954  * Section 5 of the GNU Affero General Public License version 3.
9955  *
9956  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9957  * these Appropriate Legal Notices must retain the display of the "Powered by
9958  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9959  * technical reasons, the Appropriate Legal Notices must display the words
9960  * "Powered by SugarCRM".
9961  ********************************************************************************/
9962 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9963 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;}
9964 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');}
9965 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;}}
9966 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9967 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9968 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}
9969 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="";}}
9970 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
9971 {search.clearFields=function(){};search.setFields=function(data,filter)
9972 {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])
9973 {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';}}}}
9974 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))
9975 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
9976 {if(this.inputElement.id=='shipping_account_name')
9977 {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)/;}
9978 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
9979 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9980 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];}}}
9981 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]];}
9982 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;}}}}});}
9983 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9984 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js
9985