]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.2.2
[Github/sugarcrm.git] / include / javascript / sugar_grp_emails.js
1
2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
3
4 /**
5  * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6  * dragged element is inserted before the dragged-over element.
7  *
8  * @extends YAHOO.util.DDProxy
9  * @constructor
10  * @param {String} id the id of the linked element
11  * @param {String} sGroup the group of related DragDrop objects
12  */
13 function ygDDList(id, sGroup) {
14
15         if (id) {
16                 this.init(id, sGroup);
17                 this.initFrame();
18                 //this.logger = new ygLogger("ygDDList");
19         }
20
21         var s = this.getDragEl().style;
22         s.borderColor = "transparent";
23         s.backgroundColor = "#f6f5e5";
24         s.opacity = 0.76;
25         s.filter = "alpha(opacity=76)";
26 }
27
28 ygDDList.prototype = new YAHOO.util.DDProxy();
29
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
32
33 ygDDList.prototype.startDrag = function(x, y) {
34         //this.logger.debug(this.id + " startDrag");
35
36         var dragEl = this.getDragEl();
37         var clickEl = this.getEl();
38
39         dragEl.innerHTML = clickEl.innerHTML;
40         dragElObjects = dragEl.getElementsByTagName('object');
41
42         
43         dragEl.className = clickEl.className;
44         dragEl.style.color = clickEl.style.color;
45         dragEl.style.border = "1px solid #aaa";
46
47         // save the style of the object 
48         clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
49         
50         this.borderDiv = document.createElement('div'); // create a div to display border
51         this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52         this.borderDiv.style.border = '2px dashed #cccccc';
53         
54         for(i in clickEl.childNodes) { // hide contents of the target elements contents
55                 if(typeof clickEl.childNodes[i].style != 'undefined') {
56                         this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57                         clickEl.childNodes[i].style.display = 'none';
58                 }
59
60         }
61         clickEl.appendChild(this.borderDiv);
62 };
63
64 ygDDList.prototype.endDrag = function(e) {
65         // disable moving the linked element
66         var clickEl = this.getEl();
67
68         clickEl.removeChild(this.borderDiv); // remove border div
69         
70         for(i in clickEl.childNodes) { // show target elements contents
71                 if(typeof clickEl.childNodes[i].style != 'undefined') {
72                         clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
73                 }
74         }
75         
76         if(this.clickHeight) 
77             clickEl.style.height = this.clickHeight;
78         else 
79                 clickEl.style.height = '';
80         
81         if(this.clickBorder) 
82             clickEl.style.border = this.clickBorder;
83         else 
84                 clickEl.style.border = '';
85                 
86         dragEl = this.getDragEl();
87         dragEl.innerHTML = '';
88
89         this.afterEndDrag(e);
90 };
91
92 ygDDList.prototype.afterEndDrag = function(e) {
93
94 }
95
96 ygDDList.prototype.onDrag = function(e, id) {
97     
98 };
99
100 ygDDList.prototype.onDragOver = function(e, id) {
101         // this.logger.debug(this.id.toString() + " onDragOver " + id);
102         var el;
103         
104     if ("string" == typeof id) {
105         el = YAHOO.util.DDM.getElement(id);
106     } else { 
107         el = YAHOO.util.DDM.getBestMatch(id).getEl();
108     }
109     
110         dragEl = this.getDragEl();
111         elRegion = YAHOO.util.Dom.getRegion(el);
112             
113 //    this.logger.debug('id: ' + el.id);
114 //    this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 //    this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116         var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 //    this.logger.debug('mid: ' + mid);
118         
119 //    this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " <  " + mid);
120 //    this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
121         
122         if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123                 var el2 = this.getEl();
124                 var p = el.parentNode;
125                 p.insertBefore(el2, el);
126         }
127         if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128                 var el2 = this.getEl();
129                 var p = el.parentNode;
130                 p.insertBefore(el2, el.nextSibling);
131         }
132 };
133
134 ygDDList.prototype.onDragEnter = function(e, id) {
135         // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136         // this.getDragEl().style.border = "1px solid #449629";
137 };
138
139 ygDDList.prototype.onDragOut = function(e, id) {
140     // I need to know when we are over nothing
141         // this.getDragEl().style.border = "1px solid #964428";
142 }
143
144 /////////////////////////////////////////////////////////////////////////////
145
146 function ygDDListBoundary(id, sGroup) {
147         if (id) {
148                 this.init(id, sGroup);
149                 //this.logger = new ygLogger("ygDDListBoundary");
150                 this.isBoundary = true;
151         }
152 }
153
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
156                                 
157 /*********************************************************************************
158  * SugarCRM Community Edition is a customer relationship management program developed by
159  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
160  *
161  * This program is free software; you can redistribute it and/or modify it under
162  * the terms of the GNU Affero General Public License version 3 as published by the
163  * Free Software Foundation with the addition of the following permission added
164  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
167  *
168  * This program is distributed in the hope that it will be useful, but WITHOUT
169  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
171  * details.
172  *
173  * You should have received a copy of the GNU Affero General Public License along with
174  * this program; if not, see http://www.gnu.org/licenses or write to the Free
175  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
176  * 02110-1301 USA.
177  *
178  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
180  *
181  * The interactive user interfaces in modified source and object code versions
182  * of this program must display Appropriate Legal Notices, as required under
183  * Section 5 of the GNU Affero General Public License version 3.
184  *
185  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186  * these Appropriate Legal Notices must retain the display of the "Powered by
187  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188  * technical reasons, the Appropriate Legal Notices must display the words
189  * "Powered by SugarCRM".
190  ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span>&nbsp;</span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace('&#039;',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};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;})();
226 // End of File include/SugarEmailAddress/SugarEmailAddress.js
227                                 
228 /*********************************************************************************
229  * SugarCRM Community Edition is a customer relationship management program developed by
230  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
231  *
232  * This program is free software; you can redistribute it and/or modify it under
233  * the terms of the GNU Affero General Public License version 3 as published by the
234  * Free Software Foundation with the addition of the following permission added
235  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
236  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
237  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
238  *
239  * This program is distributed in the hope that it will be useful, but WITHOUT
240  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
241  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
242  * details.
243  *
244  * You should have received a copy of the GNU Affero General Public License along with
245  * this program; if not, see http://www.gnu.org/licenses or write to the Free
246  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
247  * 02110-1301 USA.
248  *
249  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
250  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
251  *
252  * The interactive user interfaces in modified source and object code versions
253  * of this program must display Appropriate Legal Notices, as required under
254  * Section 5 of the GNU Affero General Public License version 3.
255  *
256  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
257  * these Appropriate Legal Notices must retain the display of the "Powered by
258  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
259  * technical reasons, the Appropriate Legal Notices must display the words
260  * "Powered by SugarCRM".
261  ********************************************************************************/
262 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
263 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
264 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
265 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
266 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
267 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
268 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
269 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',100);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',100);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
270 this.js_more();this.js_more();}
271 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
272 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
273 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);}}}
274 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
275 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';}
276 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);}}
277 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);}}}
278 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++;}}}
279 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
280 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='';}}
281 arrow.value='show';}
282 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;}
283 break;}}
284 if(!has_primary){return false;}
285 return true;}
286 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);}}}
287 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;}}}}
288 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;}
289 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();}}}}
290 if(noAdd){enableQS(false);}
291 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);}}}
292 divCount++;}}
293 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
294 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=='';}
295 return false;}}
296 SUGAR.collection.safe_clone=function(e,recursive)
297 {if(e.nodeName=="#text")
298 {return document.createTextNode(e.data);}
299 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];if(SUGAR.isIE7&&e.tagName.toLowerCase()=='input')
300 {var properties=['class','style','name','type','valign','border','width','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}else{var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];}
301 for(var i in properties)
302 {if(e[properties[i]])
303 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
304 newNode[properties[i]]=e[properties[i]];}}
305 if(recursive)
306 {for(var i in e.childNodes)
307 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
308 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
309 return newNode;}}
310 // End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
311                                 
312 /*********************************************************************************
313  * SugarCRM Community Edition is a customer relationship management program developed by
314  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
315  *
316  * This program is free software; you can redistribute it and/or modify it under
317  * the terms of the GNU Affero General Public License version 3 as published by the
318  * Free Software Foundation with the addition of the following permission added
319  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
320  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
321  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
322  *
323  * This program is distributed in the hope that it will be useful, but WITHOUT
324  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
325  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
326  * details.
327  *
328  * You should have received a copy of the GNU Affero General Public License along with
329  * this program; if not, see http://www.gnu.org/licenses or write to the Free
330  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
331  * 02110-1301 USA.
332  *
333  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
334  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
335  *
336  * The interactive user interfaces in modified source and object code versions
337  * of this program must display Appropriate Legal Notices, as required under
338  * Section 5 of the GNU Affero General Public License version 3.
339  *
340  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
341  * these Appropriate Legal Notices must retain the display of the "Powered by
342  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
343  * technical reasons, the Appropriate Legal Notices must display the words
344  * "Powered by SugarCRM".
345  ********************************************************************************/
346 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);}
347 return s;},init:function(){if(Rot13.map!=null)
348 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
349 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
350 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
351 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='';}
352 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='';}
353 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='';}}
354 return words;}
355 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName,ie_id)
356 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
357 ie_id=(typeof document.getElementById(formName).ie_id!='undefined')?document.getElementById(formName).ie_id:'';URL='index.php?'
358 +'module='+module_name
359 +'&to_pdf=1'
360 +'&action='+action
361 +'&target='+pageTarget
362 +'&target1='+pageTarget
363 +'&server_url='+mail_server
364 +'&email_user='+words[0]
365 +'&protocol='+protocol
366 +'&port='+port
367 +'&email_password='+words[1]
368 +'&mailbox='+words[2]
369 +'&ssl='+ssl
370 +'&ie_id='+ie_id
371 +'&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)
372 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
373 this.body.style.width=w}}
374 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
375 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();}
376 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'));}
377 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
378 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
379 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
380 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
381 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";}
382 out+=errors[i];}
383 alert(out);return false;}else{return true;}}
384 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?'
385 +'module='+module_name
386 +'&to_pdf=1'
387 +'&action='+action
388 +'&target='+pageTarget
389 +'&target1='+pageTarget
390 +'&server_url='+mail_server
391 +'&email_user='+words[0]
392 +'&protocol='+protocol
393 +'&port='+port
394 +'&email_password='+words[1]
395 +'&mailbox='+words[2]
396 +'&ssl='+ssl
397 +'&personal='+isPersonal
398 +'&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)
399 this.body.style.width=w}}
400 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();}
401 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;}}}
402 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';}}}
403 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='';}
404 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";}}
405 // End of File modules/InboundEmail/InboundEmail.js
406                                 
407 /*********************************************************************************
408  * SugarCRM Community Edition is a customer relationship management program developed by
409  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
410  * 
411  * This program is free software; you can redistribute it and/or modify it under
412  * the terms of the GNU Affero General Public License version 3 as published by the
413  * Free Software Foundation with the addition of the following permission added
414  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
415  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
416  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
417  * 
418  * This program is distributed in the hope that it will be useful, but WITHOUT
419  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
420  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
421  * details.
422  * 
423  * You should have received a copy of the GNU Affero General Public License along with
424  * this program; if not, see http://www.gnu.org/licenses or write to the Free
425  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
426  * 02110-1301 USA.
427  * 
428  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
429  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
430  * 
431  * The interactive user interfaces in modified source and object code versions
432  * of this program must display Appropriate Legal Notices, as required under
433  * Section 5 of the GNU Affero General Public License version 3.
434  * 
435  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
436  * these Appropriate Legal Notices must retain the display of the "Powered by
437  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
438  * technical reasons, the Appropriate Legal Notices must display the words
439  * "Powered by SugarCRM".
440  ********************************************************************************/
441
442 SUGAR.email2 = {
443     cache : new Object(),
444     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
445     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
446     templates : {},
447     tinyInstances : {
448         currentHtmleditor : ''
449     },
450
451     /**
452      * preserves hits from email server
453      */ 
454     _setDetailCache : function(ret) {
455         if(ret.meta) {
456             var compKey = ret.meta.mbox + ret.meta.uid;
457
458             if(!SUGAR.email2.cache[compKey]) {
459                 SUGAR.email2.cache[compKey] = ret;
460             }
461         }
462     },
463
464     autoSetLayout : function() {
465         var c = document.getElementById('container');
466         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
467         //Ensure a minimum height.
468         tHeight = Math.max(tHeight, 550);
469         c.style.height = tHeight + "px";
470         SUGAR.email2.complexLayout.set('height', tHeight);
471         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
472         SUGAR.email2.complexLayout.render();
473         SUGAR.email2.listViewLayout.resizePreview();        
474     }
475 };
476
477 /**
478  * Shows overlay progress message
479  */
480 function overlayModal(title, body) {
481     overlay(title, body);
482 }
483 function overlay(reqtitle, body, type, additconfig) {
484     var config = { };
485     if (typeof(additconfig) == "object") {
486         var config = additconfig;
487     }
488     config.type = type;
489     config.title = reqtitle;
490     config.msg = body;
491     YAHOO.SUGAR.MessageBox.show(config);
492 };
493
494 function hideOverlay() {
495         YAHOO.SUGAR.MessageBox.hide();
496 };
497 // End of File modules/Emails/javascript/EmailUIShared.js
498                                 
499 /*********************************************************************************
500  * SugarCRM Community Edition is a customer relationship management program developed by
501  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
502  * 
503  * This program is free software; you can redistribute it and/or modify it under
504  * the terms of the GNU Affero General Public License version 3 as published by the
505  * Free Software Foundation with the addition of the following permission added
506  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
507  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
508  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
509  * 
510  * This program is distributed in the hope that it will be useful, but WITHOUT
511  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
512  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
513  * details.
514  * 
515  * You should have received a copy of the GNU Affero General Public License along with
516  * this program; if not, see http://www.gnu.org/licenses or write to the Free
517  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
518  * 02110-1301 USA.
519  * 
520  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
521  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
522  * 
523  * The interactive user interfaces in modified source and object code versions
524  * of this program must display Appropriate Legal Notices, as required under
525  * Section 5 of the GNU Affero General Public License version 3.
526  * 
527  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
528  * these Appropriate Legal Notices must retain the display of the "Powered by
529  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
530  * technical reasons, the Appropriate Legal Notices must display the words
531  * "Powered by SugarCRM".
532  ********************************************************************************/
533
534
535 (function() {
536         var sw = YAHOO.SUGAR,
537                 Event = YAHOO.util.Event,
538                 Connect = YAHOO.util.Connect,
539             Dom = YAHOO.util.Dom
540             SE = SUGAR.email2;
541
542 ///////////////////////////////////////////////////////////////////////////////
543 ////    EMAIL ACCOUNTS
544 SE.accounts = {
545     outboundDialog : null,
546     inboundAccountEditDialog : null,
547     inboundAccountsSettingsTable : null,
548     outboundAccountsSettingsTable : null,
549     testOutboundDialog : null,
550     errorStyle : 'input-error',
551     normalStyle : '',
552     newAddedOutboundId : '',
553
554     /**
555      * makes async call to retrieve an outbound instance for editting
556      */
557      //EXT111
558     editOutbound : function(obi) {
559
560             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
561
562     },
563     deleteOutbound : function(obi) {
564
565         if(obi.match(/^(add|line|sendmail)+/)) {
566             alert('Invalid Operation');
567         } else {
568                 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
569             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
570         }
571     },
572     //EXT111
573     getReplyAddress : function() {
574         var primary = '';
575
576         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
577             var addy = SE.userPrefs.current_user.emailAddresses[i];
578
579             if(addy.primary_address == "1") {
580                 primary = addy.email_address;
581             }
582
583             if(addy.reply_to == "1") {
584                 return addy.email_address;
585             }
586         }
587
588         return primary;
589     },
590
591     /**
592      * Called on "Accounts" tab activation event
593      */
594     lazyLoad : function() {
595
596         this._setupInboundAccountTable();
597         this._setupOutboundAccountTable();
598
599     },
600
601     _setupInboundAccountTable: function()
602     {
603         //Setup the inbound mail settings
604         if(!this.inboundAccountsSettingsTable)
605         {
606                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
607                                         var clckEvent = oColumn.key;
608                                         var imgSrc = "";
609                                         var is_group = oRecord.getData("is_group");
610                                         if(!is_group)
611                                         {
612                                         if(oColumn.key == 'edit')
613                                         {
614                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
615                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
616                                         }
617                                         else if(oColumn.key == 'delete')
618                                         {
619                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
620                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
621                                         }
622                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
623                                         }
624                    };
625
626                    this.showBoolean = function(el, oRecord, oColumn, oData)
627                    {
628                        var is_group = oRecord.getData("is_group");
629                        var bChecked = oData;
630                        bChecked = (bChecked) ? " checked" : "";
631                        if(!is_group)
632                        {
633                        el.innerHTML = "<input type=\"radio\"" + bChecked +
634                            " name=\"col" + oColumn.getId() + "-radio\"" +
635                            " class=\"yui-dt-radio\">";
636                        }
637                    };
638
639
640                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
641                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
642
643                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
644                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
645                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
646
647
648                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
649                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
650                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
651                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
652                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
653                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
654                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
655                 this.ieDataSource = new YAHOO.util.DataSource(query);
656                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
657                         this.ieDataSource.responseSchema = {
658                                 resultsList: "account_list",
659                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
660                         };
661                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
662                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
663
664                     var elCheckbox = oArgs.target;
665                     var oColumn = this.getColumn(elCheckbox);
666                         if(oColumn.key == 'is_active')
667                         {
668                                 var oRecord = this.getRecord(elCheckbox);
669                                 oRecord.setData("is_active",elCheckbox.checked);
670                                 var t_id = oRecord.getData('id');
671                         var isGroupFolder = oRecord.getData('has_groupfolder');
672
673                         if(isGroupFolder)
674                             SUGAR.email2.folders.updateSubscriptions();
675                         else
676                         SUGAR.email2.folders.setFolderSelection();
677
678                         }
679                 });
680                         var lastDefaultSelectedId = "";
681                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
682
683                     var elRadio = oArgs.target;
684                     var oColumn = this.getColumn(elRadio);
685                         if(oColumn.key == 'is_default')
686                         {
687                                 var oRecord = this.getRecord(elRadio);
688                                 var t_id = oRecord.getData('id');
689                                 var t_isGroup = oRecord.getData('is_group');
690                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
691                                 {
692                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
693                                         lastDefaultSelectedId = t_id;
694                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
695                                 }
696                                 else if(t_isGroup)
697                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
698
699                         }
700                 });
701
702                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
703                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
704         }
705     },
706      _setupOutboundAccountTable: function()
707     {
708         if(!this.outboundAccountsSettingsTable)
709         {
710                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
711                                         var clckEvent = oColumn.key;
712                                         var imgSrc = "";
713                                         var isEditable = oRecord.getData("is_editable");
714                                         var type = oRecord.getData("type");
715                                         if(isEditable)
716                                         {
717                                         if(oColumn.key == 'edit')
718                                         {
719                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
720                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
721                                         }
722                                         else if(oColumn.key == 'delete' && type == 'user')
723                                         {
724                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
725                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
726                                         }
727                                         if(imgSrc != '')
728                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
729                                         }
730                 };
731
732                 //Custom formatter to display any error messages.
733                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
734
735                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
736                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
737
738                         var id = oRecord.getData('id');
739                                         var message = oRecord.getData("errors");
740                                         if(message != '')
741                                         {
742                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
743                                         //Add the id and message for all outbound accounts.
744                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
745                                         }
746                                         else
747                                         {
748                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
749                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
750                                         }
751                 };
752                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
753                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
754
755                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
756                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
757                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
758                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
759
760                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
761                 this.obDataSource = new YAHOO.util.DataSource(query);
762                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
763                         this.obDataSource.responseSchema = {
764
765                                 resultsList: "outbound_account_list",
766                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
767                         };
768
769                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
770
771
772                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
773                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
774                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
775         }
776     },
777     /**
778      * Displays a modal diaglogue to edit outbound account settings
779      */
780     showEditInboundAccountDialogue : function(clear) {
781
782         if(!this.inboundAccountEditDialog) {
783                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
784                 modal:true,
785                                 visible:true,
786                 fixedcenter:true,
787                 constraintoviewport: true,
788                 width   : "600px",
789                 shadow  : true
790             });
791                         EAD.showEvent.subscribe(function() {
792                 var el = this.element;
793                 var viewH = YAHOO.util.Dom.getViewportHeight();
794                 if (this.header && el && viewH - 50 < el.clientHeight) {
795                     var body = this.header.nextElementSibling;
796                                         body.style.overflow = "hidden";
797                     body.style.height = "100%";
798                 }
799             }, EAD);
800             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
801                         Dom.removeClass("editAccountDialogue", "yui-hidden");
802
803         } // end lazy load
804
805         if(clear == undefined || clear == true)
806         {
807                 SE.accounts.clearInboundAccountEditScreen();
808                 //Set default protocol to IMAP when creating new records
809                 document.forms['ieAccount'].elements['protocol'].value = "imap";
810                 SE.accounts.setPortDefault();
811         }
812
813         //Check if we should display username/password fields for outbound account if errors were detected.
814         this.checkOutBoundSelection();
815
816         this.inboundAccountEditDialog.render();
817         this.inboundAccountEditDialog.show();
818         SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
819     },
820
821     /**
822     *  Set all fields on the outbound edit form to either enabled/disabled
823     *  except for the username/password.
824     *
825     */
826     toggleOutboundAccountDisabledFields: function(disable)
827     {
828         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
829         for(var i=0;i<fields.length;i++)
830         {
831             document.getElementById(fields[i]).disabled = disable;
832         }
833         if(disable)
834             Dom.addClass("mail_smtpssl_row", "yui-hidden");
835         else
836             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
837
838     },
839     /**
840     * Refresh the inbound accounts table.
841     */
842     refreshInboundAccountTable : function()
843     {
844             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
845                 {
846                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
847                                 scope: this.inboundAccountsSettingsTable }
848                         );
849     },
850     /**
851     * Refresh the outbound accounts table.
852     */
853     refreshOuboundAccountTable : function()
854     {
855             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
856                 {
857                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
858                                 scope: this.outboundAccountsSettingsTable }
859                         );
860     },
861     /**
862      * Displays a modal diaglogue to add a SMTP server
863      */
864     showAddSmtp : function() {
865         // lazy load dialogue
866         if(!this.outboundDialog) {
867                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
868                 modal:true,
869                                 visible:true,
870                 fixedcenter:true,
871                 constraintoviewport: true,
872                 width   : "750px",
873                 shadow  : true
874             });
875             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
876             this.outboundDialog.hideEvent.subscribe(function(){
877                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
878                 var out = Dom.get("outbound_email");
879                 if (out && out.value == "SYSTEM_ADD")
880                 {
881                         out.value = out.options[0].value;
882                 }
883                 //Check if we should display username/password for system account.
884                 SE.accounts.checkOutBoundSelection();
885                 return true;
886             });
887
888             Dom.removeClass("outboundDialog", "yui-hidden");
889         } // end lazy load
890
891         // clear out form
892         var form = document.getElementById('outboundEmailForm');
893         for(i=0; i<form.elements.length; i++) {
894             if(form.elements[i].name == 'mail_smtpport') {
895                 form.elements[i].value = 25;
896             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
897                 form.elements[i].value = '';
898             } else if(form.elements[i].type == 'checkbox') {
899                 form.elements[i].checked = false;
900             }
901         }
902         //Render the SMTP buttons
903         if ( !SUGAR.smtpButtonGroup ) {
904             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
905             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
906             {
907                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
908                 document.getElementById('smtp_settings').style.display = '';
909                 form.mail_smtptype.value = e.newValue.get('value');
910             });
911             YAHOO.widget.Button.addHiddenFieldsToForm(form);
912         }
913         //Hide Username/Password
914         SUGAR.email2.accounts.smtp_authenticate_field_display();
915         //Unset readonly fields
916         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
917         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
918                 this.outboundDialog.render();
919         this.outboundDialog.show();
920     },
921
922     /**
923      * Accounts' Advanced Settings view toggle
924      */
925     toggleAdv : function() {
926         var adv = document.getElementById("ie_adv");
927         if(adv.style.display == 'none') {
928             adv.style.display = "";
929         } else {
930             adv.style.display = 'none';
931         }
932     },
933
934         smtp_authenticate_field_display : function() {
935                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
936                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
937                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
938         },
939         
940         smtp_setDefaultSMTPPort : function() {
941                 useSSLPort = !document.getElementById("mail_smtpssl").options[0].selected;
942     
943         if ( useSSLPort && document.getElementById("mail_smtpport").value == '25' ) {
944             document.getElementById("mail_smtpport").value = '465';
945         }
946         if ( !useSSLPort && document.getElementById("mail_smtpport").value == '465' ) {
947             document.getElementById("mail_smtpport").value = '25';
948         }
949         },
950
951     /**
952      * Changes the display used in the outbound email SMTP dialog to match the
953      */
954     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
955     {
956         document.getElementById("smtpButtonGroupTD").style.display = '';
957         document.getElementById("chooseEmailProviderTD").style.display = '';
958         document.getElementById("mailsettings1").style.display = '';
959         document.getElementById("mailsettings2").style.display = '';
960         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
961         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
962         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
963         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
964
965         switch (smtptype) {
966         case "yahoomail":
967             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
968             document.getElementById("mail_smtpport").value = '465';
969             document.getElementById("mail_smtpauth_req").checked = true;
970             var ssl = document.getElementById("mail_smtpssl");
971             for(var j=0;j<ssl.options.length;j++) {
972                 if(ssl.options[j].text == 'SSL') {
973                     ssl.options[j].selected = true;
974                     break;
975                 }
976             }
977             document.getElementById("mailsettings1").style.display = 'none';
978             document.getElementById("mailsettings2").style.display = 'none';
979             document.getElementById("mail_smtppass_label").innerHTML =
980             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
981             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
982             break;
983         case "gmail":
984             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
985             document.getElementById("mail_smtpport").value = '587';
986             document.getElementById("mail_smtpauth_req").checked = true;
987             var ssl = document.getElementById("mail_smtpssl");
988             for(var j=0;j<ssl.options.length;j++) {
989                 if(ssl.options[j].text == 'TLS') {
990                     ssl.options[j].selected = true;
991                     break;
992                 }
993             }
994             document.getElementById("mailsettings1").style.display = 'none';
995             document.getElementById("mailsettings2").style.display = 'none';
996             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
997             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
998             break;
999         case "exchange":
1000             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
1001                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
1002                 document.getElementById("mail_smtpserver").value = '';
1003             }
1004             document.getElementById("mail_smtpport").value = '25';
1005             document.getElementById("mail_smtpauth_req").checked = true;
1006             document.getElementById("mailsettings1").style.display = '';
1007             document.getElementById("mailsettings2").style.display = '';
1008             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
1009             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
1010             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
1011             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
1012             break;
1013         }
1014         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
1015         {
1016             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1017             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1018             document.getElementById("mailsettings2").style.display = 'none';
1019         }
1020
1021         SUGAR.email2.accounts.smtp_authenticate_field_display();
1022         SUGAR.email2.accounts.smtp_setDefaultSMTPPort()
1023     },
1024
1025     /**
1026     * Fill the gmail default values for inbound accounts.
1027     */
1028     fillInboundGmailDefaults: function () {
1029
1030         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1031         document.forms['ieAccount'].elements['ssl'].checked = true;
1032         document.forms['ieAccount'].elements['protocol'].value = "imap";
1033         SUGAR.email2.accounts.setPortDefault();
1034         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1035     },
1036     /**
1037      * Sets Port field to selected protocol and SSL settings defaults
1038      */
1039     setPortDefault : function() {
1040         var prot = document.getElementById('protocol');
1041         var ssl  = document.getElementById('ssl');
1042         var port = document.getElementById('port');
1043         var stdPorts= new Array("110", "143", "993", "995");
1044         var stdBool    = new Boolean(false);
1045         var mailboxdiv = document.getElementById("mailboxdiv");
1046         var trashFolderdiv = document.getElementById("trashFolderdiv");
1047         var sentFolderdiv = document.getElementById("sentFolderdiv");
1048                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1049         if(port.value == '') {
1050             stdBool.value = true;
1051         } else {
1052             for(i=0; i<stdPorts.length; i++) {
1053                 if(stdPorts[i] == port.value) {
1054                     stdBool.value = true;
1055                 }
1056             }
1057         }
1058
1059         if(stdBool.value == true) {
1060             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1061                 port.value = "143";
1062             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1063                 port.value = '993';
1064             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1065                 port.value = '110';
1066             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1067                 port.value = '995';
1068             }
1069         }
1070
1071         if (prot.value == 'imap') {
1072                 mailboxdiv.style.display = "";
1073                 trashFolderdiv.style.display = "";
1074                 sentFolderdiv.style.display = "";
1075                 monitoredFolder.style.display = "";
1076                 if (document.getElementById('mailbox').value == "") {
1077                         document.getElementById('mailbox').value = "INBOX";
1078                 }
1079         } else {
1080                 mailboxdiv.style.display = "none";
1081                 trashFolderdiv.style.display = "none";
1082                 sentFolderdiv.style.display = "none";
1083                         monitoredFolder.style.display = "none";
1084                 document.getElementById('mailbox').value = "";
1085         } // else
1086     },
1087
1088     /**
1089      * Draws/removes red boxes around required fields.
1090      */
1091     ieAccountError : function(style) {
1092         document.getElementById('server_url').className = style;
1093         document.getElementById('email_user').className = style;
1094         document.getElementById('email_password').className = style;
1095         document.getElementById('protocol').className = style;
1096         document.getElementById('port').className = style;
1097     },
1098
1099     checkOutBoundSelection: function() {
1100         var select = Dom.get('outbound_email');
1101         if (!select || select.selectedIndex == -1) { return; }
1102
1103         var v = select.options[select.selectedIndex].value;
1104
1105         if(v == '')
1106         {
1107                 select.options[select.selectedIndex].selected = false;
1108                 v = select.options[0].value;
1109         }
1110         else if (v == 'SYSTEM_ADD')
1111                 SUGAR.email2.accounts.showAddSmtp();
1112
1113         var foundError = false;
1114         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1115                 for(i in errorAccounts)
1116                 {
1117                     if(v == i)
1118                     {
1119                         foundError = true;
1120                         break;
1121                     }
1122                 }
1123
1124                 //Should username/password fields for outbound account.
1125                 if(foundError)
1126                     this.toggleInboundOutboundFields(true);
1127                 else
1128                     this.toggleInboundOutboundFields(false);
1129
1130
1131
1132     },
1133     toggleInboundOutboundFields : function (display)
1134     {
1135         if(display)
1136         {
1137             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1138                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1139         }
1140         else
1141         {
1142             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1143                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1144         }
1145     },
1146     /**
1147      * rebuilds the select options for mailer options
1148      */
1149     rebuildMailerOptions : function() {
1150         var select = document.forms['ieAccount'].elements['outbound_email'];
1151         SE.util.emptySelectOptions(select);
1152
1153         //Get the available sugar mailers
1154         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1155
1156         for(i=0;i<a_outbound.length;i++)
1157         {
1158                 var t_record = a_outbound[i];
1159                 var key = t_record.getData('id');
1160                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1161
1162                 var opt = new Option(display, key);
1163                 select.options.add(opt);
1164                 if (key == SE.accounts.newAddedOutboundId) {
1165                         select.options.selectedIndex = i;
1166                 }
1167         }
1168
1169         select.options.add(new Option('',''));
1170         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1171         //Hide/Show username password fields if necessary.
1172         SE.accounts.checkOutBoundSelection();
1173     },
1174     /**
1175      * Empties all the fields in the accounts edit view
1176      */
1177     clearInboundAccountEditScreen:function() {
1178
1179         document.getElementById('ie_id').value = '';
1180         document.getElementById('ie_name').value = '';
1181         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1182         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1183         document.getElementById('reply_to_addr').value = '';
1184         document.getElementById('server_url').value = '';
1185         document.getElementById('email_user').value = '';
1186         document.getElementById('email_password').value = '';
1187         document.getElementById('port').value = '';
1188         document.getElementById('inbound_mail_smtpuser').value = '';
1189         document.getElementById('inbound_mail_smtppass').value = '';
1190         document.ieAccount.protocol.options[0].selected = true;
1191         // handle SSL
1192         document.getElementById('ssl').checked = false;
1193         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1194     },
1195
1196     /**
1197      * Populates an account's fields in Settings->Accounts
1198      */
1199     fillIeAccount:function(jsonstr) {
1200         var o = YAHOO.lang.JSON.parse(jsonstr);
1201
1202         document.getElementById('ie_id').value = o.id;
1203         document.getElementById('ie_name').value = o.name;
1204         if (o.stored_options != null) {
1205                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1206                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1207                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1208                 if (o.stored_options.trashFolder != null) {
1209                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1210                 }
1211                 if (o.stored_options.sentFolder != null) {
1212                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1213                 }
1214         }
1215         document.getElementById('server_url').value = o.server_url;
1216         document.getElementById('email_user').value = o.email_user;
1217         document.getElementById('port').value = o.port;
1218         document.getElementById('group_id').value = o.group_id;
1219         document.getElementById('mailbox').value = o.mailbox;
1220
1221
1222         var i = 0;
1223
1224         // handle SSL
1225         if(typeof(o.service[2]) != 'undefined') {
1226             document.getElementById('ssl').checked = true;
1227         }
1228
1229         // handle protocol
1230         if(document.getElementById('protocol').value != o.protocol) {
1231             var prot = document.getElementById('protocol');
1232             for(i=0; i<prot.options.length; i++) {
1233                 if(prot.options[i].value == o.service[3]) {
1234                     prot.options[i].selected = true;
1235                     this.setPortDefault();
1236                 }
1237             }
1238         }
1239  // handle SMTP selection
1240         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1241             var opts = document.getElementById('outbound_email').options;
1242             for(i=0; i<opts.length; i++) {
1243                 if(opts[i].value == o.stored_options.outbound_email) {
1244                     opts[i].selected = true;
1245                 }
1246             }
1247         }
1248     },
1249
1250     deleteIeAccount : function(IeAccountID,IeGroupID) {
1251         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1252         {
1253             overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1254
1255             AjaxObject.target = 'frameFlex';
1256             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1257             SUGAR.email2.accounts.refreshInboundAccountTable();
1258          }
1259      },
1260
1261        // Null check for Outbound Settings.
1262     checkOutboundSettings: function() {
1263         var errorMessage = '';
1264         var isError = false;
1265         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1266             var mailName = document.getElementById('mail_name').value;
1267             var smtpServer = document.getElementById('mail_smtpserver').value;
1268             var smtpPort = document.getElementById('mail_smtpport').value;
1269
1270             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1271             if(trim(mailName) == '') {
1272                 isError = true;
1273                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1274             }
1275             if(trim(smtpServer) == '') {
1276                 isError = true;
1277                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1278             }
1279             if(trim(smtpPort) == '') {
1280                 isError = true;
1281                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1282             }
1283             if(mailsmtpauthreq.checked) {
1284                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1285                     isError = true;
1286                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1287                 }
1288             }
1289         }
1290         if(isError) {
1291             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1292             return false;
1293         } else {
1294             return true;
1295         }
1296     },
1297
1298     testOutboundSettings: function() {
1299         var errorMessage = '';
1300         var isError = false;
1301         var fromAddress = document.getElementById("outboundtest_from_address").value;
1302         if (trim(fromAddress) == "") {
1303             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1304             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1305             return false;
1306
1307         }
1308         else if (!isValidEmail(fromAddress)) {
1309             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1310             overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1311             return false;
1312         }
1313
1314         //Hide the dialogue and show an in progress indicator.
1315         SE.accounts.testOutboundDialog.hide();
1316         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1317
1318         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1319         //nothing is sent in the request.
1320         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1321         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1322
1323         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1324         if(outboundType == 'system-override')
1325             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1326
1327         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1328         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1329
1330     },
1331
1332     testOutboundSettingsDialog: function() {
1333         //Ensure that all settings are correct before proceeding to send test email.
1334         if(!SE.accounts.checkOutboundSettings())
1335             return;
1336
1337         // lazy load dialogue
1338         if(!SE.accounts.testOutboundDialog) {
1339                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1340                 modal:true,
1341                                 visible:true,
1342                 fixedcenter:true,
1343                 constraintoviewport: true,
1344                 width   : 600,
1345                 shadow  : true
1346             });
1347             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1348             Dom.removeClass("testOutboundDialog", "yui-hidden");
1349         } // end lazy load
1350         SE.accounts.testOutboundDialog.render();
1351         SE.accounts.testOutboundDialog.show();
1352     },
1353
1354     /**
1355      * Saves Outbound email settings
1356      */
1357     saveOutboundSettings : function() {
1358         if(SE.accounts.checkOutboundSettings()) {
1359             //Enable the form fields for the post.
1360             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1361             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1362             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1363         } else {
1364             return false;
1365         }
1366     },
1367
1368     saveIeAccount : function() {
1369
1370         //Before saving check if there are any error messages associated with the outbound account.
1371         var outboundID = document.getElementById('outbound_email').value;
1372
1373         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1374             'validateSMTPCreds':true}) )
1375         {
1376             document.getElementById('saveButton').disabled = true;
1377
1378             overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1379
1380             var formObject = document.getElementById('ieAccount');
1381             YAHOO.util.Connect.setForm(formObject);
1382
1383             AjaxObject._reset();
1384             AjaxObject.target = 'frameFlex';
1385             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1386         }
1387     },
1388
1389     testSettings : function() {
1390         form = document.getElementById('ieAccount');
1391
1392         if(SE.accounts.checkIeCreds()) {
1393             ie_test_open_popup_with_submit("InboundEmail", "Popup", "Popup", 400, 300, trim(form.server_url.value), form.protocol.value, trim(form.port.value), trim(form.email_user.value), Rot13.write(form.email_password.value), trim(form.mailbox.value), form.ssl.checked, true, "ieAccount", form.ie_id.value);
1394         }
1395     },
1396
1397     getFoldersListForInboundAccountForEmail2 : function() {
1398         form = document.getElementById('ieAccount');
1399         if(SE.accounts.checkIeCreds()) {
1400                 var mailBoxValue = form.mailbox.value;
1401                 if (form.searchField.value.length > 0) {
1402                         mailBoxValue = "";
1403                 } // if
1404             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 );
1405         } // if
1406
1407     },
1408
1409     checkIeCreds : function(validateRules) {
1410         if(typeof(validateRules) == 'undefined')
1411             validateRules = {};
1412
1413         var errors = new Array();
1414         var out = new String();
1415
1416         var ie_name = Dom.get('ie_name').value;
1417         var fromAddress = Dom.get('ie_from_addr').value;
1418         var server_url = Dom.get('server_url').value;
1419         var email_user = Dom.get('email_user').value;
1420         var email_password = Dom.get('email_password').value;
1421         var protocol = Dom.get('protocol').value;
1422         var port = Dom.get('port').value;
1423         var oe = Dom.get('outbound_email');
1424
1425         // Bug 44392: IE9 and possibly previous versions have a quirk where selectedIndex is -1 if you have nothing selected vs 0 for
1426         // other browsers. And if you check options[-1] it returns "unknown" instead of undefined. Also other options out of index
1427         // return null instead of undefined for other browsers, thus we need to check for all the possible outcomes.
1428         var oe_value = (typeof(oe.options[oe.selectedIndex]) === 'undefined' || typeof(oe.options[oe.selectedIndex]) === 'unknown' || typeof(oe.options[oe.selectedIndex]) === null) ? "" : oe.options[oe.selectedIndex].value;
1429
1430         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1431         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1432
1433         //If the username and password were provided then ignore the error messge
1434
1435         var outboundCredentialsFound = false;
1436
1437         if(outboundUserName != "" && outboundPass != "")
1438             outboundCredentialsFound = true;
1439
1440         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1441
1442         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1443              && validateSMTPCreds)
1444         {
1445             if(trim(outboundUserName) == "") {
1446                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1447             }
1448             if(trim(outboundPass) == "") {
1449                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1450             }
1451         }
1452
1453         if(trim(ie_name) == "") {
1454             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1455         }
1456
1457         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1458         {
1459             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1460                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1461             }
1462         }
1463
1464
1465         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1466              || trim(oe_value) == "SYSTEM_ADD") ) {
1467             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1468         }
1469         if(trim(server_url) == "") {
1470             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1471         }
1472         if(trim(email_user) == "") {
1473             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1474         }
1475         if(protocol == "") {
1476             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1477         }
1478         if (protocol == 'imap') {
1479                 var mailbox = document.getElementById('mailbox').value;
1480                 if (trim(mailbox) == "") {
1481                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1482                 } // if
1483                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1484                         var trashFolder = document.getElementById('trashFolder').value;
1485                         if (trim(trashFolder) == "") {
1486                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1487                         } // if
1488                         } // if
1489         }
1490         if(port == "") {
1491             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1492         }
1493
1494         if(errors.length > 0) {
1495             out = app_strings.LBL_EMAIL_ERROR_DESC;
1496             for(i=0; i<errors.length; i++) {
1497                 if(out != "") {
1498                     out += "\n";
1499                 }
1500                 out += errors[i];
1501             }
1502
1503             alert(out);
1504             return false;
1505         } else {
1506
1507             return true;
1508         }
1509     },
1510
1511     getIeAccount : function(ieId) {
1512         if(ieId == '')
1513             return;
1514
1515         overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1516                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1517
1518         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1519     },
1520
1521     /**
1522      * Iterates through TreeView nodes to apply styles dependent nature of node
1523      */
1524     renderTree:function() {
1525         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1526         SE.tree.render();
1527     },
1528
1529     //Sets the style for any nodes that need it.
1530     setNodeStyle : function(node) {
1531         if (!node.data.origText) {
1532             node.data.origText = node.data.text;
1533         }
1534         //Set unread
1535         if (typeof(node.data.unseen) != 'undefined') {
1536                 if (node.data.unseen > 0) {
1537                                 node.setUpLabel(node.data.origText + '(' + node.data.unseen + ')');
1538                 // Add bold style to label, kinda hacky
1539                 node.labelStyle += " ygtvlabelbold";
1540                         }
1541                         else {
1542                                 node.setUpLabel(node.data.origText);
1543                         }
1544         } else {
1545                 node.setUpLabel(node.data.origText);
1546         }
1547         SE.accounts.setupDDTarget(node);
1548     },
1549
1550     setupDDTarget : function(node) {
1551         if (node.ddTarget) {
1552                 node.ddTarget.removeFromGroup();
1553                 delete node.ddTarget;
1554         }
1555         var id = node.getElId();
1556         var num = id.substring(4);
1557         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1558                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1559                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1560
1561                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1562         }
1563         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1564                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1565         }
1566     },
1567
1568     /**
1569      * Async call to rebuild the folder list.  After a folder delete or account delete
1570      */
1571     rebuildFolderList : function() {
1572         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1573         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1574     },
1575
1576     /**
1577      * Returns the number of remote accounts the user has active.
1578      */
1579     getAccountCount : function() {
1580         var tree = SE.tree;
1581         var count = 0;
1582         for(i=0; i<tree._nodes.length; i++) {
1583             var node = tree._nodes[i];
1584
1585             if(typeof(node) != 'undefined' && node.data.ieId) {
1586                 count++;
1587             }
1588         }
1589         return count;
1590     }
1591 };
1592 ////    END ACCOUNTS
1593 ///////////////////////////////////////////////////////////////////////////////
1594
1595
1596
1597
1598 ///////////////////////////////////////////////////////////////////////////////
1599 ////    CONTEXT MENU CALLS
1600 SE.contextMenus = {
1601
1602     assignToDialogue : null,
1603     /**
1604      * Archives from context menu
1605      * @param Array uids
1606      * @param string ieId
1607      * @param string folder
1608      */
1609     _archiveToSugar : function(uids, ieId, folder) {
1610         var ser = '';
1611
1612         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1613             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1614             ser += uids[i];
1615         }
1616         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1617     },
1618
1619     /**
1620      * Archives from context menu
1621      */
1622     archiveToSugar : function(menuItem) {
1623         SE.contextMenus.emailListContextMenu.hide();
1624
1625         var rows = SE.grid.getSelectedRows();
1626         var uids = [];
1627         /* iterate through available rows JIC a row is deleted - use first available */
1628         for(var i=0; i<rows.length; i++) {
1629             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1630         }
1631         var data = SE.grid.getRecord(rows[0]).getData();
1632         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1633     },
1634
1635     /**
1636      * Popup the printable version and start system's print function.
1637      */
1638     viewPrintable : function(menuItem) {
1639         var rows = SE.grid.getSelectedRows();
1640         var data = SE.grid.getRecord(rows[0]).getData();
1641         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1642     },
1643
1644     /**
1645      * Marks email flagged on mail server
1646      */
1647     markRead : function(type, contextMenuId) {
1648         SE.contextMenus.markEmail('read');
1649     },
1650
1651     /**
1652      * Assign this emails to people based on assignment rules
1653      */
1654     assignEmailsTo : function(type, contextMenuId) {
1655         if(!SE.contextMenus.assignToDialogue)
1656         {
1657                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1658                 modal:true,
1659                                 visible:false,
1660                 fixedcenter:true,
1661                 constraintoviewport: true,
1662                 width   : "600px",
1663                 shadow  : true
1664             });
1665             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1666             enableQS(true);
1667         }
1668
1669         Dom.removeClass("assignToDiv", "yui-hidden");
1670         SE.contextMenus.assignToDialogue.render();
1671         SE.contextMenus.assignToDialogue.show();
1672     },
1673
1674     /**
1675      * Marks email flagged on mail server
1676      */
1677     markFlagged : function(contextMenuId) {
1678         SE.contextMenus.markEmail('flagged');
1679     },
1680
1681     /**
1682      * Marks email unflagged on mail server
1683      */
1684     markUnflagged : function(contextMenuId) {
1685         SE.contextMenus.markEmail('unflagged');
1686     },
1687
1688     /**
1689      * Marks email unread on mail server
1690      */
1691     markUnread : function() {
1692         SE.contextMenus.markEmail('unread');
1693     },
1694
1695     /**
1696      * Deletes an email from context menu
1697      */
1698     markDeleted : function() {
1699         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1700                 document.getElementById('_blank').innerHTML = "";
1701                 SE.contextMenus.markEmail('deleted');
1702         }
1703     },
1704
1705     /**
1706      * generic call API to apply a flag to emails on the server and on sugar
1707      * @param string type "read" | "unread" | "flagged" | "deleted"
1708      */
1709     markEmail : function(type) {
1710         SE.contextMenus.emailListContextMenu.hide();
1711
1712         //var dm = SE.grid.getStore();
1713         //var uids = SE.grid.getSelectedRowIds();
1714         //var indexes = SE.grid.getSelectedRowIndexes();
1715         var rows = SE.grid.getSelectedRows();
1716         if (rows.length == 0)
1717                 rows = [SE.contextMenus.currentRow];
1718         var ser = [ ];
1719
1720         for(var i=0; i<rows.length; i++) {
1721             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1722         }
1723
1724         ser = YAHOO.lang.JSON.stringify(ser);
1725
1726         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1727         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1728
1729
1730         var count = 0;
1731
1732
1733         if(type == 'read' || type == 'deleted') {
1734             // mark read
1735             for(var j=0; j<rows.length; j++) {
1736                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1737                     count = count + 1;
1738                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1739                 }
1740             }
1741            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1742             if(ieId){
1743             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1744             var unseenCount = node.data.unseen;
1745             if (isNaN(unseenCount)) {
1746                 unseenCount = 0;
1747             }
1748             var finalCount = parseInt(unseenCount) - count;
1749             node.data.unseen = finalCount;
1750
1751             SE.accounts.renderTree();
1752             }
1753         } else if(type == 'unread') {
1754             // mark unread
1755             for(var j=0; j<rows.length; j++) {
1756                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1757                     count = count + 1;
1758                 }
1759             }
1760
1761             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1762             var unseenCount = node.data.unseen;
1763             if (isNaN(unseenCount)) {
1764                 unseenCount = 0;
1765             }
1766             var finalCount = parseInt(unseenCount) + count;
1767             node.data.unseen = finalCount;
1768             SE.accounts.renderTree();
1769         }
1770
1771         if (type == 'unread') {
1772                 for(var i=0; i<rows.length; i++) {
1773                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1774                 } // for
1775         }
1776
1777                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1778         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1779     },
1780
1781     /**
1782      * refreshes the ListView to show changes to cache
1783      */
1784     markEmailCleanup : function() {
1785         SE.accounts.renderTree();
1786         hideOverlay();
1787         SE.listView.refreshGrid();
1788     },
1789
1790         showAssignmentDialog : function() {
1791                 if (SE.contextMenus.assignmentDialog == null) {
1792                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1793                 } else {
1794                         SE.contextMenus.assignmentDialog.show();
1795                 } // else
1796         },
1797
1798         /**
1799      * shows the import dialog with only relate visible.
1800      */
1801     relateTo : function() {
1802         SE.contextMenus.emailListContextMenu.hide();
1803
1804         var rows = SE.grid.getSelectedRows();
1805         var data = SE.grid.getRecord(rows[0]).getData();
1806         var ieId = data.ieId;
1807         var folder = data.mbox;
1808         var uids = [];
1809         /* iterate through available rows JIC a row is deleted - use first available */
1810         for(var i=0; i<rows.length; i++) {
1811             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1812         }
1813         var ser = YAHOO.lang.JSON.stringify(uids);
1814         
1815         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1816     },
1817
1818         /**
1819      * shows the import dialog with only relate visible.
1820      */
1821     showDetailView : function() {
1822         SE.contextMenus.emailListContextMenu.hide();
1823         var rows = SE.grid.getSelectedRows();
1824         if (rows.length > 1) {
1825                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1826                 return;
1827         }
1828         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1829         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1830         /* iterate through available rows JIC a row is deleted - use first available */
1831         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1832         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1833     },
1834
1835     /**
1836      *
1837      */
1838     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1839         overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1840         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1841     },
1842
1843     /**
1844      * Opens multiple messages from ListView context click
1845      */
1846     openMultiple : function() {
1847         SE.contextMenus.emailListContextMenu.hide();
1848
1849         var rows = SE.grid.getSelectedRows();
1850         var uids = SE.listView.getUidsFromSelection();
1851
1852         if(uids.length > 0) {
1853             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1854             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1855             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1856         }
1857     },
1858
1859     /**
1860      * Replies/forwards email
1861      */
1862     replyForwardEmailContext : function() {
1863         SE.contextMenus.emailListContextMenu.hide();
1864
1865         var indexes = SE.grid.getSelectedRows();
1866         //var dm = SE.grid.getDataModel();
1867         var type = this.id;
1868
1869         for(var i=0; i<indexes.length; i++) {
1870             var row = SE.grid.getRecord(indexes[i]).getData();
1871             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1872         }
1873     },
1874
1875     //show menu functions
1876     showEmailsListMenu : function(grid, row) {
1877
1878        var data = row.getData();
1879        var draft = (data.type == "draft");
1880        var menu = SE.contextMenus.emailListContextMenu;
1881        var folderNode;
1882
1883        if (SE.tree)
1884        {
1885                if (data.mbox == 'sugar::Emails')
1886                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1887                else
1888                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1889
1890                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1891                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1892                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1893                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1894                else
1895                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1896        }
1897        else
1898            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1899
1900        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1901        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1902        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1903        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1904        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1905
1906
1907        if (data.mbox == "sugar::Emails")
1908        {
1909            //Allow users to reassign imported emails
1910            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1911            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1912            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1913            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1914        }
1915        else
1916        {
1917            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1918            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1919        }
1920     },
1921
1922     showFolderMenu : function(grid, rowIndex, event) {
1923        event.stopEvent();
1924        var coords = event.getXY();
1925        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1926     }
1927 };
1928
1929 SE.contextMenus.dv = {
1930     archiveToSugar : function(contextMenuId) {
1931
1932         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1933     },
1934
1935     replyForwardEmailContext : function(all) {
1936         SE.contextMenus.detailViewContextMenu.hide();
1937     }
1938
1939 };
1940
1941
1942
1943
1944
1945 ////    END SE.contextMenus
1946 ///////////////////////////////////////////////////////////////////////////////
1947
1948
1949
1950 ///////////////////////////////////////////////////////////////////////////////
1951 ////    DETAIL VIEW
1952 SE.detailView = {
1953     consumeMetaDetail : function(ret) {
1954         // handling if the Email drafts
1955         if(ret.type == 'draft') {
1956             SE.composeLayout.c0_composeDraft();
1957             return;
1958         }
1959
1960
1961         // cache contents browser-side
1962         SE._setDetailCache(ret);
1963
1964         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1965         // 2 below must be in global context
1966         meta = ret.meta;
1967         meta['panelId'] = SE.util.getPanelId();
1968
1969         email = ret.meta.email;
1970         var out = displayTemplate.exec({
1971             'app_strings' : app_strings,
1972             'theme' : theme,
1973             'idx' : targetDiv.id,
1974             'meta' : meta,
1975             'email' : meta.email,
1976             'linkBeans' : linkBeans
1977         });
1978         var tabLabel = meta.email.name;
1979         if (tabLabel != null && tabLabel.length > 25) {
1980                 tabLabel = tabLabel.substring(0, 25) + "...";
1981         } // if
1982         targetDiv.set("label", tabLabel);
1983         targetDiv.set("content", out);
1984
1985         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1986         if (SUGAR.email2.util.isIe()) {
1987                 displayEmailFrameDiv.style.height = "390px";
1988         } else {
1989                 displayEmailFrameDiv.style.height = "410px";
1990         }
1991
1992         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1993         displayFrame.contentWindow.document.write(email.description);
1994         displayFrame.contentWindow.document.close();
1995
1996         // hide archive links
1997         if(ret.meta.is_sugarEmail) {
1998                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1999             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
2000         } else {
2001             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
2002                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
2003         } // else
2004
2005     },
2006
2007     consumeMetaPreview : function(ret) {
2008         // cache contents browser-side
2009         SE._setDetailCache(ret);
2010
2011
2012
2013         var currrow = SE.grid.getLastSelectedRecord();
2014         currrow = SE.grid.getRecord(currrow);
2015         if (!currrow) {
2016             document.getElementById('_blank').innerHTML = '';
2017             return;
2018         }
2019         // handling if the Email drafts
2020         if(ret.type == 'draft'){
2021             if (currrow.getData().uid == ret.uid) {
2022                 SE.composeLayout.c0_composeDraft();
2023             }
2024             return;
2025         }
2026
2027         if (currrow.getData().uid != ret.meta.uid) {
2028            return;
2029         }
2030
2031         // remove loading sprite
2032         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2033         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2034         meta = ret.meta;
2035         meta['panelId'] = SE.util.getPanelId();
2036         email = ret.meta.email;
2037
2038         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2039             'app_strings' : app_strings,
2040             'theme' : theme,
2041             'idx' : 'Preview',
2042             'meta' : meta,
2043             'email' :meta.email,
2044             'linkBeans' : linkBeans
2045         });
2046        // document.getElementById('_blank').innerHTML = meta.email;
2047        /* displayTemplate.append('_blank', {
2048             'app_strings' : app_strings,
2049             'theme' : theme,
2050             'idx' : 'Preview',
2051             'meta' : meta,
2052             'email' :meta.email,
2053             'linkBeans' : linkBeans
2054         });*/
2055
2056         var displayFrame = document.getElementById('displayEmailFramePreview');
2057         displayFrame.contentWindow.document.write(email.description);
2058         displayFrame.contentWindow.document.close();
2059
2060         SE.listViewLayout.resizePreview();
2061
2062         // hide archive links
2063         if(ret.meta.is_sugarEmail) {
2064             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2065             document.getElementById("btnEmailViewPreview").style.display = "none";
2066             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2067         } else {
2068           //hide view relationship link
2069                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2070         }
2071     },
2072
2073     /**
2074      * wraps emailDelete() for single messages, comes from preview or tab
2075      */
2076     emailDeleteSingle : function(ieId, uid, mbox) {
2077         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2078             // find active panel and close if the user double clicked the email to view.
2079             var activeTabId = SE.util.getPanelId();
2080             if(activeTabId != 'Preview')
2081                 SE.innerLayout.get("activeTab").close();
2082
2083             document.getElementById('_blank').innerHTML = "";
2084                 var ser = [ ];
2085                         ser.push(uid);
2086                 uid = YAHOO.lang.JSON.stringify(ser);
2087             this.emailDelete(ieId, uid, mbox);
2088         }
2089     },
2090
2091     /**
2092      * Sends async call to delete a given message
2093      * @param
2094      */
2095     emailDelete : function(ieId, uid, mbox) {
2096        overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2097        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2098            uid + "&ieId=" + ieId + "&folder=" + mbox);
2099     },
2100
2101     /**
2102      * retrieves one email to display in the preview pane.
2103      */
2104     getEmailPreview : function() {
2105         var row = SUGAR.email2.listView.currentRow;
2106         var data = row.getData();
2107             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2108                var setRead = (data['seen'] == 0) ? true : false;
2109                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2110                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2111             }
2112     },
2113
2114     /**
2115      * Imports one email into Sugar
2116      */
2117     importEmail : function(ieId, uid, mbox) {
2118         SE.util.clearHiddenFieldValues('emailUIForm');
2119
2120         overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2121
2122         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2123         AjaxObject.target = '';
2124         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2125     },
2126
2127     /**
2128      * Populates the frameFlex div with the contents of an email
2129      */
2130     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2131         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2132
2133         var mboxStr = new String(mbox);
2134         var compKey = mbox + uid;
2135
2136         if(setRead == true) {
2137                 SE.listView.boldUnreadRows()
2138                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2139         }
2140
2141         if(destination == SE.innerLayout) {
2142                 /*
2143              * loading email into a tab, peer with ListView
2144              * targetDiv must remain in the global namespace as it is used by AjaxObject
2145              */
2146                 //Check if we already have a tab of the email open
2147                 var tabs = SE.innerLayout.get("tabs");
2148                 for (var t in tabs) {
2149                         if (tabs[t].id && tabs[t].id == uid) {
2150                                 SE.innerLayout.set("activeTab", tabs[t]);
2151                                 return;
2152                         }
2153                 }
2154
2155                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2156                                 label: loadingSprite,
2157                                         scroll : true,
2158                                         content : "",
2159                                         active : true
2160                 }, SE.innerLayout);
2161                 targetDiv.id = uid;
2162                 SE.innerLayout.addTab(targetDiv);
2163
2164             // use cache if available
2165             if(SE.cache[compKey]) {
2166                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2167             } else {
2168                 // open email as peer-tab to listView
2169                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2170                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2171             }
2172         } else {
2173             // loading email into preview pane
2174             document.getElementById('_blank').innerHTML = loadingSprite;
2175
2176             // use cache if available
2177             if(SE.cache[compKey]) {
2178                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2179             } else {
2180                 AjaxObject.forceAbort = true;
2181                 // open in preview window
2182                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2183                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2184             }
2185         }
2186     },
2187
2188     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2189     {
2190         if(mboxStr.substring(0,7) == 'sugar::') {
2191             // display an email from Sugar
2192             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2193         } else {
2194             // display an email from an email server
2195             document.getElementById('emailUIAction').value = 'getSingleMessage';
2196         }
2197         document.getElementById('mbox').value = mbox;
2198         document.getElementById('ieId').value = ieId;
2199         document.getElementById('uid').value = uid;
2200
2201         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2202
2203         AjaxObject.forceAbort = true;
2204         AjaxObject.target = '_blank';
2205         AjaxObject.startRequest(callback, null);
2206     },
2207
2208     /**
2209      * Retrieves multiple emails for DetailView
2210      */
2211     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2212         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2213         SE.util.clearHiddenFieldValues('emailUIForm');
2214
2215         var mboxStr = new String(mbox);
2216
2217         uids = SE.util.cleanUids(uids);
2218
2219         if(mboxStr.substring(0,7) == 'sugar::') {
2220             // display an email from Sugar
2221             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2222             document.getElementById('uid').value = uids;
2223         } else {
2224             // display an email from an email server
2225             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2226             document.getElementById('mbox').value = mbox;
2227             document.getElementById('ieId').value = ieId;
2228             document.getElementById('uid').value = uids;
2229         }
2230
2231         var formObject = document.getElementById('emailUIForm');
2232         YAHOO.util.Connect.setForm(formObject);
2233
2234         AjaxObject.target = 'frameFlex';
2235         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2236
2237         if(setRead == true) {
2238             var c = uids.split(",");
2239             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2240         }
2241     },
2242
2243     /**
2244      * Makes async call to get QuickCreate form
2245      * Renders a modal edit view for a given module
2246      */
2247     quickCreate : function(module, ieId, uid, mailbox) {
2248         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2249
2250         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2251             get += "&sugarEmail=true";
2252         }
2253
2254         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2255     },
2256
2257     /**
2258      * Makes async call to save a quick create
2259      * @param bool
2260      */
2261     saveQuickCreate : function(action) {
2262         var qcd = SE.detailView.quickCreateDialog;
2263         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2264                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2265                 var theCallback = callbackQuickCreateSave;
2266                 var accountType = '&sugarEmail=true';
2267                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2268                    accountType = '&ieId=' + qcd.ieId;
2269                 }
2270
2271             if (action == 'reply') {
2272                    theCallback = callbackQuickCreateSaveAndReply;
2273                 } else if (action == true) {
2274                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2275                 }
2276                 formObject.action.value = 'EmailUIAjax';
2277                 YAHOO.util.Connect.setForm(formObject);
2278                 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2279                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2280                                        accountType + '&mbox=' + qcd.mbox);
2281         }
2282     },
2283
2284     /**
2285      * Code to show/hide long list of email address in DetailView
2286      */
2287     showCroppedEmailList : function(el) {
2288         el.style.display = 'none';
2289         el.previousSibling.style.display = 'inline'
2290     },
2291     showFullEmailList : function(el) {
2292         el.style.display = 'none';
2293         el.nextSibling.style.display = 'inline';
2294     },
2295
2296     /**
2297      * Shows the QuickCreate overlay
2298      * @param string ieId
2299      * @param string uid
2300      * @param string mailbox
2301      */
2302     showQuickCreate : function(ieId, uid, mailbox) {
2303         var panelId = SE.util.getPanelId();
2304         var context = document.getElementById("quickCreateSpan" + panelId);
2305
2306         if (!SE.detailView.cqMenus)
2307                 SE.detailView.cqMenus = {};
2308
2309         if (SE.detailView.cqMenus[context])
2310                 SE.detailView.cqMenus[context].destroy();
2311
2312             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2313                 lazyload:true,
2314                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2315         });
2316
2317             for (var i=0; i < this.qcmodules.length; i++) {
2318             var module = this.qcmodules[i];
2319             menu.addItem({
2320                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2321                 modulename: module,
2322                 value: module,
2323                 onclick: { fn: function() {
2324                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2325                         }
2326                 }
2327             });
2328         }
2329
2330                 menu.render(document.body);
2331                 menu.show();
2332     },
2333
2334     /**
2335      * Displays the "View" submenu in the detailView
2336      * @param string ieId
2337      * @param string uid
2338      * @param string mailbox
2339      */
2340     showViewMenu : function(ieId, uid, mailbox) {
2341         var panelId = SE.util.getPanelId();
2342         var context = "btnEmailView" + panelId;
2343         if (!SE.detailView.viewMenus)
2344                 SE.detailView.viewMenus = {};
2345
2346         if (SE.detailView.viewMenus[context])
2347                 SE.detailView.viewMenus[context].destroy();
2348
2349             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2350                 lazyload:true,
2351                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2352                 clicktohide: true
2353         });
2354                 menu.addItems(
2355                                 (ieId == 'null' || ieId == null) ?
2356                         //No ieId - Sugar Email
2357                         [{
2358                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2359                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2360             }]
2361                         :
2362                         //IeID exists, on a remote server
2363                         [{
2364                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2365                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2366             },{
2367                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2368                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2369             }]
2370         );
2371                 menu.render(document.body);
2372                 menu.show();
2373
2374
2375         /*
2376         //#23108 jchi@07/17/2008
2377         menu.render('quickCreateSpan'+ panelId);*/
2378         //this.viewMenu = menu;
2379         //this.viewMenu.show(context);
2380     },
2381     /**
2382      * Makes async call to get an email's headers
2383      */
2384     viewHeaders : function(ieId, uid, mailbox) {
2385         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2386         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2387     },
2388
2389     /**
2390      * Makes async call to get a printable version
2391      */
2392     viewPrintable : function(ieId, uid, mailbox) {
2393         if(mailbox == 'sugar::Emails') {
2394             // display an email from Sugar
2395             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2396         } else {
2397             // display an email from an email server
2398             var emailUIAction = '&emailUIAction=getSingleMessage';
2399         }
2400
2401         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2402         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2403     },
2404
2405     /**
2406      * Makes async call to get an email's raw source
2407      */
2408     viewRaw : function(ieId, uid, mailbox) {
2409         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2410         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2411     },
2412
2413     /**
2414      * Display all email addresses in detailview.
2415      */
2416     displayAllAddrs : function(el) {
2417         el.style.display = 'none';
2418         Dom.getNextSibling(el).style.display = 'inline';
2419     }
2420 };
2421 ////    END SE.detailView
2422 ///////////////////////////////////////////////////////////////////////////////
2423
2424
2425
2426 ///////////////////////////////////////////////////////////////////////////////
2427 ////    SE.folders
2428 SE.folders = {
2429     contextMenuFocus : new Object(),
2430
2431     /**
2432      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2433      * SugarFolder ID - folder strings
2434      */
2435     _createFolderId : function(node) {
2436         var ret = '';
2437
2438         if(!node.data.id)
2439             return ret;
2440
2441         if(node.data.ieId) {
2442             /* we have a local Sugar folder */
2443             if(node.data.ieId == 'folder') {
2444                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2445             } else if(node.data.ieId.match(SE.reGUID)) {
2446                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2447             }
2448         } else {
2449             ret = node.data.id;
2450         }
2451
2452         return ret;
2453     },
2454
2455     addChildNode : function(parentNode, childNode) {
2456         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2457         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2458         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2459
2460         if(childNode.nodes) {
2461             if(childNode.nodes.length > 0) {
2462                 for(j=0; j<childNode.nodes.length; j++) {
2463                     var newChildNode = childNode.nodes[j];
2464                     this.addChildNode(node, newChildNode);
2465                 }
2466             }
2467         }
2468     },
2469
2470     /**
2471      * Builds and returns a new TreeView Node
2472      * @param string name
2473      * @param string id
2474      * @param int is_group
2475      * @return object
2476      */
2477     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2478         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2479
2480         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2481         node.expanded = expanded;
2482         node.data = new Object;
2483         node.data['id'] = id;
2484         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2485         node.data['label'] = name;
2486         node.data['ieId'] = 'folder';
2487         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2488         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2489         node.data['unseen'] = unseen;
2490         return node;
2491     },
2492
2493     /**
2494      * ensures that a new folder has a valid name
2495      */
2496     checkFolderName : function(name) {
2497         if(name == "")
2498             return false;
2499
2500         this.folderAdd(name);
2501     },
2502
2503     /**
2504      * Pings email servers for new email - forces refresh of folder pane
2505      */
2506     checkEmailAccounts : function() {
2507         this.checkEmailAccountsSilent(true);
2508     },
2509
2510     checkEmailAccountsSilent : function(showOverlay) {
2511         if(typeof(SE.folders.checkingMail)) {
2512             clearTimeout(SE.folders.checkingMail);
2513         }
2514
2515         // don't stomp an on-going request
2516         if(AjaxObject.currentRequestObject.conn == null) {
2517             if(showOverlay) {
2518                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2519                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2520             }
2521             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2522         } else {
2523             // wait 5 secs before trying again.
2524             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2525         }
2526     },
2527
2528     /**
2529      * Starts check of all email Accounts using a loading bar for large POP accounts
2530      */
2531     startEmailAccountCheck : function() {
2532         // don't do two checks at the same time
2533        if(!AjaxObject.requestInProgress()) {
2534             overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2535             SE.accounts.ieIds = SE.folders.getIeIds();
2536             if (SE.accounts.ieIds.length > 0) {
2537                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2538                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2539             } else {
2540                hideOverlay();
2541             }
2542         } else {
2543             // wait 5 secs before trying again.
2544             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2545         }
2546     },
2547
2548     /**
2549      * Checks a single Account check based on passed ieId
2550      */
2551      startEmailCheckOneAccount : function(ieId, synch) {
2552             if (synch) {
2553                 synch = true;
2554             } else {
2555                 synch = false;
2556             }
2557             var mbox = "";
2558             var node = SE.clickedFolderNode;
2559             if (node && !synch) {
2560                 mbox = node.data.mbox;
2561             } // if
2562             overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2563             SE.accounts.ieIds = [ieId];
2564             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2565                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2566       },
2567
2568
2569     /**
2570      * Empties trash for subscribed accounts
2571      */
2572     emptyTrash : function() {
2573         SE.contextMenus.frameFoldersContextMenu.hide();
2574         overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2575         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2576     },
2577
2578     /**
2579      * Clears Cache files of the inboundemail account
2580      */
2581     clearCacheFiles : function(ieId) {
2582         SE.contextMenus.frameFoldersContextMenu.hide();
2583         overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2584         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2585     },
2586
2587
2588     /**
2589      * Returns an array of all the active accounts in the folder view
2590      */
2591     getIeIds : function() {
2592          var ieIds = [];
2593          var root = SE.tree.getRoot();
2594          for(i=0; i < root.children.length; i++) {
2595            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2596                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2597                ieIds.push(root.children[i].children[0].data.ieId);
2598            }
2599          }
2600          return ieIds;
2601      },
2602
2603     /**
2604      * loads folder lists in Settings->Folders
2605      */
2606     lazyLoadSettings : function() {
2607         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2608         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2609     },
2610
2611     /**
2612      * After the add new folder is done via folders tab on seetings, this function should get called
2613      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2614      */
2615     loadSettingFolder : function() {
2616         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2617         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2618     },
2619
2620     /**
2621      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2622      */
2623     removeSugarFolders : function() {
2624         var tree = SE.tree;
2625         var root = tree.getRoot();
2626         var folder = SE.util.findChildNode(root, "ieId", "folder");
2627         while(folder) {
2628             tree.removeNode(folder);
2629             folder = SE.util.findChildNode(root, "ieId", "folder");
2630         }
2631         if (!root.childrenRendered) {
2632                 root.childrenRendered = true;
2633         }
2634     },
2635
2636     rebuildFolders : function(silent) {
2637       if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2638        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2639     },
2640
2641
2642
2643     /**
2644      * Updates TreeView with Sugar Folders
2645      */
2646     setSugarFolders : function(delay) {
2647         this.removeSugarFolders();
2648                 //AjaxObject.forceAbort = true;
2649                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2650     },
2651
2652     /**
2653      * Takes async data object and creates the sugar folders in TreeView
2654      */
2655     setSugarFoldersEnd : function(o) {
2656         var root = SE.tree.getRoot();
2657         addChildNodes(root, {nodes: o});
2658         SE.accounts.renderTree();
2659         //If nothing is loaded in the grid, load "My Inbox"
2660         if (SE.grid.params.ieId == "undefined") {
2661                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2662         }
2663     },
2664
2665     startCheckTimer : function() {
2666         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2667             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2668
2669             if(typeof(SE.folders.checkTimer) != 'undefined') {
2670                 clearTimeout(SE.folders.checkTimer);
2671             }
2672
2673             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2674             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2675             {
2676                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2677                 SE.folders.checkEmailAccountsSilent(false);
2678             }
2679         }
2680     },
2681
2682     /**
2683      * makes an async call to save user preference and refresh folder view
2684      * @param object SELECT list object
2685      */
2686     setFolderSelection : function() {
2687         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2688
2689         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2690         var a_active_accnts = "";
2691         for(i=0;i<a_rs.length;i++)
2692         {
2693                 var t_record = a_rs[i];
2694                 var is_active = t_record.getData('is_active');
2695                 if(is_active)
2696                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2697         }
2698
2699         if(a_active_accnts == "")
2700                 a_active_accnts = "&ieIdShow[]=";
2701
2702         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2703
2704         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2705     },
2706
2707     /**
2708      * makes async call to save user preference for a given node's open state
2709      * @param object node YUI TextNode object
2710      */
2711     setOpenState : function(node) {
2712         SE.util.clearHiddenFieldValues('emailUIForm');
2713         var nodePath = node.data.id;
2714         var nodeParent = node.parent;
2715
2716         while(nodeParent != null) {
2717             // root node has no ID param
2718             if(nodeParent.data != null) {
2719                 nodePath = nodeParent.data.id + "::" + nodePath;
2720             }
2721
2722             var nodeParent = nodeParent.parent;
2723         }
2724
2725         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2726         document.getElementById('focusFolder').value = nodePath;
2727
2728         if(node.expanded == true) {
2729             document.getElementById('focusFolderOpen').value = 'open';
2730         } else {
2731             document.getElementById('focusFolderOpen').value = 'closed';
2732         }
2733
2734         var formObject = document.getElementById('emailUIForm');
2735         YAHOO.util.Connect.setForm(formObject);
2736
2737         AjaxObject.startRequest(null, null);
2738     },
2739
2740     getNodeFromMboxPath : function(path) {
2741         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2742         var a = YAHOO.lang.JSON.parse(path);
2743
2744         var node = tree.getRoot();
2745
2746         var i = 0;
2747         while(i < a.length) {
2748             node = this.getChildNodeFromLabel(node, a[i]);
2749             i++;
2750         }
2751
2752         return node;
2753     },
2754
2755     getChildNodeFromLabel : function(node, nodeLabel) {
2756         for(i=0; i<node.children.length; i++) {
2757             if(node.children[i].data.id == nodeLabel) {
2758                 return node.children[i];
2759             }
2760         }
2761     },
2762
2763     /**
2764      * returns the node that presumably under the user's right-click
2765      */
2766     getNodeFromContextMenuFocus : function() {
2767         //// get the target(parent) node
2768         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2769         var index = -1;
2770         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2771
2772         // filter local folders
2773         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2774             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2775                 if(target.id == '') {
2776                     target = target.parentNode;
2777                 } else {
2778                     break;
2779                 }
2780             }
2781         }
2782
2783         var targetNode = document.getElementById(target.id);
2784         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2785
2786         try {
2787             var matches = re.exec(targetNode.id);
2788         } catch(ex) {
2789             return document.getElementById(ygtvlabelel1);
2790         }
2791
2792         if(matches) {
2793             index = matches[1];
2794         } else {
2795             // usually parent node
2796             matches = re.exec(targetNode.parentNode.id);
2797
2798             if(matches) {
2799                 index = matches[1];
2800             }
2801         }
2802
2803         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2804         parentNode.expand();
2805
2806         return parentNode;
2807     },
2808
2809     /**
2810      * Decrements the Unread Email count in folder text
2811      * @param string ieId ID to look for
2812      * @param string mailbox name
2813      * @param count how many to decrement
2814      */
2815     decrementUnreadCount : function(ieId, mbox, count) {
2816
2817         if(mbox == null)
2818             return;
2819
2820         if(mbox.indexOf("sugar::") === 0) {
2821             var node = this.getNodeFromId(ieId);
2822         } else {
2823             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2824         }
2825         if(node) {
2826             var unseen = node.data.unseen;
2827             if(unseen > 0) {
2828                 var check = unseen - count;
2829                 var finalCount = (check >= 0) ? check : 0;
2830                 node.data.unseen = finalCount;
2831             }
2832             SE.accounts.renderTree();
2833         }
2834     },
2835
2836     /**
2837      * gets the TreeView node with a given ID/ieId
2838      * @param string id ID to look for
2839      * @return object Node
2840      */
2841     getNodeFromId : function(id) {
2842         SE.folders.focusNode = null;
2843         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2844             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2845                 SE.folders.focusNode = this;
2846                 return false;
2847             }
2848         }, null, [id]);
2849         return SE.folders.focusNode;
2850     },
2851
2852     /**
2853      * Uses ieId and mailbox to try to find a node in the tree
2854      */
2855     getNodeFromIeIdAndMailbox : function(id, mbox) {
2856                 SE.folders.focusNode = null;
2857         if (mbox == "sugar::Emails") {
2858                 mbox = id;
2859                 id = "folder";
2860         } // if
2861         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2862                 if (varsarray instanceof Array) {
2863             if (this.data.ieId && this.data.ieId == varsarray[0]
2864                     && this.data.mbox == varsarray[1]) {
2865                 SE.folders.focusNode = this;
2866                 return false;
2867             } }
2868                 else {
2869                         if (this.data.ieId && this.data.ieId == varsarray) {
2870                                 SE.folders.focusNode = this;
2871                     return false;
2872                         }
2873                 }
2874         }, null, [id, mbox]);
2875         return SE.folders.focusNode;
2876     },
2877
2878     unhighliteAll : function() {
2879         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2880     },
2881
2882     /**
2883      * Displays a short form
2884      */
2885     folderAdd : function() {
2886         SE.contextMenus.frameFoldersContextMenu.hide();
2887
2888         var node = SE.clickedFolderNode;
2889
2890         if(node != null && node.data) {
2891             overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2892                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2893                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2894         } else {
2895             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2896         }
2897     },
2898
2899     folderAddRegisterEnter : function() {
2900         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2901                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2902                                                                                                                         this.buttons[1].handler);
2903
2904                 this.enterKeyListener.enable();
2905     },
2906
2907     folderRemoveRegisterEnter : function() {
2908         this.enterKeyListener.disable();
2909     },
2910
2911     folderAddXmlCall : function(name) {
2912         if (trim(name) == "") {
2913                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2914                 return false;
2915         }
2916         name = escape(name);
2917         var post = '';
2918         var type = 'sugar';
2919
2920         var parentNode = SE.clickedFolderNode;
2921
2922         this.contextMenuFocus = parentNode;
2923
2924         if(parentNode.data.ieId) {
2925             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2926                 type = 'imap';
2927             }
2928         }
2929         if(type == 'imap') {
2930                 // make an IMAP folder
2931             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2932             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2933         } else if(type == 'sugar') {
2934             // make a Sugar folder
2935             if(SE.folders.isUniqueFolderName(name)) {
2936                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2937                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2938             } else {
2939                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2940                 SE.folders.folderAdd();
2941                 return;
2942             }
2943         } else {
2944             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2945         }
2946
2947         // hide add-folder diaglogue
2948         SE.e2overlay.hide();
2949     },
2950
2951     /**
2952      * Removes either an IMAP folder or a Sugar Folder
2953      */
2954     folderDelete : function() {
2955         SE.contextMenus.frameFoldersContextMenu.hide();
2956
2957         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2958             var post = '';
2959             var parentNode = SE.clickedFolderNode;
2960
2961             if(parentNode != null && parentNode.data) {
2962                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2963                     overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2964                     return;
2965                 }
2966
2967                 AjaxObject.target = 'frameFlex';
2968
2969                 if(parentNode.data.ieId != 'folder') {
2970                     // delete an IMAP folder
2971                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2972                 } else {
2973                     // delete a sugar folder
2974                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2975                 }
2976                 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2977                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2978             } else {
2979                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2980             }
2981         }
2982     },
2983
2984     /**
2985      * Rename folder form
2986      */
2987      //EXT111
2988     folderRename : function() {
2989         SE.contextMenus.frameFoldersContextMenu.hide();
2990         var node = SE.clickedFolderNode;
2991
2992         if(node != null) {
2993             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2994                 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2995                 return;
2996             }
2997
2998                         overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2999                     app_strings.LBL_EMAIL_SETTINGS_NAME,
3000                     'prompt',
3001                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
3002         } else {
3003             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
3004         }
3005     },
3006
3007     /**
3008      * fills an Object with key-value pairs of available folders
3009      */
3010     getAvailableFoldersObject : function() {
3011         var ret = new Object();
3012         var tree = SE.tree.root;
3013
3014         if(tree.children) {
3015             for(var i=0; i<tree.children.length; i++) {
3016                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
3017             }
3018         } else {
3019             ret['none'] = app_strings.LBL_NONE;
3020         }
3021
3022         return ret;
3023     },
3024
3025     /**
3026      * Fills in key-value pairs for dependent dropdowns
3027      * @param object ret Associative array
3028      * @param object node TreeView node in focus
3029      * @param string currentPath Built up path thus far
3030      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3031      */
3032     getFolderFromChild : function(ret, node, currentPath, spacer) {
3033         if(node.data != null && node.depth > 0) {
3034             /* handle visual separtors differentiating b/t mailserver and local */
3035             if(node.data.ieId && node.data.ieId == 'folder') {
3036                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3037             }
3038
3039             if(!ret.spacer0) {
3040                 ret['spacer0'] = spacer;
3041             } else if(ret.spacer0 != spacer) {
3042                 ret['spacer1'] = spacer
3043             }
3044
3045             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3046             var depthMarker = currentPath;
3047             var retIndex = SE.folders._createFolderId(node);
3048             ret[retIndex] = depthMarker + theLabel;
3049         }
3050
3051         if(node.children != null) {
3052             if(theLabel) {
3053                 currentPath += theLabel + "/";
3054             }
3055
3056             for(var i=0; i<node.children.length; i++) {
3057                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3058             }
3059         }
3060
3061         return ret;
3062     },
3063
3064     /**
3065      * Wrapper to refresh folders tree
3066      */
3067     getFolders : function() {
3068         SE.accounts.rebuildFolderList();
3069     },
3070
3071     /**
3072      * handles events around folder-rename input field changes
3073      * @param object YUI event object
3074      */
3075     handleEnter : function(e) {
3076         switch(e.browserEvent.type) {
3077             case 'click':
3078                 e.preventDefault(); // click in text field
3079             break;
3080
3081             case 'blur':
3082                 SE.folders.submitFolderRename(e);
3083             break;
3084
3085             case 'keypress':
3086                 var kc = e.browserEvent.keyCode;
3087                 switch(kc) {
3088                     case 13: // enter
3089                         e.preventDefault();
3090                         SE.folders.submitFolderRename(e);
3091                     break;
3092
3093                     case 27: // esc
3094                         e.preventDefault(e);
3095                         SE.folders.cancelFolderRename(e);
3096                     break;
3097                 }
3098             break;
3099         }
3100     },
3101     /**
3102     * Called when a node is clicked on in the folder tree
3103     * @param node, The node clicked on
3104     * @param e, The click event
3105     */
3106     handleClick : function(o) {
3107         var node = o.node;
3108         //If the click was on a sugar folder
3109         if (node.data.ieId == "folder") {
3110             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3111         }
3112         else {
3113             SE.listView.populateListFrame(node, node.data.ieId, false);
3114         }
3115        //eval(node.data.click);
3116        //debugger;
3117     },
3118
3119     /**
3120     * Called when a node is right-clicked on in the folder tree
3121     */
3122     handleRightClick : function(e) {
3123         YAHOO.util.Event.preventDefault(e);
3124                 //Get the Tree Node
3125                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3126                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3127
3128                 //If the click was on a sugar folder
3129         SE.clickedFolderNode = node;
3130         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3131                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3132                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3133                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3134                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3135                 menu.getItem(3).cfg.setProperty("disabled", false);
3136                 menu.getItem(4).cfg.setProperty("disabled", false);
3137                 menu.getItem(5).cfg.setProperty("disabled", false);
3138                 menu.getItem(6).cfg.setProperty("disabled", true);
3139                 //Group folder
3140                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3141                         menu.getItem(0).cfg.setProperty("disabled", true);
3142                         menu.getItem(1).cfg.setProperty("disabled", true);
3143                         menu.getItem(2).cfg.setProperty("disabled", true);
3144                         menu.getItem(3).cfg.setProperty("disabled", true);
3145                         menu.getItem(4).cfg.setProperty("disabled", true);
3146                 }
3147         if (node.data.protocol != null) {
3148                 menu.getItem(6).cfg.setProperty("disabled", false);
3149         }
3150                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3151                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3152                         //Sent or Draft folders
3153                         menu.getItem(3).cfg.setProperty("disabled", true);
3154                         menu.getItem(4).cfg.setProperty("disabled", true);
3155                         menu.getItem(5).cfg.setProperty("disabled", true);
3156                 }
3157
3158                 //For group with auto inbound, disable everything.
3159                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3160                 {
3161                     menu.getItem(0).cfg.setProperty("disabled", true);
3162                 menu.getItem(1).cfg.setProperty("disabled", true);
3163                 menu.getItem(2).cfg.setProperty("disabled", true);
3164                 menu.getItem(3).cfg.setProperty("disabled", true);
3165                 menu.getItem(4).cfg.setProperty("disabled", true);
3166                 menu.getItem(5).cfg.setProperty("disabled", true);
3167                 menu.getItem(6).cfg.setProperty("disabled", true);
3168                 }
3169
3170                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3171                 menu.show();
3172     },
3173
3174     /**
3175     * Called when a row is dropped on a node
3176     */
3177     handleDrop : function(rows, targetFolder) {
3178         var rowData = rows[0].getData();
3179         if (rowData.mbox != targetFolder.data.mbox) {
3180             var srcIeId = rowData.ieId;
3181             var srcFolder = rowData.mbox;
3182             var destIeId = targetFolder.data.ieId;
3183             var destFolder = targetFolder.data.mbox;
3184             var uids = [];
3185             for(var i=0; i<rows.length; i++) {
3186                 uids[i] = rows[i].getData().uid;
3187             }
3188             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3189         }
3190     },
3191
3192     /**
3193     * Called when something is dragged over a Folder Node
3194     */
3195     dragOver : function(dragObject) {
3196        return true;
3197     },
3198
3199     /**
3200      * Determines if a folder name is unique to the folder tree
3201      * @param string name
3202      */
3203     isUniqueFolderName : function(name) {
3204         uniqueFolder = true;
3205         var root = SE.tree.getRoot();
3206         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3207             if (this.attributes && this.attributes.ieId == "folder") {
3208                 if (this.attributes.text == name) {
3209                     uniqueFolder = false;
3210                     return false;
3211                 }
3212             }
3213         }, null, [name]);
3214         return uniqueFolder;
3215     },
3216
3217     /**
3218      * Makes async call to rename folder in focus
3219      * @param object e Event Object
3220      */
3221     submitFolderRename : function(newName) {
3222         if (trim(newName) == "") {
3223                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3224                 return false;
3225         }
3226                 newName = escape(newName);
3227         var node = SE.clickedFolderNode;
3228         var origName = node.data.text
3229         //Ignore no change
3230         if (newName == origName) {
3231             return true;
3232         }
3233         if(SE.folders.isUniqueFolderName(newName)) {
3234             overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3235             if (node.data.ieId == "folder") {
3236                 //Sugar Folder
3237                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3238             }
3239             else {
3240                 //IMAP folder or POP mailbox
3241                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3242                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3243                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3244             }
3245             return true;
3246         } else {
3247             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3248             return false;
3249         }
3250     },
3251
3252     moveFolder : function(folderId, parentFolderId) {
3253         if (folderId != parentFolderId)
3254         {
3255                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3256                     + folderId + "&newParentId=" + parentFolderId);
3257         }
3258     },
3259
3260     /**
3261      * makes async call to do a full synchronization of all accounts
3262      */
3263     synchronizeAccounts : function() {
3264         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3265             overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3266             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3267         }
3268     },
3269
3270     /**
3271      * Updates user's folder subscriptsion (Sugar only)
3272      * @param object SELECT DOM object in focus
3273      * @param string type of Folder selection
3274      */
3275     updateSubscriptions : function() {
3276         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3277
3278         var active = "";
3279
3280         select = document.getElementById('userFolders');
3281
3282         for(i=0; i<select.options.length; i++) {
3283             var opt = select.options[i];
3284              if(opt.selected && opt.value != "") {
3285                  if(active != "") {
3286                      active += "::";
3287                  }
3288                  active += opt.value;
3289              }
3290         }
3291
3292         //Add the group folder ids.
3293         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3294         for(i=0; i<group_folders.length; i++)
3295         {
3296             active += ("::" + group_folders[i]);
3297         }
3298
3299         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3300     },
3301     /**
3302      * Updates user's group folder subscriptsion (Sugar only)
3303      * @param ieID The group folder to add to the tree view
3304      */
3305     retrieveGroupFolderSubscriptions : function() {
3306
3307         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3308         var activeGroupFolders = "";
3309         var activeGroupIds = [];
3310         for(i=0;i<a_rs.length;i++)
3311         {
3312                 var t_record = a_rs[i];
3313                 var is_active = t_record.getData('is_active');
3314                 var isGroupFolder = t_record.getData('has_groupfolder');
3315                 var ieID = t_record.getData('id');
3316                 if( isGroupFolder )
3317                 {
3318                     if(is_active)
3319                       activeGroupIds.push(ieID);
3320                 }
3321         }
3322
3323         return activeGroupIds;
3324     }
3325
3326 };
3327
3328 SE.folders.checkEmail2 = function() {
3329     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3330 }
3331 ////    END FOLDERS OBJECT
3332 ///////////////////////////////////////////////////////////////////////////////
3333
3334
3335 ///////////////////////////////////////////////////////////////////////////////
3336 ////    SE.keys
3337 /**
3338  * Keypress Event capture and processing
3339  */
3340 SE.keys = {
3341     overall : function(e) {
3342         switch(e.charCode) {
3343             case 119: // "w"
3344                 if(e.ctrlKey || e.altKey) {
3345                     var focusRegion = SE.innerLayout.regions.center;
3346                     if(focusRegion.activePanel.closable == true) {
3347                         focusRegion.remove(focusRegion.activePanel);
3348                     }
3349                 }
3350             break;
3351         }
3352     }
3353 };
3354 ////    END SE.keys
3355 ///////////////////////////////////////////////////////////////////////////////
3356
3357
3358 ///////////////////////////////////////////////////////////////////////////////
3359 ////    SE.listView
3360 /**
3361  * ListView object methods and attributes
3362  */
3363 SE.listView = {
3364     currentRowId : -1,
3365
3366     /**
3367      * Fills the ListView pane with detected messages.
3368      */
3369     populateListFrame : function(node, ieId, forceRefresh) {
3370         SE.innerLayout.selectTab(0);
3371                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3372
3373         Dom.get('_blank').innerHTML = "";
3374         SE.grid.params['emailUIAction'] = 'getMessageList';
3375         SE.grid.params['mbox'] = node.data.mbox;
3376         SE.grid.params['ieId'] = ieId;
3377         forcePreview = true; // loads the preview pane with first item in grid
3378         SE.listView.refreshGrid();
3379     },
3380
3381     /**
3382      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3383      */
3384     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3385         SE.innerLayout.selectTab(0);
3386         Dom.get('_blank').innerHTML = "";
3387         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3388         SE.grid.params['ieId'] = node.data.id;
3389         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3390         SE.listView.refreshGrid();
3391     },
3392
3393     /**Mac
3394      * Sets sort order as user preference
3395      * @param
3396      */
3397     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3398         ieId = ieIdPassed;
3399         ieName = ieNamePassed;
3400         focusFolder = focusFolderPassed;
3401
3402         SE.util.clearHiddenFieldValues('emailUIForm');
3403         var previousSort = document.getElementById('sortBy').value;
3404
3405         document.getElementById('sortBy').value = sortBy;
3406         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3407         document.getElementById('focusFolder').value = focusFolder;
3408         document.getElementById('ieId').value = ieId;
3409
3410         if(sortBy == previousSort) {
3411             document.getElementById('reverse').value = '1';
3412         }
3413
3414         var formObject = document.getElementById('emailUIForm');
3415         YAHOO.util.Connect.setForm(formObject);
3416
3417         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3418     },
3419
3420
3421     /**
3422      * Enables click/arrow select of grid items which then populate the preview pane.
3423      */
3424     selectFirstRow : function() {
3425         SE.grid.selModel.selectFirstRow();
3426     },
3427
3428     selectLastRow : function() {
3429         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3430     },
3431
3432     setEmailListStyles : function() {
3433         SE.listView.boldUnreadRows();
3434         return;
3435         var ds = SE.grid.getStore();
3436         if (SE.grid.getSelections().length == 0) {
3437             document.getElementById('_blank').innerHTML = '';
3438         }
3439
3440         var acctMbox = '';
3441         if(typeof(ds.baseParams.mbox) != 'undefined') {
3442             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3443             var cm = SE.grid.getColumnModel();
3444             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3445                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3446                 //SE.grid.render();
3447             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3448                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3449                 //SE.grid.render();
3450             }
3451         }
3452         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3453         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3454
3455
3456         // 4/20/2007 added to hide overlay after search
3457         //hideOverlay();
3458         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3459             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3460             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3461             if (node) node.data.unseen = unread;
3462         }
3463         SE.accounts.renderTree();
3464
3465
3466         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3467         if(forcePreview && ds.totalCount > 0) {
3468             SE.detailView.getEmailPreview();
3469             forcePreview = false;
3470         }
3471     },
3472
3473     /**
3474      * Removes a row if found via its UID
3475      */
3476     removeRowByUid : function(uid) {
3477         uid = new String(uid);
3478         uids = uid.split(',');
3479         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3480
3481         for(j=0; j<uids.length; j++) {
3482             var theUid = uids[j];
3483             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3484                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3485                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3486                 }
3487             } // for
3488         }
3489     },
3490
3491     displaySelectedEmails : function(rows) {
3492         var dm = SE.grid.getDataModel();
3493         var uids = '';
3494
3495         for(i=0; i<rows.length; i++) {
3496             var rowIndex = rows[i].rowIndex;
3497             var metadata = dm.data[rowIndex];
3498
3499             if(uids != "") {
3500                 uids += ",";
3501             }
3502             uids += metadata[5];
3503
3504             // unbold unseen email
3505             this.unboldRow(rowIndex);
3506         }
3507
3508         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3509     },
3510
3511     /**
3512      * exception handler for data load failures
3513      */
3514     loadException : function(dataModel, ex, response) {
3515         //debugger;
3516     },
3517
3518     /**
3519      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3520      * @param string sourceIeId Email's source I-E id
3521      * @param string sourceFolder Email's current folder
3522      * @param destinationIeId Destination I-E id
3523      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3524      *
3525      * @param array emailUids Array of email's UIDs
3526      */
3527     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3528         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3529             overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3530         } else {
3531             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3532             // remove rows from visibility
3533             for(row in selectedRows) {
3534                 //SE.grid.getStore().remove(row);
3535             }
3536
3537             var baseUrl =    '&sourceIeId=' + sourceIeId +
3538                             '&sourceFolder=' + sourceFolder +
3539                             '&destinationIeId=' + destinationIeId +
3540                             '&destinationFolder=' + destinationFolder;
3541             var uids = '';
3542
3543             for(i=0; i<emailUids.length; i++) {
3544                 if(uids != '') {
3545                     uids += app_strings.LBL_EMAIL_DELIMITER;
3546                 }
3547                 uids += emailUids[i];
3548             }
3549             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3550                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3551             } else {
3552                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3553             }
3554         }
3555     },
3556
3557     /**
3558      * Unbolds text in the grid view to denote read status
3559      */
3560     markRead : function(index, record) {
3561         // unbold unseen email
3562         var row = SE.grid.getRecord(record);
3563         row.getData().seen = 1;
3564         SE.grid.getTrEl(record).style.fontWeight = "normal";
3565     },
3566
3567     /**
3568      * grid row output, bolding unread emails
3569      */
3570     boldUnreadRows : function() {
3571         // bold unread emails
3572         var trEl = SE.grid.getFirstTrEl();
3573         while(trEl != null) {
3574                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3575                         trEl.style.fontWeight = "bold";
3576                 else
3577                         trEl.style.fontWeight = "";
3578                 trEl = SE.grid.getNextTrEl(trEl);
3579         }
3580     },
3581
3582     /**
3583      * Show preview for an email if 1 and only 1 is selected
3584      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3585      */
3586     handleRowSelect : function(e) {
3587         if(e.selectedRows.length == 1) {
3588             SE.detailView.getEmailPreview();
3589         }
3590     },
3591
3592     handleDrop : function(e, dd, targetId, e2) {
3593         switch(targetId) {
3594             case 'htmleditordiv':
3595                 var rows = SE.grid.getSelectedRows();
3596                 if(rows.length > 0) {
3597                     SE.listView.displaySelectedEmails(rows);
3598                 }
3599             break;
3600
3601             default:
3602                 var targetElId = new String(targetId);
3603                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3604                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3605                 var dm = SE.grid.getDataModel();
3606                 var emailUids = new Array();
3607                 var destinationIeId = targetNode.data.ieId;
3608                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3609
3610
3611                 var rows = SE.grid.getSelectedRows();
3612                 // iterate through dragged rows
3613                 for(i=0; i<rows.length; i++) {
3614                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3615                     var rowIndex = rows[i].rowIndex;
3616                     var dataModelRow = dm.data[rowIndex];
3617                     var sourceIeId = dataModelRow[7];
3618                     var sourceFolder = dataModelRow[6];
3619                     emailUids[i] = dataModelRow[5];
3620                 }
3621
3622                 // event wrapped call - need FQ
3623                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3624                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3625             break;
3626         }
3627     },
3628
3629     /**
3630      * Hack-around to get double-click and single clicks to work on the grid
3631      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3632      */
3633     handleClick : function(o) {
3634         SUGAR.email2.grid.clearTextSelection();
3635
3636         var el = SUGAR.email2.grid.getSelectedRows();
3637
3638         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3639         if ( el.length == 1)
3640         {
3641            var rowId = el[0];
3642            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3643            SUGAR.email2.listView.currentRowIndex = rowId;
3644            clearTimeout(SUGAR.email2.detailView.previewTimer);
3645            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3646         }
3647     },
3648
3649     /**
3650      * Custom handler for double-click/enter
3651      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3652      */
3653     getEmail : function(e) {
3654         var rows = SE.grid.getSelectedRows();
3655         var row = SE.grid.getRecord(rows[0]).getData();
3656
3657         clearTimeout(SE.detailView.previewTimer);
3658         document.getElementById("_blank").innerHTML = "";
3659
3660         if(row.type != "draft") {
3661             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3662         } else {
3663             // circumventing yui-ext tab generation, let callback handler build new view
3664             SE.util.clearHiddenFieldValues('emailUIForm');
3665             //function(uid, mbox, ieId, setRead, destination) {
3666             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3667             document.getElementById('uid').value = row.uid; // uid;
3668             document.getElementById('mbox').value = row.mbox; // mbox;
3669             document.getElementById('ieId').value = row.ieId; // ieId;
3670
3671             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3672             AjaxObject.target = '_blank';
3673             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3674         }
3675     },
3676
3677     /**
3678      * Retrieves a row if found via its UID
3679      * @param string
3680      * @return int
3681      */
3682     getRowIndexByUid : function(uid) {
3683         uid = new String(uid);
3684         uids = uid.split(',');
3685
3686         for(j=0; j<uids.length; j++) {
3687             var theUid = uids[j];
3688
3689             for(i=0; i<SE.grid.getStore().data.length; i++) {
3690                 if(SE.grid.getStore().data[i].id == theUid) {
3691                     return i;
3692                 }
3693             }
3694         }
3695     },
3696
3697     /**
3698      * Returns the UID's of the seleted rows
3699      *
3700      */
3701      getUidsFromSelection : function() {
3702          var rows = SE.grid.getSelectedRows();
3703          var uids = [];
3704          /* iterate through available rows JIC a row is deleted - use first available */
3705          for(var i=0; i<rows.length; i++) {
3706                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3707          }
3708          return uids;
3709      },
3710
3711     refreshGrid : function() {
3712         SE.grid.getDataSource().sendRequest(
3713             SUGAR.util.paramsToUrl(SE.grid.params),
3714                 SE.grid.onDataReturnInitializeTable,
3715                 SE.grid
3716         );
3717     }
3718
3719 };
3720 ////    END SE.listView
3721 ///////////////////////////////////////////////////////////////////////////////
3722
3723 ///////////////////////////////////////////////////////////////////////////////
3724 ////    SEARCH
3725 SE.search = {
3726     /**
3727      * sends search criteria
3728      * @param reference element search field
3729      */
3730     search : function(el) {
3731         var searchCriteria = new String(el.value);
3732
3733         if(searchCriteria == '') {
3734             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3735             return false;
3736         }
3737
3738         var safeCriteria = escape(searchCriteria);
3739
3740         var accountListSearch = document.getElementById('accountListSearch');
3741         //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3742
3743         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3744         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3745         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3746         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3747         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3748
3749     },
3750
3751     /**
3752      * sends advanced search criteria
3753      */
3754     searchAdvanced : function() {
3755         var formObject = document.getElementById('advancedSearchForm');
3756         var search = false;
3757
3758         //Set assigned user id to blank if name is not present.
3759         if (formObject.elements['assigned_user_name'].value == "")
3760             formObject.elements['assigned_user_id'].value = "";
3761
3762         for(i=0; i<formObject.elements.length; i++) {
3763             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3764                 search = true;
3765             }
3766             if(formObject.elements[i].type == 'text') {
3767                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3768             }
3769             if(formObject.elements[i].type == 'hidden') {
3770                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3771             }
3772              if(formObject.elements[i].type == 'select-one') {
3773                 var el = formObject.elements[i];
3774                 var v = el.options[el.selectedIndex].value;
3775
3776                 if(v != "")
3777                     SE.grid.params[el.name] = v;
3778                 else
3779                 {
3780                     //Clear previous search results if necessary
3781                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3782                         delete SE.grid.params[el.name]
3783                 }
3784              }
3785         }
3786
3787         if (search)
3788         {
3789             if(! this.validateSearchFormInput() )
3790                 return;
3791
3792                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3793                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3794                 var accountListSearch = document.getElementById('accountListSearch');
3795                 SE.listView.refreshGrid();
3796         } else {
3797             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3798         }
3799     },
3800
3801     /**
3802     *  Validates the search form inputs to ensure all parameters are valid
3803     *  @return bool
3804     */
3805     validateSearchFormInput: function()
3806     {
3807         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3808         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3809         var dateCheck = check_form('advancedSearchForm');
3810
3811         //If the parent type is selected ensure the user selected a parent_id.
3812         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3813             return true;
3814         else
3815             return false;
3816     },
3817     /**
3818     *   Toggles the advanced options, either hidding or showing the selection.
3819     */
3820     toggleAdvancedOptions: function()
3821     {
3822         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3823
3824         for(var i=0;i<el.length;i++)
3825         {
3826             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3827                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3828             else
3829                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3830         }
3831     },
3832     /**
3833      * clears adv search form fields
3834      */
3835     searchClearAdvanced : function() {
3836         var form = document.getElementById('advancedSearchForm');
3837
3838         for(i=0; i<form.elements.length; i++) {
3839             if(form.elements[i].type != 'button') {
3840                 form.elements[i].value = '';
3841             }
3842         }
3843     }
3844 };
3845 ////    END SE.search
3846 //////////////////////////////////////////////////////////////////////////////
3847
3848
3849 //////////////////////////////////////////////////////////////////////////////
3850 ////    SE.settings
3851 SE.settings = {
3852     /******************************************************************************
3853      * USER SIGNATURES calls stolen from Users module
3854      *****************************************************************************/
3855     createSignature : function(record, the_user_id) {
3856         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3857         if(record != "") {
3858             URL += "&record="+record;
3859         }
3860         if(the_user_id != "") {
3861             URL += "&the_user_id="+the_user_id;
3862         }
3863         var windowName = 'email_signature';
3864         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3865
3866         var win = window.open(URL, windowName, windowFeatures);
3867         if(win && win.focus) {
3868             // put the focus on the popup if the browser supports the focus() method
3869             win.focus();
3870         }
3871     },
3872
3873     deleteSignature : function() {
3874         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3875             overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3876                 var singature_id = document.getElementById('signature_id').value;
3877                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3878         } // if
3879     },
3880
3881     saveOptionsGeneral :  function(displayMessage) {
3882         var formObject = document.getElementById('formEmailSettingsGeneral');
3883         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3884                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3885                 return false;
3886         } // if
3887         YAHOO.util.Connect.setForm(formObject);
3888         SE.composeLayout.emailTemplates = null;
3889
3890         AjaxObject.target = 'frameFlex';
3891         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3892
3893         if(displayMessage)
3894             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3895
3896         SE.settings.settingsDialog.hide();
3897     },
3898
3899     /**
3900      * Shows settings container screen
3901      */
3902     showSettings : function() {
3903         if(!SE.settings.settingsDialog) {
3904                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3905                 modal:true,
3906                 visible:false,
3907                 fixedcenter:true,
3908                 draggable: false,
3909                 width:"800px",
3910                                 constraintoviewport: true
3911             });
3912                         dlg.showEvent.subscribe( function (){
3913                                 var el = this.element;
3914                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3915                 if (this.header && el && viewH - 50 < el.clientHeight) {
3916                     var body = this.header.nextElementSibling;
3917                                         body.style.overflow = "auto";
3918                     body.style.height = (viewH - 50) + "px";
3919                 }
3920             }, dlg);
3921                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3922                 dlg.setBody('<div id="settingsTabDiv"/>');
3923                 dlg.beforeRenderEvent.subscribe(function() {
3924                         var dd = new YAHOO.util.DDProxy(dlg.element);
3925                         dd.setHandleElId(dlg.header);
3926                         dd.on('endDragEvent', function() {
3927                                 dlg.show();
3928                         });
3929                 }, dlg, true);
3930                 dlg.render();
3931
3932                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3933                         var tabContent = Dom.get("tab_general");
3934                 tp.addTab(new YAHOO.widget.Tab({
3935                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3936                                 scroll : true,
3937                                 content :  tabContent.innerHTML,
3938                                 id : "generalSettings",
3939                                 active : true
3940                         }));
3941                 tabContent.parentNode.removeChild(tabContent);
3942                 tabContent = Dom.get("tab_accounts");
3943                 var accountTab = new YAHOO.widget.Tab({
3944                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3945                                 scroll : true,
3946                                 content : tabContent.innerHTML,
3947                                 id : "accountSettings"
3948                         });
3949                 tp.addTab(accountTab);
3950                 tabContent.parentNode.removeChild(tabContent);
3951
3952                         tp.appendTo(dlg.body);
3953         }
3954
3955         SE.settings.settingsDialog.show();
3956         SE.folders.lazyLoadSettings();
3957         SE.accounts.lazyLoad();
3958     },
3959
3960
3961     lazyLoadRules : function() {
3962         if(false/*!SE.settings.rules*/) {
3963             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3964         }
3965
3966     }
3967 };
3968 ////    END SE.settings
3969 ///////////////////////////////////////////////////////////////////////////////
3970 })();
3971
3972 /******************************************************************************
3973  * UTILITIES
3974  *****************************************************************************/
3975 function removeHiddenNodes(nodes, grid) {
3976     var el;
3977         for(var i = nodes.length - 1; i > -1; i--) {
3978         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3979         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3980                 nodes.splice(i,1);
3981        }
3982     }
3983 }
3984
3985 function strpad(val) {
3986     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3987 };
3988
3989 function refreshTodos() {
3990     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3991     AjaxObject.target = 'todo';
3992     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3993 };
3994
3995 /******************************************************************************
3996  * MUST STAY IN GLOBAL NAMESPACE
3997  *****************************************************************************/
3998 function refresh_signature_list(signature_id, signature_name) {
3999     var field=document.getElementById('signature_id');
4000     var bfound=0;
4001     for (var i=0; i < field.options.length; i++) {
4002             if (field.options[i].value == signature_id) {
4003                 if (field.options[i].selected==false) {
4004                     field.options[i].selected=true;
4005                 }
4006                 bfound=1;
4007             }
4008     }
4009     //add item to selection list.
4010     if (bfound == 0) {
4011         var newElement=document.createElement('option');
4012         newElement.text=signature_name;
4013         newElement.value=signature_id;
4014         field.options.add(newElement);
4015         newElement.selected=true;
4016     }
4017
4018     //enable the edit button.
4019     var field1=document.getElementById('edit_sig');
4020     field1.style.visibility="inherit";
4021     var deleteButt = document.getElementById('delete_sig');
4022     deleteButt.style.visibility="inherit";
4023 };
4024
4025 function setDefaultSigId(id) {
4026     var checkbox = document.getElementById("signature_default");
4027     var default_sig = document.getElementById("signatureDefault");
4028
4029     if(checkbox.checked) {
4030         default_sig.value = id;
4031     } else {
4032         default_sig.value = "";
4033     }
4034 };
4035
4036 function setSigEditButtonVisibility() {
4037     var field = document.getElementById('signature_id');
4038     var editButt = document.getElementById('edit_sig');
4039     var deleteButt = document.getElementById('delete_sig');
4040     if(field.value != '') {
4041         editButt.style.visibility = "inherit";
4042         deleteButt.style.visibility = "inherit";
4043     } else {
4044         editButt.style.visibility = "hidden";
4045         deleteButt.style.visibility = "hidden";
4046     }
4047 }// End of File modules/Emails/javascript/EmailUI.js
4048                                 
4049 /*********************************************************************************
4050  * SugarCRM Community Edition is a customer relationship management program developed by
4051  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4052  * 
4053  * This program is free software; you can redistribute it and/or modify it under
4054  * the terms of the GNU Affero General Public License version 3 as published by the
4055  * Free Software Foundation with the addition of the following permission added
4056  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4057  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4058  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4059  * 
4060  * This program is distributed in the hope that it will be useful, but WITHOUT
4061  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4062  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4063  * details.
4064  * 
4065  * You should have received a copy of the GNU Affero General Public License along with
4066  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4067  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4068  * 02110-1301 USA.
4069  * 
4070  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4071  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4072  * 
4073  * The interactive user interfaces in modified source and object code versions
4074  * of this program must display Appropriate Legal Notices, as required under
4075  * Section 5 of the GNU Affero General Public License version 3.
4076  * 
4077  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4078  * these Appropriate Legal Notices must retain the display of the "Powered by
4079  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4080  * technical reasons, the Appropriate Legal Notices must display the words
4081  * "Powered by SugarCRM".
4082  ********************************************************************************/
4083
4084  (function() {
4085         var sw = YAHOO.SUGAR,
4086                 Event = YAHOO.util.Event,
4087                 Connect = YAHOO.util.Connect,
4088             Dom = YAHOO.util.Dom
4089             SE = SUGAR.email2;
4090
4091 ///////////////////////////////////////////////////////////////////////////////
4092 ////    ADDRESS BOOK
4093 SE.addressBook = {
4094     _contactCache : new Array(), // cache of contacts
4095     _dd : new Array(), // filtered list, same format as _contactCache
4096     _ddLists : new Array(), // list of Lists
4097     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4098     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4099     clickBubble : true, // hack to get around onclick event bubbling
4100         relatedBeanId : '',
4101         relatedBeanType : '',
4102         idx : 0,
4103
4104     itemSpacing : 'white-space:nowrap; padding:2px;',
4105     reGUID : SE.reGUID,
4106
4107
4108
4109     /**
4110     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4111     */
4112     initFixForDatatableSort: function () {
4113         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4114         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4115             var oColumn = this._oColumnSet.getColumn(column);
4116
4117             if(!oColumn) {
4118                 // Validate TD element
4119                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4120                 if(elCell) {
4121                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4122                 }
4123                 // Validate TH element
4124                 else {
4125                     elCell = this.getThEl(column);
4126                     if(elCell) {
4127                         // Find by TH el ID
4128                         var allColumns = this._oColumnSet.flat;
4129                         for(var i=0, len=allColumns.length; i<len; i++) {
4130                             if(allColumns[i].getThEl().id === elCell.id) {
4131                                 oColumn = allColumns[i];
4132                             }
4133                         }
4134                     }
4135                 }
4136             }
4137
4138             return oColumn;
4139         };
4140     },
4141
4142     cancelEdit : function() {
4143         if(this.editContactDialog)
4144             this.editContactDialog.hide();
4145         if(this.editMailingListDialog)
4146             this.editMailingListDialog.hide();
4147     },
4148
4149     /**
4150      * Clears filter form
4151      */
4152     clear : function() {
4153         var t = document.getElementById('contactsFilter');
4154         t.value = '';
4155         this.filter(t);
4156     },
4157
4158     /**
4159      * handle context-menu Compose-to call
4160      * @param string type 'contacts' or 'lists'
4161      */
4162     composeTo : function(type, waited) {
4163         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4164         if (activePanel.substring(0, 10) != "composeTab") {
4165             SE.composeLayout.c0_composeNewEmail();
4166             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4167                 SE.contextMenus.contactsContextMenu.hide();
4168             return;
4169         }
4170         var idx = activePanel.substring(10);
4171         var rows = [ ];
4172         var id = '';
4173         // determine if we have a selection to work with
4174         if(type == 'contacts') {
4175             var ids = SE.contactView.getSelectedRows();
4176             for (var i in ids) {
4177                 rows[i] = SE.contactView.getRecord(ids[i]);
4178             }
4179             removeHiddenNodes(rows, SE.contactView);
4180         }
4181                 else { return; }
4182
4183         if(rows.length > 0) {
4184             SE.composeLayout.handleDrop(
4185                 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4186                 null, rows, 'addressTO' + idx );
4187         } else {
4188             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4189         }
4190     },
4191
4192     editContact : function() {
4193         SE.contextMenus.contactsContextMenu.hide();
4194         var element = SE.contactView.getSelectedNodes()[0];
4195         var elementId = "";
4196         if (element.className.indexOf('address-contact') > -1) {
4197             elementId = element.id;
4198         } else if (element.className.indexOf('address-exp-contact') > -1) {
4199             elementId = element.id.substring(2);
4200         }
4201     },
4202
4203
4204     /**
4205      * Filters contact entries based on user input
4206      */
4207     filter : function(inputEl) {
4208         var ret = new Object();
4209         var re = new RegExp(inputEl.value, "gi");
4210
4211         for(var i in this._contactCache) {
4212             if(this._contactCache[i].name.match(re)) {
4213                 ret[i] = this._contactCache[i];
4214             }
4215         }
4216
4217         this.buildContactList(ret);
4218     },
4219
4220     fullForm : function(id, module) {
4221         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4222     },
4223
4224     /**
4225      * returns a formatted email address from the addressBook cache
4226      */
4227     getFormattedAddress : function(id) {
4228         var o = this._contactCache[id];
4229         var primaryEmail = '';
4230
4231         for(var i=0; i<o.email.length; i++) {
4232             var currentEmail = o.email[i].email_address;
4233
4234             if(o.email[i].primary_address == 1) {
4235                 primaryEmail = o.email[i].email_address;
4236             }
4237         }
4238
4239         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4240         var name = new String(o.name);
4241         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4242         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4243
4244         return ret;
4245     },
4246
4247     /**
4248      * Sets up async call to query for matching contacts, users, etc.
4249      */
4250     searchContacts : function() {
4251         var fn = document.getElementById('input_searchField').value;
4252         var pe = document.getElementById('input_searchPerson').value;
4253
4254         var rb = document.getElementById('hasRelatedBean').checked;
4255         if (rb) {
4256                         var idx = this.idx;
4257                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4258                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4259                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4260                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4261         } else {
4262                 this.addressBookDataModel.params['related_bean_id'] = '';
4263         }
4264
4265         this.addressBookDataModel.params['search_field'] = fn;
4266         this.addressBookDataModel.params['person'] = pe;
4267         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4268         this.grid._oDataSource = this.addressBookDataModel;
4269         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4270     },
4271
4272     /**
4273      * Clear Search Crieteria For Addressbook
4274      */
4275     clearAddressBookSearch : function() {
4276         document.getElementById('input_searchField').value = "";
4277         document.getElementById('input_searchPerson').selectedIndex = 0;
4278     },
4279
4280     /**
4281      * Opens modal select window to add contacts to addressbook
4282      */
4283     selectContactsDialogue : function(destId) {
4284         if(!this.contactsDialogue) {
4285                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4286                 modal:true,
4287                 visible:false,
4288                 draggable: false,
4289                 constraintoviewport: true,
4290                 width   : 980,
4291                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4292                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4293             });
4294                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4295
4296                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4297                 dlg.setBody(body.innerHTML);
4298                 dlg.renderEvent.subscribe(function() {
4299                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4300                 if (iev && !SUGAR.isIE) {
4301                         this.body.style.width = "950px";
4302                 }
4303             }, dlg);
4304
4305
4306                 dlg.beforeRenderEvent.subscribe(function() {
4307                         var dd = new YAHOO.util.DDProxy(dlg.element);
4308                         dd.setHandleElId(dlg.header);
4309                         dd.on('endDragEvent', function() {
4310                                 dlg.show();
4311                         });
4312                 }, dlg, true);
4313                 dlg.render();
4314
4315                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4316
4317                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4318                 tp.addTab(new YAHOO.widget.Tab({
4319                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4320                                 scroll : true,
4321                                 content : tabContent.innerHTML,
4322                                 id : "addressSearchTab",
4323                                 active : true
4324                         }));
4325
4326                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4327                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4328                         if (e.keyCode == 13) {
4329                                 YAHOO.util.Event.stopEvent(e);
4330                                 SUGAR.email2.addressBook.searchContacts();
4331                         }
4332                 });
4333
4334                 this.contactsDialogue.render();
4335                 dlg.center();
4336         }
4337         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4338         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4339             var idx = 0;
4340         else
4341         {
4342             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4343             var idx = activePanel.substring(10);
4344         }
4345         SE.addressBook.idx = idx;
4346
4347                 var relatedBeanId;
4348         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4349                 document.getElementById('relatedBeanColumn').style.display = '';
4350                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4351                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4352                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4353                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4354                         SE.addressBook.relatedBeanType = relatedBeanType;
4355             } else {
4356                 document.getElementById('relatedBeanColumn').style.display = 'none';
4357                 document.getElementById('hasRelatedBean').checked = false;
4358             }
4359
4360             if (!SE.addressBook.grid)
4361             {
4362                 if (hasRelatedBeanId) {
4363                         document.getElementById('hasRelatedBean').checked = true;
4364                 }
4365                 AddressSearchGridInit();
4366                         SE.addressBook.relatedBeanId = relatedBeanId;
4367             }
4368             else
4369             {
4370                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4371                 {
4372                         SE.addressBook.relatedBeanId = relatedBeanId;
4373                         document.getElementById('hasRelatedBean').checked = true;
4374                 }
4375                 if (document.getElementById('hasRelatedBean').checked == true)
4376                 {
4377                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4378                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4379                 } else {
4380                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4381                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4382                 }
4383                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4384                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4385                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4386             }
4387
4388             //Remove any lingering rows in the result set table if the module was closed.
4389             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4390             //Repopulate
4391             SE.addressBook.populateResulstTableEmailAddresses();
4392
4393         this.contactsDialogue.show();
4394     },
4395     /**
4396     *  Clear all email addresses from result table.
4397     *
4398     */
4399     clearAllEmailAddressFieldsFromResultTable: function () {
4400         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4401         //Unhighlight any rows currently selected if the emails were cleared.
4402         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4403         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4404     },
4405     /**
4406     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4407     *  results table.  This function is called when the address book is displayed.
4408     */
4409     populateResulstTableEmailAddresses: function () {
4410
4411         var idx = SE.addressBook.idx;
4412         var emailFields = ['to','cc','bcc'];
4413
4414         for(var k=0;k<emailFields.length;k++)
4415         {
4416             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4417             var allEmails = document.getElementById(elKey).value;
4418             if(allEmails == '')
4419                 continue;
4420
4421             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4422
4423                 for (var i=0; i<formatedEmails.length; i++)
4424                 {
4425                     var t_name = formatedEmails[i].name;
4426                     var t_emailAddr = formatedEmails[i].email_address;
4427                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4428                     if(t_name == '')
4429                         t_name = displayEmail = t_emailAddr;
4430
4431                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4432                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4433                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4434                 }
4435         }
4436     },
4437
4438     /**
4439     * Checks all entries in the result table against a particular email address, returning true
4440     * if the email address is found, false otherwise.
4441     */
4442     doesEmailAdddressExistInResultTable: function(emailAddress)
4443     {
4444         if(trim(emailAddress) == '')
4445             return false;
4446
4447         var emailAddressFound = false;
4448         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4449         for (var i=0; i < contacts.length; i++)
4450         {
4451             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4452             //If we are adding to cc or bcc fields, make them visible.
4453             if(data.email_address == emailAddress)
4454             {
4455                 emailAddressFound = true;
4456                 break;
4457             }
4458         }
4459
4460         return emailAddressFound;
4461     },
4462     /**
4463     *  Takes all email addresses that the users wishes to add from the address book and populates the To
4464     *  fields on the compose tab.
4465     */
4466     populateEmailAddressFieldsFromResultTable: function()
4467     {
4468         //Clear the fields first, all email addresses are stored in the address book
4469         var idx = SE.addressBook.idx;
4470         var emailFields = ['to','cc','bcc'];
4471         for(var k=0;k<emailFields.length;k++)
4472         {
4473             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4474             document.getElementById(elKey).value = "";
4475         }
4476
4477         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4478         for (var i=0; i < contacts.length; i++)
4479         {
4480             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4481
4482             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4483             //If we are adding to cc or bcc fields, make them visible.
4484             if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4485                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4486             //Construct the target id
4487             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4488
4489             var target = document.getElementById(target_id);
4490             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4491         }
4492
4493         //Delete all rows from the result set table
4494         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4495
4496         //Hide the dialogue
4497         SE.addressBook.contactsDialogue.hide()
4498     },
4499     /**
4500     *  Insert contacts into the result table.
4501     */
4502     insertContactToResultTable : function(event,address_type) {
4503
4504         var contactsDialogue = SE.addressBook.contactsDialogue;
4505         var contacts = SE.addressBook.grid.getSelectedRows();
4506
4507         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4508         for (var i = 0; i < rows.length; i++)
4509         {
4510                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4511                         {
4512                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4513                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4514                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4515                 rows[i].setData("selected",true);
4516                         }
4517         }
4518         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4519         for (var i = 0; i < checkBoxes.length; i++) {
4520             checkBoxes[i].checked = false;
4521         }
4522     },
4523     /**
4524     *
4525     */
4526     insertContactRowToResultTable : function(rowId, addressType) {
4527         var data = SE.addressBook.grid.getRecord(rowId).getData();
4528         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4529                 return;
4530         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4531         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4532         if(addressType == null)
4533             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4534         SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':name,'email_address': data.email,'display_email_address': ea,'bean_id': data.bean_id,'idx' : SE.addressBook.idx});
4535     },
4536     /**
4537     * Remove a row from the gridsResult table.
4538     */
4539     removeRowFromGridResults : function(rowId,emailAddress)
4540     {
4541         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4542         for (var i=0; i < contacts.length; i++)
4543         {
4544             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4545             var data = rec.getData();
4546             if(data.email_address == emailAddress)
4547             {
4548                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4549                 break;
4550             }
4551         }
4552
4553        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4554     },
4555     /**
4556     * Translates between the addressType To|Cc|Bcc labels/keys.
4557     */
4558     translateAddresType: function(addressType,fromKey)
4559     {
4560         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4561         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4562         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4563         var mappingObject = {};
4564
4565         if(fromKey)
4566             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4567         else
4568         {
4569             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4570             mappingObject[displayCc] = 'cc';
4571             mappingObject[displayBcc] = 'bcc';
4572         }
4573
4574         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4575
4576     },
4577     /**
4578     *
4579     */
4580     toggleSearchRowIcon : function(rowId,show)
4581     {
4582         if(show)
4583         {
4584             var idToShow = rowId + '_add_img';
4585             var idToHide = rowId + '_rm_img';
4586         }
4587         else
4588         {
4589             var idToShow = rowId + '_rm_img';
4590             var idToHide = rowId + '_add_img';
4591         }
4592
4593
4594         Dom.addClass(idToHide, "yui-hidden");
4595         Dom.removeClass(idToShow, "yui-hidden");
4596     },
4597     /**
4598     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4599     */
4600     doesGridResultsEntryExist: function(emailAddrs)
4601     {
4602
4603         var contactExists = false;
4604         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4605         for (var i=0; i < contacts.length; i++)
4606         {
4607             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4608             if(data.email_address == emailAddrs)
4609             {
4610                 contactExists = true;
4611                 break;
4612             }
4613         }
4614         return contactExists;
4615     },
4616
4617     /**
4618      * adds an email address to a string, but first checks if it exists
4619      * @param string concat The string we are appending email addresses to
4620      * @param string addr Email address to add
4621      * @return string
4622      */
4623     smartAddEmailAddressToComposeField : function(concat, addr) {
4624         var re = new RegExp(addr);
4625
4626         if(!concat.match(re)) {
4627             if(concat != "") {
4628                 concat += "; " + addr;
4629             } else {
4630                 concat = addr;
4631             }
4632         }
4633
4634         return concat;
4635     }
4636 };
4637 ////    END ADDRESS BOOK
4638 ///////////////////////////////////////////////////////////////////////////////
4639
4640
4641
4642 ///////////////////////////////////////////////////////////////////////////////
4643 ////    AUTOCOMPLETE
4644 /**
4645  * Auto-complete object
4646  */
4647 SE.autoComplete = {
4648     config : {
4649         delimChar : [";", ","],
4650         useShadow :    false,
4651         useIFrame : false,
4652         typeAhead : true,
4653         prehighlightClassName : "yui-ac-prehighlight",
4654         queryDelay : 0
4655     },
4656     instances : new Array(),
4657
4658     /**
4659      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4660      * @param object Contact from AddressBook
4661      * @return string
4662      */
4663     getPrimaryAddress : function(contact) {
4664         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4665
4666         for(var eIndex in contact.email) {
4667             address = contact.email[eIndex].email_address;
4668             if(contact.email[eIndex].primary_address == 1) {
4669                 return contact.email[eIndex].email_address;
4670             }
4671         }
4672         return address;
4673     },
4674
4675
4676     /**
4677      * initializes autocomplete widgets for a given compose view
4678      * @param int idx
4679      */
4680     init : function(idx) {
4681         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4682             "queryMatchContains" : false,
4683             "queryMatchSubset" : true
4684         });
4685
4686         this.instances[idx] = {
4687             to : null,
4688             cc : null,
4689             bcc : null
4690         };
4691
4692
4693         // instantiate the autoComplete widgets
4694         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4695         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4696         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4697
4698         // enable hiding of interfering textareas
4699         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4700         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4701         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4702
4703         // enable reshowing of hidden textareas
4704         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4705         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4706         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4707
4708         // enable refreshes of contact lists
4709         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4710         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4711         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4712     },
4713
4714     refreshDataSource : function(sType, aArgs) {
4715         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4716         var idx;
4717         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4718
4719         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4720             idx = textBoxId.substr(9);
4721         } else {
4722             idx = textBoxId.substr(10);
4723         }
4724
4725         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4726         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4727         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4728     },
4729
4730     /**
4731      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4732      */
4733     returnDataSource : function(contacts) {
4734         var ret = new Array();
4735         for(var id in contacts) {
4736             if (contacts[id].name) {
4737                     var primary = this.getPrimaryAddress(contacts[id]);
4738
4739                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4740                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4741
4742                     for(var emailIndex in contacts[id].email) {
4743                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4744                     }
4745             }
4746         }
4747
4748         return ret;
4749     },
4750
4751     /**
4752      * Hides address textareas to prevent autocomplete dropdown from being obscured
4753      */
4754     toggleTextareaHide : function(sType, aArgs) {
4755         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4756         var type = "";
4757         var idx = -1;
4758
4759         if(textBoxId.indexOf("addressTO") > -1) {
4760             type = "to";
4761         } else if(textBoxId.indexOf("addressCC") > -1) {
4762             type = "cc";
4763         }
4764         idx = textBoxId.substr(9);
4765
4766         // follow through if not BCC
4767         if(type != "") {
4768             var cc = document.getElementById("addressCC" + idx);
4769             var bcc = document.getElementById("addressBCC" + idx);
4770
4771             switch(type) {
4772                 case "to":
4773                     cc.style.visibility = 'hidden';
4774                 case "cc":
4775                     bcc.style.visibility = 'hidden';
4776                 break;
4777             }
4778         }
4779     },
4780
4781     /**
4782      * Redisplays the textareas after an address is commited
4783      */
4784     toggleTextareaShow : function(sType, aArgs) {
4785         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4786         var type = "";
4787         var idx = -1;
4788
4789         if(textBoxId.indexOf("addressTO") > -1) {
4790             type = "to";
4791         } else if(textBoxId.indexOf("addressCC") > -1) {
4792             type = "cc";
4793         }
4794         idx = textBoxId.substr(9);
4795
4796         // follow through if not BCC
4797         if(type != "") {
4798             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4799             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4800         }
4801     }
4802 };
4803
4804 ////    END AUTOCOMPLETE
4805 ///////////////////////////////////////////////////////////////////////////////
4806
4807 ///////////////////////////////////////////////////////////////////////////////
4808 ////    COMPOSE & SEND
4809 /**
4810  * expands the options sidebar
4811  */
4812 SE.composeLayout = {
4813     currentInstanceId : 0,
4814     ccHidden : true,
4815     bccHidden : true,
4816     outboundAccountErrors : null,
4817     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4818
4819     showAddressDetails : function(e) {
4820         var linkElement = document.getElementById("More"+e.id);
4821         var spanElement = document.getElementById("Detail"+e.id);
4822         var emailAddressList = e.value;
4823         if(e.value.length > 96)
4824         {
4825                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4826             var displayArray = [];
4827                 for (var i=0; i<resultArray.length; i++)
4828                 {
4829                     var t_name = resultArray[i].name;
4830                     var t_emailAddr = resultArray[i].email_address;
4831                     if(t_name == '')
4832                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4833                     else
4834                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');
4835                 }
4836
4837             var result = displayArray.join('<br/>');
4838                 // Display
4839             linkElement.style.display = "inline";
4840             linkElement.style.height="10px";
4841             linkElement.style.overflow="visible";
4842             spanElement.innerHTML = result;
4843         }
4844         else
4845                 linkElement.style.display = "none";
4846
4847         },
4848
4849    /**
4850     *  Given a string of email address, return an array containing the name portion (if available)
4851     *  and email portion.
4852     */
4853     _getEmailArrayFromString : function (emailAddressList){
4854
4855         var reg = /@.*?;/g;
4856         while ((results = reg.exec(emailAddressList)) != null)
4857         {
4858             orignial = results[0];
4859             parsedResult = results[0].replace(';', ':::::');
4860             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4861         }
4862
4863         reg = /@.*?,/g;
4864         while ((results = reg.exec(emailAddressList)) != null)
4865         {
4866             orignial = results[0];
4867             parsedResult = results[0].replace(',', ':::::');
4868             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4869         }
4870         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4871         var emailArr = emailAddressList.split(":::::");
4872         var resultsArray = [];
4873         var newArr = [];
4874         for (var i=0; i<emailArr.length; i++)
4875         {
4876             var rposition = emailArr[i].indexOf('<');
4877             var lposition = emailArr[i].indexOf('>');
4878
4879             if(trim(emailArr[i]) != '')
4880             {
4881                 if(rposition != -1 && lposition != -1)
4882                 {
4883                     var t_name = emailArr[i].substr(0, rposition-1);
4884                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4885                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4886                 }
4887                 else
4888                 {
4889                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4890                 }
4891             }
4892         }
4893         return resultsArray;
4894     },
4895     ///////////////////////////////////////////////////////////////////////////
4896     ////    COMPOSE FLOW
4897     /**
4898      * Prepare bucket DIV and yui-ext tab panels
4899      */
4900     _0_yui : function() {
4901         var idx = this.currentInstanceId;
4902
4903         var composeTab = new YAHOO.SUGAR.ClosableTab({
4904                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4905                                 scroll : true,
4906                                 content : "<div id='htmleditordiv" + idx + "'/>",
4907                                 id : "composeTab" + idx,
4908                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4909                                 active : true
4910         }, SE.innerLayout);
4911         SE.innerLayout.addTab(composeTab);
4912
4913         // get template engine with template
4914         if (!SE.composeLayout.composeTemplate) {
4915                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4916         }
4917
4918         // create Tab inner layout
4919         var composePanel =  this.getComposeLayout();
4920         composePanel.getUnitByPosition("right").collapse();
4921         composePanel.autoSize();
4922
4923     },
4924         /**
4925      * Generate the quick compose layout
4926          * @method getQuickComposeLayout
4927          * @param {Pannel} parentPanel Parent pannel
4928          * @param {Object} o Options
4929          * @return {} none
4930          **/
4931     getQuickComposeLayout : function (parentPanel,o) {
4932          var idx = SE.composeLayout.currentInstanceId;
4933
4934          //Before rendering the parent pannel we need to initalize the grid layout
4935          parentPanel.beforeRenderEvent.subscribe(function() {
4936
4937                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4938                         SE.composeLayout._createComposeLayout(idx);
4939                         SE.composeLayout[idx].set('height', 350);
4940                         SE.composeLayout[idx].render();
4941            });
4942         });
4943
4944          //Wait until the Compose Layout has rendered, then add the
4945          //options tab and perform the tiny initialization.
4946          parentPanel.renderEvent.subscribe(function() {
4947
4948                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4949                 SE.composeLayout._initComposeOptionTabs(idx);
4950                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4951                 //Initialize tinyMCE
4952                 if (!SUGAR.util.isTouchScreen())
4953                     SE.composeLayout._1_tiny(false);
4954                 //Init templates and address book
4955                 SE.composeLayout._2_final();
4956
4957             SE.composeLayout.quickCreateComposePackage(o);
4958
4959                 });
4960          });
4961
4962             //Check if we have the div override for the shortcut bar
4963         if(typeof o.menu_id != 'undefined') {
4964                    parentPanel.render(o.menu_id);
4965             } else {
4966                    parentPanel.render(document.body);
4967             }
4968
4969         return SE.composeLayout[idx];
4970     },
4971     /**
4972      * Fill in all fields into the quick compose layout.
4973          * @method quickCreateComposePackage
4974          * @param {Object} o Options
4975          * @return {} none
4976          **/
4977     quickCreateComposePackage: function(o)
4978     {
4979         //If we have a compose package fill in defaults.
4980         if (typeof(o.composePackage) != 'undefined')
4981         {
4982             composePackage = o.composePackage; //Set the compose data object
4983             //Hijack this method called by composePackage as it's not need for quick creates.
4984             SE.composeLayout.c0_composeNewEmail = function(){};
4985             SE.composeLayout.composePackage(); //Fill in defaults.
4986         }
4987     },
4988     getComposeLayout : function() {
4989         var idx = SE.composeLayout.currentInstanceId;
4990
4991         this._createComposeLayout(idx);
4992         SE.composeLayout[idx].render();
4993         this._initComposeOptionTabs(idx);
4994
4995         return SE.composeLayout[idx];
4996         },
4997
4998         /**
4999         *       Create the layout manager for the compose window.
5000         */
5001         _createComposeLayout : function(idx)
5002         {
5003                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
5004                 parent: SE.complexLayout,
5005                 border:true,
5006             hideOnLayout: true,
5007             height: 400,
5008                         units: [{
5009                                         position: "center",
5010                         animate: false,
5011                         scroll: false,
5012                         split:true,
5013                         body:
5014                                 SE.composeLayout.composeTemplate.exec({
5015                                 'app_strings':app_strings,
5016                                 'mod_strings':mod_strings,
5017                                 'theme': theme,
5018                                 'linkbeans_options' : linkBeans,
5019                                 'idx' : SE.composeLayout.currentInstanceId
5020                                 })
5021                     },{
5022                         position: "right",
5023                                     scroll:true,
5024                                     collapse: true,
5025                                     collapsed: true,
5026                                     resize: true,
5027                                     border:true,
5028                                     animate: false,
5029                                     width:'230',
5030                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5031                                     titlebar: true,
5032                                     split: true,
5033                                     header: app_strings.LBL_EMAIL_OPTIONS
5034                     }]
5035                 });
5036         },
5037
5038         /**
5039         *  Create compose tab which will populate the 'right' container in the compose window.
5040         */
5041         _initComposeOptionTabs : function(idx)
5042         {
5043                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5044                 var tab = new YAHOO.widget.Tab({
5045                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5046                                 scroll : true,
5047                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5048                                 id : "divAttachments" + idx,
5049                                 active : true
5050                         });
5051
5052                 tab.layout = SE.composeLayout[idx];
5053
5054            tab.on("activeChange", function(o){
5055                         if (o.newValue) {
5056                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5057                         }
5058                 });
5059
5060                 cTabs.addTab(tab);
5061
5062                 tab = new YAHOO.widget.Tab({
5063                                 label: app_strings.LBL_EMAIL_OPTIONS,
5064                                 scroll : true,
5065                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5066                                 id : "divOptions" + idx,
5067                                 active : false
5068                         });
5069
5070                 tab.layout = SE.composeLayout[idx];
5071                 tab.on("activeChange", function(o){
5072                         if (o.newValue) {
5073                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5074                         }
5075                 });
5076                 cTabs.addTab(tab);
5077
5078                 SE.composeLayout[idx].autoSize = function() {
5079                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5080                         this.set("height", pEl.clientHeight-30);
5081                         this.render();
5082                 }
5083
5084                 SE.composeLayout[idx].rightTabs = cTabs;
5085     },
5086     isParentTypeValid : function(idx) {
5087                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5088                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5089                 if (trim(parentTypeValue) == ""){
5090                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5091                         return false;
5092                 } // if
5093                 return true;
5094     },
5095
5096     isParentTypeAndNameValid : function(idx) {
5097                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5098                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5099                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5100                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5101                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5102                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5103                         return false;
5104                 } // if
5105                 return true;
5106     },
5107
5108     callopenpopupForEmail2 : function(idx,options) {
5109
5110         var formName = 'emailCompose' + idx;
5111
5112         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5113             formName = options.form_name;
5114
5115                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5116                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5117                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5118                         return;
5119                 } // if
5120                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5121                 {
5122                         call_back_function:"SE.composeLayout.popupAddEmail",
5123                         form_name:formName,
5124                         field_to_name_array:{
5125                                 id:'data_parent_id' + idx,
5126                                 name:'data_parent_name' + idx,
5127                                 email1:'email1'}
5128                 });
5129         },
5130
5131         popupAddEmail : function(o)
5132         {
5133                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5134                 var data = o.name_to_value_array;
5135                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5136                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5137         {
5138                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5139                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5140         }
5141                 set_return(o);
5142         },
5143     /**
5144      * Prepare TinyMCE
5145      */
5146     _1_tiny : function(isReplyForward) {
5147         var idx = SE.composeLayout.currentInstanceId;
5148         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5149         SE.tinyInstances[elId] = { };
5150         SE.tinyInstances[elId].ready = false;
5151         var t = tinyMCE.getInstanceById(elId);
5152
5153         if(typeof(t) == 'undefined')  {
5154             tinyMCE.execCommand('mceAddControl', false, elId);
5155             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5156                 SE.composeLayout.resizeEditorSetSignature(idx,!isReplyForward);
5157             }, this);
5158         }
5159     },
5160
5161     resizeEditorSetSignature : function(idx,setSignature)
5162     {
5163         var instance = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5164
5165         if(typeof(instance) == 'undefined' || (typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false)) {
5166             setTimeout("SE.composeLayout.resizeEditorSetSignature(" + idx + ",'"+isReplyForward+"');",500);
5167                     return;
5168                 }
5169
5170         SE.composeLayout.resizeEditor(idx);
5171         if(setSignature) {
5172             setTimeout("SUGAR.email2.composeLayout.setSignature("+idx+");",250);
5173         }
5174
5175     },
5176
5177     resizeEditor : function(idx)
5178     {
5179         var cof = Dom.get('composeOverFrame' + idx);
5180         var head = Dom.get('composeHeaderTable' + idx);
5181         var targetHeight = cof.clientHeight - head.clientHeight;
5182         var instance = SE.util.getTiny('htmleditor' + idx);
5183
5184         try {
5185         var parentEl = Dom.get(instance.editorId + '_parent');
5186         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5187         var contentEl  = instance.contentAreaContainer;
5188         var iFrame = contentEl.firstChild;
5189         var tinMceToolbarOffset = 18;
5190         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5191
5192         } catch(e) {
5193             setTimeout("SE.composeLayout.resizeEditor("+idx+");",1000);
5194         }
5195     },
5196
5197     /**
5198      * Initializes d&d, auto-complete, email templates
5199      */
5200     _2_final : function() {
5201         var idx = SE.composeLayout.currentInstanceId;
5202
5203         if(this.emailTemplates) {
5204             this.setComposeOptions(idx);
5205         } else {
5206             //populate email template cache
5207             AjaxObject.target = '';
5208             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5209         }
5210
5211         // handle drop targets for addressBook
5212        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5213        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5214        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5215        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5216
5217         // auto-complete setup
5218         SE.autoComplete.init(idx);
5219
5220         // set focus on to:
5221         document.getElementById("addressTO" + idx).focus();
5222     },
5223
5224         /**
5225      * hide tinyMCE tool bar if send email as plaintext is checked
5226      */
5227     renderTinyMCEToolBar : function (idx, hide) {
5228         if (hide) {
5229                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5230         } else {
5231                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5232         }
5233     },
5234
5235     c1_composeEmail : function(isReplyForward, retry) {
5236         if (!retry) {
5237             this._0_yui();
5238         }
5239         if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5240             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5241         } else {
5242                 this._1_tiny(isReplyForward);
5243                 this._2_final();
5244
5245                 if(isReplyForward) {
5246                     this.replyForwardEmailStage2();
5247                 }
5248         }
5249     },
5250
5251     /**
5252      * takes draft info and prepopulates
5253      */
5254     c0_composeDraft : function() {
5255         this.getNewInstanceId();
5256         inCompose = true;
5257         document.getElementById('_blank').innerHTML = '';
5258         var idx = SE.composeLayout.currentInstanceId;
5259                 SE.composeLayout.draftObject = new Object();
5260                 SE.composeLayout.draftObject.id = idx;
5261                 SE.composeLayout.draftObject.isDraft = true;
5262         SE.composeLayout.currentInstanceId = idx;
5263         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5264         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5265         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5266
5267         SE.composeLayout._0_yui();
5268         SE.composeLayout._1_tiny(true);
5269
5270         // final touches
5271         SE.composeLayout._2_final();
5272
5273         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5274         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5275     },
5276
5277     /**
5278      * Strip & Prep editor hidden fields
5279      */
5280     c0_composeNewEmail : function() {
5281         this.getNewInstanceId();
5282         this.c1_composeEmail(false);
5283     },
5284
5285     /**
5286      * Sends async request to get the compose view.
5287      * Requests come from "reply" or "forwards"
5288      */
5289     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5290         SE.composeLayout.replyForwardObj = new Object();
5291         SE.composeLayout.replyForwardObj.ieId = ieId;
5292         SE.composeLayout.replyForwardObj.uid = uid;
5293         SE.composeLayout.replyForwardObj.mbox = mbox;
5294         SE.composeLayout.replyForwardObj.type = type;
5295
5296         if(mbox == 'sugar::Emails') {
5297             SE.composeLayout.replyForwardObj.sugarEmail = true;
5298         }
5299
5300         SE.composeLayout.getNewInstanceId();
5301         SE.composeLayout.c1_composeEmail(true);
5302     },
5303     ////    END COMPOSE FLOW
5304     ///////////////////////////////////////////////////////////////////////////
5305
5306     /**
5307      * Called when a contact, email, or mailinglist is dropped
5308      * into one of the compose fields.
5309      */
5310     handleDrop : function (source, event, data, target) {
5311         var nodes;
5312         if (!target) {
5313             target = event.getTarget();
5314             if (data.single) {
5315                 data.nodes = [data.nodes];
5316             }
5317             nodes = data.nodes;
5318         } else {
5319             target = document.getElementById(target);
5320             nodes = data;
5321         }
5322
5323         if (target.id.indexOf('address') > -1) {
5324             // dropped onto email to/cc/bcc field
5325             for(var i in nodes) {
5326                 var node = nodes[i].getData();
5327                 var email = "";
5328                 if (node[1].indexOf('contact') > -1) {
5329                     email = SE.addressBook.getFormattedAddress(node[0]);
5330                 } else if (node[1].indexOf('address-email') > -1){
5331                     email = node[3].replace(/&nbsp;/gi, '');
5332                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5333                     var tr = source.getTrEl(nodes[i]);
5334                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5335                         tr = source.getPreviousTrEl(tr);
5336                     }
5337                     var CID = source.getRecord(tr).getData()[0];
5338                     var o = SE.addressBook._contactCache[CID];
5339                     var name = new String(o.name);
5340                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5341                     email = finalName + email;
5342                 }
5343                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5344             }
5345         }
5346     },
5347
5348
5349     /*/////////////////////////////////////////////////////////////////////////////
5350     ///    EMAIL TEMPLATE CODE
5351      */
5352     applyEmailTemplate : function (idx, id) {
5353
5354         //bug #20680
5355         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5356                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5357                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5358                 
5359                 //bug #6224
5360                 var to_addr = document.getElementById('addressTO'+idx);
5361                 if (to_addr.value.search(/[^;,]{6,}[;,][^;,]{6,}/) != -1) 
5362                 {
5363                         box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_WARNING_TITLE;
5364                         box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_MULTIPLE_RECIPIENTS + '<br /><br />' + box_msg;
5365                 }
5366                 
5367                 // id is selected index of email template drop-down
5368                 if(id == '' || id == "0") {
5369                         YAHOO.SUGAR.MessageBox.show({
5370                    title:box_title,
5371                    msg: box_none_msg,
5372                    type: 'confirm',
5373                    fn: function(btn){
5374                                 if(btn=='no'){return;};
5375                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5376                    modal:true,
5377                    scope:this
5378                });
5379                return;
5380                 }
5381
5382                 YAHOO.SUGAR.MessageBox.show({
5383            title:box_title,
5384            msg: box_msg,
5385            type: 'confirm',
5386            fn: function(btn){
5387                         if(btn=='no'){return;};
5388                         SUGAR.email2.composeLayout.processResult(idx, id);},
5389            modal:true,
5390            scope:this
5391        });
5392     },
5393
5394     processNoneResult : function(idx, id) {
5395         var tiny = SE.util.getTiny('htmleditor' + idx);
5396         var tinyHTML = tiny.getContent();
5397         var openTag = '<div><span><span>';
5398         var htmllow = tinyHTML.toLowerCase();
5399         var start = htmllow.indexOf(openTag);
5400                 if (start > -1) {
5401                 tinyHTML = tinyHTML.substr(start);
5402             tiny.setContent(tinyHTML);
5403                 } else { 
5404             tiny.setContent('');
5405                 }
5406     },
5407
5408         processResult : function(idx , id){
5409         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5410
5411         // get attachments if any
5412         AjaxObject.target = '';
5413         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5414     },
5415
5416     appendEmailTemplateJSON : function() {
5417         var idx = SE.composeLayout.currentInstanceId; // post increment
5418
5419         // query based on template, contact_id0,related_to
5420         //jchi 09/10/2008 refix #7743
5421         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5422             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5423         }
5424
5425         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,'"');
5426
5427         // cn: bug 14361 - text-only templates don't fill compose screen
5428         if(text == '') {
5429             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/>");
5430         }
5431
5432         var tiny = SE.util.getTiny('htmleditor' + idx);
5433         var tinyHTML = tiny.getContent();
5434         var openTag = '<div><span><span>';
5435         var closeTag = '</span></span></div>';
5436         var htmllow = tinyHTML.toLowerCase();
5437         var start = htmllow.indexOf(openTag);
5438                 if (start > -1) {
5439                 var htmlPart2 = tinyHTML.substr(start);
5440                 tinyHTML = text + htmlPart2;
5441                 tiny.setContent(tinyHTML);
5442                 } else {
5443                 tiny.setContent(text);
5444                 }
5445     },
5446
5447     /**
5448      * Writes out the signature in the email editor
5449      */
5450     setSignature : function(idx) {
5451         if (!tinyMCE)
5452             return false;
5453         var hide = document.getElementById('setEditor' + idx).checked;
5454         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5455         //wait for signatures to load before trying to set them
5456         if (!SE.composeLayout.signatures) {
5457             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5458                         return;
5459         }
5460
5461         if(idx) {
5462             var sel = document.getElementById('signatures' + idx);
5463         } else {
5464             var sel = document.getElementById('signature_id');
5465             idx = SE.tinyInstances.currentHtmleditor;
5466         }
5467
5468         //Ensure that the tinyMCE html has been rendered.
5469         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5470             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5471                     return;
5472                 }
5473
5474         var signature = '';
5475
5476         try {
5477             signature = sel.options[sel.selectedIndex].value;
5478         } catch(e) {
5479
5480         }
5481
5482         var openTag = '<div><span><span>';
5483         var closeTag = '</span></span></div>';
5484         var t = tinyMCE.getInstanceById('htmleditor' + idx);
5485         //IE 6 Hack
5486         if(typeof(t) != 'undefined')
5487         {
5488             t.contentDocument = t.contentWindow.document;
5489             var html = t.getContent();
5490         }
5491         else
5492         {
5493             var html = '';
5494         }
5495
5496         var htmllow = html.toLowerCase();
5497         var start = htmllow.indexOf(openTag);
5498         var end = htmllow.indexOf(closeTag) + closeTag.length;
5499
5500         // selected "none" - remove signature from email
5501         if(signature == '') {
5502             if (start > -1) {
5503                 var htmlPart1 = html.substr(0, start);
5504                 var htmlPart2 = html.substr(end, html.length);
5505
5506                 html = htmlPart1 + htmlPart2;
5507                 t.setContent(html);
5508             }
5509             SE.signatures.lastAttemptedLoad = '';
5510             return false;
5511         }
5512
5513         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5514             SE.signatures.lastAttemptedLoad = '';
5515
5516         SE.signatures.lastAttemptedLoad = signature;
5517
5518         if(typeof(SE.signatures[signature]) == 'undefined') {
5519             //lazy load
5520             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5521             SE.signatures.targetInstance = (idx) ? idx : "";
5522             AjaxObject.target = '';
5523             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5524         } else {
5525             var newSignature = this.prepareSignature(SE.signatures[signature]);
5526
5527             // clear out old signature
5528             if(SE.signatures.lastAttemptedLoad && start > -1) {
5529                 var htmlPart1 = html.substr(0, start);
5530                 var htmlPart2 = html.substr(end, html.length);
5531
5532                 html = htmlPart1 + htmlPart2;
5533             }
5534
5535             // [pre|ap]pend
5536                         start = html.indexOf('<div><hr></div>');
5537             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5538                                 var htmlPart1 = html.substr(0, start);
5539                                 var htmlPart2 = html.substr(start, html.length);
5540                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5541             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5542                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5543             } else {
5544                 var newHtml = html + openTag + newSignature + closeTag;
5545             }
5546             //tinyMCE.setContent(newHtml);
5547             t.setContent(newHtml);
5548         }
5549     },
5550
5551     prepareSignature : function(str) {
5552         var signature = new String(str);
5553
5554         signature = signature.replace(/&lt;/gi, '<');
5555         signature = signature.replace(/&gt;/gi, '>');
5556
5557         return signature;
5558     },
5559
5560
5561     showAttachmentPanel : function(idx) {
5562         var east = SE.composeLayout[idx].getUnitByPosition("right");
5563         var tabs = SE.composeLayout[idx].rightTabs;
5564         east.expand();
5565         tabs.set("activeTab", tabs.getTab(0));
5566     },
5567
5568     /**
5569      * expands sidebar and displays options panel
5570      */
5571     showOptionsPanel : function(idx) {
5572         var east = SE.composeLayout[idx].getUnitByPosition("right");
5573         var tabs = SE.composeLayout[idx].rightTabs;
5574         east.expand();
5575         tabs.set("activeTab", tabs.getTab(1));
5576     },
5577
5578     /**
5579      * Selects the Contacts tab
5580      */
5581     showContactsPanel : function() {
5582         SE.complexLayout.regions.west.showPanel("contactsTab");
5583     },
5584
5585     /**
5586      * Generates fields for Select Document
5587      */
5588     addDocumentField : function(idx) {
5589         var basket = document.getElementById('addedDocuments' + idx);
5590         if(basket) {
5591             var index = (basket.childNodes.length / 7) - 1;
5592             if(index < 0)
5593                 index = 0;
5594         } else {
5595             index = 0;
5596         }
5597
5598         var test = document.getElementById('documentId' + idx + index);
5599
5600         while(test != null) {
5601             index++;
5602             test = document.getElementById('documentId' + idx + index);
5603         }
5604
5605         var documentCup = document.createElement("div");
5606         documentCup.id = 'documentCup' + idx + index;
5607         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5608                 // document id field
5609                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5610                 // document name field
5611                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5612                 // select button
5613                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5614                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5615                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5616                 // remove button
5617                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5618                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5619                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5620                 "<br/>";
5621
5622         basket.appendChild(documentCup);
5623         //basket.innerHTML += out;
5624         return index;
5625     },
5626
5627     /**
5628      * Makes async call to save a draft of the email
5629      * @param int Instance index
5630      */
5631     saveDraft : function(tinyInstance) {
5632         this.sendEmail(tinyInstance, true);
5633     },
5634
5635     selectDocument : function(target) {
5636         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5637         windowName = 'selectDocument';
5638         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5639
5640         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5641         if(window.focus) {
5642             // put the focus on the popup if the browser supports the focus() method
5643             win.focus();
5644         }
5645     },
5646
5647     /**
5648      * Modal popup for file attachment dialogue
5649      */
5650     addFileField : function() {
5651         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5652             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5653                 modal:true,
5654                 visible:false,
5655                 fixedcenter:true,
5656                 constraintoviewport: true,
5657                 scroll: true,
5658                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5659                         fn:function(){SE.addFileDialog.hide();}
5660                 })
5661             });
5662             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5663             SE.addFileDialog.render();
5664            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5665         }
5666         Dom.removeClass("addFileDialog", "yui-hidden");
5667
5668         SE.addFileDialog.show();
5669     },
5670
5671     /**
5672      * Async upload of file to temp dir
5673      */
5674     uploadAttachment : function() {
5675         if(document.getElementById('email_attachment').value != "") {
5676             var formObject = document.getElementById('uploadAttachment');
5677             YAHOO.util.Connect.setForm(formObject, true, true);
5678             AjaxObject.target = '';
5679             AjaxObject.startRequest(callbackUploadAttachment, null);
5680         } else {
5681             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5682         }
5683     },
5684
5685     /**
5686      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5687      * @param string target in focus compose layout
5688      */
5689     setDocument : function(idx, target, documentId, documentName, docRevId) {
5690         // fields are named/id'd [fieldName][instanceId][index]
5691         var addedDocs = document.getElementById("addedDocuments" + idx);
5692         var docId = document.getElementById('documentId' + idx + target);
5693         var docName = document.getElementById('documentName' + idx + target);
5694         var docRevisionId = document.getElementById('document' + idx + target);
5695         docId.value = documentId;
5696         docName.value = documentName;
5697         docRevisionId.value = docRevId;
5698     },
5699
5700     /**
5701      * Removes the bucket div containing the document input fields
5702      */
5703     deleteDocumentField : function(documentCup) {
5704         var f0 = document.getElementById(documentCup);
5705         f0.parentNode.removeChild(f0);
5706     },
5707
5708     /**
5709      * Removes a Template Attachment field
5710      * @param int
5711      * @param int
5712      */
5713     deleteTemplateAttachmentField : function(idx, index) {
5714         // create not-in-array values for removal filtering
5715         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5716
5717         if(r != "") {
5718             r += "::";
5719         }
5720
5721         r += document.getElementById('templateAttachmentId' + idx + index).value;
5722         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5723
5724         var target = 'templateAttachmentCup' + idx + index;
5725         d =  document.getElementById(target);
5726         d.parentNode.removeChild(d);
5727     },
5728
5729     /**
5730      * Async removal of uploaded temp file
5731      * @param string index Should be a concatenation of idx and index
5732      * @param string
5733      */
5734     deleteUploadAttachment : function(index, file) {
5735         var d = document.getElementById('email_attachment_bucket' + index);
5736         d.parentNode.removeChild(d);
5737
5738         // make async call to delete cached file
5739         AjaxObject.target = '';
5740         AjaxObject.startRequest('', urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5741     },
5742
5743     /**
5744      * Attaches files coming from Email Templates
5745      */
5746     addTemplateAttachmentField : function(idx) {
5747         // expose title
5748         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5749
5750         var basket = document.getElementById('addedTemplateAttachments' + idx);
5751
5752         if(basket) {
5753             var index = basket.childNodes.length;
5754             if(index < 0)
5755                 index = 0;
5756         } else {
5757             index = 0;
5758         }
5759
5760         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5761                                 // remove button
5762                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5763                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5764                                         idx + "\",\"" + index + "\");'/>" +
5765                                 // file icon
5766                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5767                                 // templateAttachment field
5768                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5769                                 // docId field
5770                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5771                                 // file name
5772                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
5773                                 "<br id='br" + index + "></br>" +
5774                                 "<br id='brdoc" + index + "></br>" +
5775                         "</div>";
5776                 basket.innerHTML = basket.innerHTML + out;
5777
5778         return index;
5779     },
5780
5781     /**
5782      * Sends one email via async call
5783      * @param int idx Editor instance ID
5784      * @param bool isDraft
5785      */
5786     sendEmail : function(idx, isDraft) {
5787
5788         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5789         var obAccountID = document.getElementById('addressFrom' + idx).value;
5790
5791         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5792         {
5793             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5794             return false;
5795         }
5796
5797
5798         var form = document.getElementById('emailCompose' + idx);
5799         var composeOptionsFormName = "composeOptionsForm" + idx;
5800         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5801         var html = t.getContent();
5802         var subj = document.getElementById('emailSubject' + idx).value;
5803         var to = trim(document.getElementById('addressTO' + idx).value);
5804         var cc = trim(document.getElementById('addressCC' + idx).value);
5805         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5806         var email_id = document.getElementById('email_id' + idx).value;
5807         var composeType = document.getElementById('composeType').value;
5808         var parent_type = document.getElementById("parent_type").value;
5809         var parent_id = document.getElementById("parent_id").value;
5810
5811         var el_uid = document.getElementById("uid");
5812         var uid = (el_uid == null) ? '' : el_uid.value;
5813
5814         var el_ieId = document.getElementById("ieId");
5815         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5816
5817         var el_mbox = document.getElementById("mbox");
5818         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5819
5820         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5821                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5822                 return false;
5823         }
5824
5825         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5826                 return;
5827         } // if
5828                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5829                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5830         parent_id = parentIdValue;
5831         parent_type = parentTypeValue;
5832
5833         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5834         // baseline viability check
5835
5836         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5837             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5838             return false;
5839         } else if(subj == '' && !isDraft) {
5840             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5841                 return false;
5842             } else {
5843                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5844             }
5845         } else if(html == '' && !isDraft) {
5846             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5847                 return false;
5848             }
5849         }
5850
5851         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5852                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5853                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5854         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5855         html = html.replace(/&lt;/ig, "sugarLessThan");
5856         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5857
5858         form.sendDescription.value = html;
5859         form.sendSubject.value = subj;
5860         form.sendTo.value = to;
5861         form.sendCc.value = cc;
5862         form.sendBcc.value = bcc;
5863         form.email_id.value = email_id;
5864         form.composeType.value = composeType;
5865         form.composeLayoutId.value = 'composeLayout' + idx;
5866         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5867         form.saveToSugar.value = 1;
5868         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5869         form.parent_type.value = parent_type;
5870         form.parent_id.value = parent_id;
5871         form.uid.value = uid;
5872         form.ieId.value = ieId;
5873         form.mbox.value = mbox;
5874
5875         // email attachments
5876         var addedFiles = document.getElementById('addedFiles' + idx);
5877         if(addedFiles) {
5878             for(i=0; i<addedFiles.childNodes.length; i++) {
5879                 var bucket = addedFiles.childNodes[i];
5880
5881                 for(j=0; j<bucket.childNodes.length; j++) {
5882                     var node = bucket.childNodes[j];
5883                     var nName = new String(node.name);
5884
5885                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5886                         if(form.attachments.value != '') {
5887                             form.attachments.value += "::";
5888                         }
5889                         form.attachments.value += node.value;
5890                     }
5891                 }
5892             }
5893         }
5894
5895         // sugar documents
5896         var addedDocs = document.getElementById('addedDocuments' + idx);
5897         if(addedDocs) {
5898             for(i=0; i<addedDocs.childNodes.length; i++) {
5899                 var cNode = addedDocs.childNodes[i];
5900                 for(j=0; j<cNode.childNodes.length; j++) {
5901                     var node = cNode.childNodes[j];
5902                     var nName = new String(node.name);
5903                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5904                         if(form.documents.value != '') {
5905                             form.documents.value += "::";
5906                         }
5907                         form.documents.value += node.value;
5908                     }
5909                 }
5910             }
5911         }
5912
5913         // template attachments
5914         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5915         if(addedTemplateAttachments) {
5916             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5917                 var cNode = addedTemplateAttachments.childNodes[i];
5918                 for(j=0; j<cNode.childNodes.length; j++) {
5919                     var node = cNode.childNodes[j];
5920                     var nName = new String(node.name);
5921                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5922                         if(form.templateAttachments.value != "") {
5923                             form.templateAttachments.value += "::";
5924                         }
5925                         form.templateAttachments.value += node.value;
5926                     }
5927                 }
5928             }
5929         }
5930
5931         // remove attachments
5932         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5933
5934         YAHOO.util.Connect.setForm(form);
5935
5936         AjaxObject.target = 'frameFlex';
5937
5938         // sending a draft email
5939         if(!isDraft && in_draft) {
5940             // remove row
5941             SE.listView.removeRowByUid(email_id);
5942         }
5943
5944         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5945         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5946
5947         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5948     },
5949
5950     /**
5951      * Handles clicking the email address link from a given view
5952      */
5953     composePackage : function() {
5954         if(composePackage != null) {
5955             SE.composeLayout.c0_composeNewEmail();
5956
5957
5958             if(composePackage.to_email_addrs) {
5959                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5960             } // if
5961             if (composePackage.subject != null && composePackage.subject.length > 0) {
5962                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5963             }
5964
5965             //If no parent fields are set in the composePackage, ensure they are cleared.
5966             var parentFields = ['parent_type','parent_name','parent_id'];
5967             for(var i=0;i<parentFields.length;i++)
5968             {
5969                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5970                     composePackage[parentFields[i]] = "";
5971             }
5972
5973             document.getElementById("parent_type").value = composePackage.parent_type;
5974             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5975             document.getElementById("parent_id").value = composePackage.parent_id;
5976             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5977             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5978
5979             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5980                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5981             } // if
5982             if (composePackage.body != null && composePackage.body.length > 0) {
5983                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5984                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5985                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5986             } // if
5987             if (composePackage.attachments != null) {
5988                                 SE.composeLayout.loadAttachments(composePackage.attachments);
5989             } // if
5990
5991             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5992                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5993                         SE.util.emptySelectOptions(addressFrom);
5994                         var fromAccountOpts = composePackage.fromAccounts.data;
5995                         for(i=0; i<fromAccountOpts.length; i++) {
5996                               var key = fromAccountOpts[i].value;
5997                               var display = fromAccountOpts[i].text;
5998                               var opt = new Option(display, key);
5999                               if (fromAccountOpts[i].selected) {
6000                                 opt.selected = true;
6001                               }
6002                               addressFrom.options.add(opt);
6003                         }
6004
6005             } // if
6006         } // if
6007     },
6008
6009     setContentOnThisTiny : function() {
6010         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
6011         var tinyHTML = tiny.getContent();
6012         composePackage.body = decodeURI(encodeURI(composePackage.body));
6013         // cn: bug 14361 - text-only templates don't fill compose screen
6014         if(composePackage.body == '') {
6015             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,'"');
6016         } // if
6017         //Flag determines if we should clear the tiny contents or just append
6018         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
6019             SE.composeLayout.tinyHTML = '';
6020         else
6021             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
6022
6023          tiny.setContent(SE.composeLayout.tinyHTML);
6024          //Indicate that the contents has been loaded successfully.
6025          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
6026     },
6027     /**
6028      * Confirms closure of a compose screen if "x" is clicked
6029      */
6030     confirmClose : function(panel) {
6031         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
6032             SE.composeLayout.closeCompose(panel.id);
6033             return true;
6034         } else {
6035             return false;
6036         }
6037     },
6038
6039     /**
6040      * forces close of a compose screen
6041      */
6042     forceCloseCompose : function(id) {
6043         SE.composeLayout.closeCompose(id);
6044
6045         // handle flow back to originating view
6046         if(composePackage) {
6047             // check if it's a module we need to return to
6048             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
6049                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
6050                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
6051                     window.location = url;
6052                 }
6053             }
6054         }
6055     },
6056
6057     /**
6058      * closes the editor that just sent email
6059      * @param string id ID of composeLayout tab
6060      */
6061     closeCompose : function(id) {
6062         // destroy tinyMCE instance
6063         var idx = id.substr(13, id.length);
6064         var instanceId = "htmleditor" + idx;
6065         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6066
6067         // nullify DOM and namespace values.
6068         inCompose = false;
6069         SE.composeLayout[idx] = null;
6070         SE.tinyInstances[instanceId] = null;
6071         var tabsArray = SE.innerLayout.get("tabs");
6072         for (i = 0 ; i < tabsArray.length ; i++) {
6073                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6074                         tabsArray[i].close();
6075                         break;
6076                 }
6077         }
6078         //SE.innerLayout.getTab(idx).close();
6079     },
6080
6081     /**
6082     *  Enable the quick search for the compose relate field or search tab
6083     */
6084     enableQuickSearchRelate: function(idx,overides){
6085
6086         if(typeof overides != 'undefined')
6087         {
6088             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6089             var newModule = document.getElementById(newModuleID).value;
6090             var formName = overides['formName'];
6091             var fieldName = overides['fieldName'];
6092             var fieldId = overides['fieldId'];
6093             var fullName = formName + "_" + fieldName;
6094             var postBlurFunction = null;
6095         }
6096         else
6097         {
6098             var newModule = document.getElementById('data_parent_type'+idx).value;
6099             var formName = 'emailCompose'+idx;
6100             var fieldName = 'data_parent_name'+idx;
6101             var fieldId = 'data_parent_id'+idx;
6102             var fullName = formName + "_" + fieldName;
6103             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6104         }
6105
6106         if(typeof sqs_objects == 'undefined')
6107             window['sqs_objects'] = new Array;
6108
6109         window['sqs_objects'][fullName] = {
6110             form:formName,
6111                         method:"query",
6112                         modules:[newModule],
6113                         group:"or",
6114             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6115             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6116                         post_onblur_function: postBlurFunction,
6117             order:"name","limit":"30","no_match_text":"No Match"};
6118
6119
6120         if(typeof QSProcessedFieldsArray != 'undefined')
6121                 QSProcessedFieldsArray[fullName] = false;
6122         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6123                 QSFieldsArray[fullName].destroy();
6124                 delete QSFieldsArray[fullName];
6125         }
6126         if (Dom.get(fullName + "_results")) {
6127                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6128         }
6129
6130         enableQS(false);
6131     },
6132
6133         qsAddAddress : function(o) {
6134         if (o.name != "" && o.email1 != "")
6135         {
6136                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6137                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6138         }
6139     },
6140     /**
6141      * Returns a new instance ID, 0-index
6142      */
6143     getNewInstanceId : function() {
6144         this.currentInstanceId = this.currentInstanceId + 1;
6145         return this.currentInstanceId;
6146     },
6147
6148     /**
6149      * 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.
6150      */
6151     loadAttachments : function(result) {
6152         var idx = SE.composeLayout.currentInstanceId;
6153
6154         if(typeof(result) == 'object') {
6155                 //jchi #20680. Clean the former template attachments;
6156                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6157                         if(basket.innerHTML != ''){
6158                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6159                                         if (btn != 'yes'){
6160                                                 basket.innerHTML = '';
6161                                         }
6162                                 });
6163                         }
6164             for(i in result) {
6165                 if(typeof result[i] == 'object') {
6166                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6167                     var bean = result[i];
6168                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6169                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6170                 }
6171             }
6172         }
6173     },
6174
6175     /**
6176      * fills drop-down values for email templates and signatures
6177      */
6178     setComposeOptions : function(idx) {
6179         // send from accounts
6180         var addressFrom = document.getElementById('addressFrom' + idx);
6181
6182         if (addressFrom.options.length <= 0) {
6183                 SE.util.emptySelectOptions(addressFrom);
6184                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6185                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6186                       var key = fromAccountOpts[id].value;
6187                       var display = fromAccountOpts[id].text;
6188                       var is_default = false;
6189                       if(key == SUGAR.default_inbound_accnt_id)
6190                         is_default = true;
6191                       var opt = new Option(display, key);
6192                       addressFrom.options.add(opt);
6193                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6194                 }
6195         }
6196
6197         // email templates
6198         var et = document.getElementById('email_template' + idx);
6199         SE.util.emptySelectOptions(et);
6200
6201         for(var key in this.emailTemplates) { // iterate through assoc array
6202             var display = this.emailTemplates[key];
6203             var opt = new Option(display, key);
6204             et.options.add(opt);
6205         }
6206
6207         // signatures
6208         var sigs = document.getElementById('signatures' + idx);
6209         SE.util.emptySelectOptions(sigs);
6210
6211         for(var key in this.signatures) { // iterate through assoc array
6212             var display = this.signatures[key];
6213             var opt = new Option(display, key);
6214
6215             if(key == SE.userPrefs.signatures.signature_default) {
6216                 opt.selected = true;
6217             }
6218
6219             sigs.options.add(opt);
6220         }
6221
6222         // html/plain email?
6223         var htmlEmail = document.getElementById('setEditor' + idx);
6224         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6225             htmlEmail.checked = true;
6226         } else {
6227                 htmlEmail.checked = false;
6228         }
6229
6230         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6231     },
6232
6233     /**
6234      * After compose screen is rendered, async call to get email body from Sugar
6235      */
6236     replyForwardEmailStage2 : function() {
6237         SE.util.clearHiddenFieldValues('emailUIForm');
6238         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6239
6240         var ieId = SE.composeLayout.replyForwardObj.ieId;
6241         var uid = SE.composeLayout.replyForwardObj.uid;
6242         var mbox = SE.composeLayout.replyForwardObj.mbox;
6243         var type = SE.composeLayout.replyForwardObj.type;
6244         var idx = SE.composeLayout.currentInstanceId;
6245
6246         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6247
6248         document.getElementById('emailSubject' + idx).value = type;
6249         document.getElementById('emailUIAction').value = 'composeEmail';
6250         document.getElementById('composeType').value = type;
6251         document.getElementById('ieId').value = ieId;
6252         document.getElementById('uid').value = uid;
6253         document.getElementById('mbox').value = mbox;
6254                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6255         var formObject = document.getElementById('emailUIForm');
6256         YAHOO.util.Connect.setForm(formObject);
6257
6258         var sendType = type;
6259         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6260     },
6261
6262     /**
6263     *  Show the hidden cc or bcc fields
6264     */
6265     showHiddenAddress: function(addrType,idx){
6266
6267         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6268         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6269                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6270                 this[addrType+'Hidden'+idx] = false;
6271
6272                 //After bcc or cc is added, move options below last addr field
6273                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6274
6275                 //If both cc and bcc hidden, remove the empty row containing text.
6276                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6277                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6278                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6279
6280                 // SE.composeLayout.resizeEditor(idx);
6281     },
6282     /**
6283     *  Hide the cc and bcc fields if they were shown.
6284     */
6285     hideHiddenAddresses: function(idx){
6286
6287         var addrTypes = ['cc','bcc'];
6288         for(var i = 0;i<addrTypes.length;i++)
6289         {
6290             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6291             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6292             this[addrTypes[i] + 'Hidden'+idx] = true
6293         }
6294
6295         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6296         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6297         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6298     }
6299 };
6300
6301 ////    END SE.composeLayout
6302 ///////////////////////////////////////////////////////////////////////////////
6303 ///////////////////////////////////////////////////////////////////////////////
6304 ////    SE.util
6305 SE.util = {
6306     /**
6307      * Cleans serialized UID lists of duplicates
6308      * @param string
6309      * @return string
6310      */
6311     cleanUids : function(str) {
6312         var seen = new Object();
6313         var clean = "";
6314         var arr = new String(str).split(",");
6315
6316         for(var i=0; i<arr.length; i++) {
6317             if(seen[arr[i]]) {
6318                 continue;
6319             }
6320
6321             clean += (clean != "") ? "," : "";
6322             clean += arr[i];
6323             seen[arr[i]] = true;
6324         }
6325
6326         return clean;
6327     },
6328
6329     /**
6330      * Clears hidden field values
6331      * @param string id ID of form element to clear
6332      */
6333     clearHiddenFieldValues : function(id) {
6334         var form = document.getElementById(id);
6335
6336         for(i=0; i<form.elements.length; i++) {
6337             if(form.elements[i].type == 'hidden') {
6338                 var e = form.elements[i];
6339                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6340                     e.value = '';
6341                 }
6342             }
6343         }
6344     },
6345
6346     /**
6347      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6348      */
6349     emptySelectOptions : function(el) {
6350         if(el) {
6351             for(i=el.childNodes.length - 1; i >= 0; i--) {
6352                 if(el.childNodes[i]) {
6353                     el.removeChild(el.childNodes[i]);
6354                 }
6355             }
6356         }
6357     },
6358
6359     /**
6360      * Returns the MBOX path in the manner php_imap expects:
6361      * ie: INBOX.DEBUG.test
6362      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6363      */
6364     generateMboxPath : function(str) {
6365         var ex = str.split("::");
6366
6367         /* we have a serialized MBOX path */
6368         if(ex.length > 1) {
6369             var start = false;
6370             var ret = '';
6371             for(var i=0; i<ex.length; i++) {
6372                 if(ex[i] == 'INBOX') {
6373                     start = true;
6374                 }
6375
6376                 if(start == true) {
6377                     if(ret != "") {
6378                         ret += ".";
6379                     }
6380                     ret += ex[i];
6381                 }
6382             }
6383         } else {
6384             /* we have a Sugar folder GUID - do nothing */
6385             return str;
6386         }
6387
6388         return ret;
6389     },
6390
6391     /**
6392      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6393      * @param HTMLElement el
6394      * @return string GUID of found element or empty on failure
6395      */
6396     getGuidFromElement : function(el) {
6397         var GUID = '';
6398         var iterations = 4;
6399         var passedEl = el;
6400
6401         // upwards
6402         for(var i=0; i<iterations; i++) {
6403             if(el) {
6404                 if(el.id.match(SE.reGUID)) {
6405                     return el.id;
6406                 } else {
6407                     el = el.parentNode;
6408                 }
6409             }
6410         }
6411
6412         return GUID;
6413     },
6414
6415     /**
6416      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6417      * @return string
6418      */
6419     getPanelId : function() {
6420         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6421     },
6422
6423     /**
6424      * wrapper to handle weirdness with IE
6425      * @param string instanceId
6426      * @return tinyMCE Controller object
6427      */
6428     getTiny : function(instanceId) {
6429         if(instanceId == '') {
6430             return null;
6431         }
6432
6433         var t = tinyMCE.getInstanceById(instanceId);
6434
6435         if(this.isIe()) {
6436             this.sleep(200);
6437             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6438         }
6439         return t;
6440     },
6441
6442     /**
6443      * Simple check for MSIE browser
6444      * @return bool
6445      */
6446     isIe : function() {
6447         var nav = new String(navigator.appVersion);
6448         if(nav.match(/MSIE/)) {
6449             return true;
6450         }
6451         return false;
6452     },
6453
6454     /**
6455      * Recursively removes an element from the DOM
6456      * @param HTMLElement
6457      */
6458     removeElementRecursive : function(el) {
6459         this.emptySelectOptions(el);
6460     },
6461
6462     /**
6463      * Fakes a sleep
6464      * @param int
6465      */
6466     sleep : function(secs) {
6467         setTimeout("void(0);", secs);
6468     },
6469
6470     /**
6471      * Converts a <select> element to an Ext.form.combobox
6472      */
6473      convertSelect : function(select) {
6474        alert('in convertSelect');
6475        if (typeof(select) == "string") {
6476            select = document.getElementById(select);
6477        }
6478      },
6479
6480      findChildNode : function (parent, property, value) {
6481          for (i in parent.children) {
6482                  var child = parent.children[i];
6483                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6484                          return child;
6485                  var searchChild = SE.util.findChildNode(child, property, value);
6486                  if (searchChild)
6487                          return searchChild;
6488          }
6489          return false;
6490      },
6491
6492      cascadeNodes : function (parent, fn, scope, args) {
6493          for (i in parent.children) {
6494                  var child = parent.children[i];
6495                  var s = scope ? scope : child;
6496                  var a = args ? args : child;
6497                  fn.call(s, a);
6498                  SE.util.cascadeNodes(child, fn, scope, args);
6499          }
6500      }
6501 };
6502
6503
6504 ////    END UTIL
6505 ///////////////////////////////////////////////////////////////////////////////
6506
6507
6508 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6509                                 
6510 /*********************************************************************************
6511  * SugarCRM Community Edition is a customer relationship management program developed by
6512  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6513  * 
6514  * This program is free software; you can redistribute it and/or modify it under
6515  * the terms of the GNU Affero General Public License version 3 as published by the
6516  * Free Software Foundation with the addition of the following permission added
6517  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6518  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6519  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6520  * 
6521  * This program is distributed in the hope that it will be useful, but WITHOUT
6522  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6523  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6524  * details.
6525  * 
6526  * You should have received a copy of the GNU Affero General Public License along with
6527  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6528  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6529  * 02110-1301 USA.
6530  * 
6531  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6532  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6533  * 
6534  * The interactive user interfaces in modified source and object code versions
6535  * of this program must display Appropriate Legal Notices, as required under
6536  * Section 5 of the GNU Affero General Public License version 3.
6537  * 
6538  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6539  * these Appropriate Legal Notices must retain the display of the "Powered by
6540  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6541  * technical reasons, the Appropriate Legal Notices must display the words
6542  * "Powered by SugarCRM".
6543  ********************************************************************************/
6544
6545
6546 if (typeof console == "undefined")
6547         console = { log: function(o) {alert(o)} };
6548
6549 var AjaxObject = {
6550         ret : '',
6551         currentRequestObject : null,
6552         //timeout : 30000, // 30 second timeout default
6553         timeout : 9999999999, // 30 second timeout default
6554         forceAbort : false,
6555         trail : new Array(),
6556
6557         /**
6558          */
6559         _reset : function() {
6560                 this.timeout = 30000;
6561                 this.forceAbort = false;
6562         },
6563
6564         folderRenameCleanup : function() {
6565                 SUGAR.email2.folders.setSugarFolders();
6566         },
6567
6568         fullSyncCleanup : function(o) {
6569                 this.folders.checkMailCleanup(o);
6570                 SUGAR.email2.settings.settingsDialog.hide();
6571         },
6572
6573         /**
6574          */
6575         composeCache : function(o) {
6576                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6577                 // get email templates and user signatures
6578                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6579
6580                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6581                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6582                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6583
6584                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6585
6586                 //Set the error array so we can notify the user when they try to hit send if any errors
6587                 //are present.  We will also notify them now (after hitting compose button).
6588                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6589
6590
6591                 //if error element is returning an array, then check the length to make sure we have error messages
6592                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6593                         //add error messages for display
6594                         for(i in ret.errorArray)
6595                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6596                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6597                         //if error element is returning an object, and the object value is not empty or null, then display error message
6598                         for(i in ret.errorArray)
6599                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6600                 }
6601
6602                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6603                 if(SUGAR.isIE) {
6604                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6605                         if(overlayPanel) {
6606                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6607                         }
6608                 }
6609         },
6610
6611
6612         handleDeleteSignature : function(o) {
6613                 hideOverlay();
6614                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6615                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6616         var field = document.getElementById('signature_id');
6617                 SUGAR.email2.util.emptySelectOptions(field);
6618
6619                 for(var i in ret.signatures) { // iterate through assoc array
6620                         var opt = new Option(ret.signatures[i], i);
6621                         field.options.add(opt);
6622                 }
6623                 setSigEditButtonVisibility();
6624         },
6625
6626         /**
6627          */
6628         handleDeleteReturn : function(o) {
6629                 // force refresh ListView
6630                 hideOverlay();
6631                 if(document.getElementById('focusEmailMbox')) {
6632                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6633                 }
6634
6635                 // need to display success message before calling next async call?
6636                 document.getElementById(this.target).innerHTML = o.responseText;
6637         },
6638
6639         /**
6640          */
6641     handleFailure : function(o) {
6642                 // Failure handler
6643                 overlay('Exception occurred...', o.statusText, 'alert');
6644                 if(document.getElementById('saveButton')) {
6645                         document.getElementById('saveButton').disabled = false;
6646                 }
6647         },
6648
6649         handleReplyForward : function(o) {
6650                 var a = YAHOO.lang.JSON.parse(o.responseText);
6651                 globalA = a;
6652                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6653
6654                 document.getElementById('email_id' + idx).value = a.uid;
6655                 document.getElementById('emailSubject' + idx).value = a.name;
6656                 document.getElementById('addressTO' + idx).value = a.from;
6657                 document.getElementById('uid' + idx).value = a.uid;
6658                 if(a.cc) {
6659                         document.getElementById('addressCC' + idx).value = a.cc;
6660                         SE.composeLayout.showHiddenAddress('cc', idx);
6661                 }
6662
6663                 if(a.type) {
6664                         document.getElementById('type' + idx).value = a.type;
6665                 }
6666
6667                 // apply attachment values
6668                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6669
6670                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6671         },
6672
6673         handleReplyForwardForDraft : function(o) {
6674                 var a = YAHOO.lang.JSON.parse(o.responseText);
6675                 globalA = a;
6676                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6677
6678                 document.getElementById('email_id' + idx).value = a.uid;
6679                 document.getElementById('emailSubject' + idx).value = a.name;
6680                 document.getElementById('addressTO' + idx).value = a.to;
6681
6682                 if(a.cc) {
6683                         document.getElementById('addressCC' + idx).value = a.cc;
6684                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6685                 }
6686
6687                 if(a.bcc) {
6688                         document.getElementById('addressBCC' + idx).value = a.bcc;
6689                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6690                 }
6691
6692
6693                 if(a.type) {
6694                         document.getElementById('type' + idx).value = a.type;
6695                 }
6696
6697
6698                 // apply attachment values
6699                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6700
6701                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6702         },
6703
6704         /**
6705          */
6706         handleSuccess : function(o) {
6707                 document.getElementById(this.target).innerHTML = o.responseText;
6708                 hideOverlay();
6709         },
6710
6711         /**
6712          */
6713         ieDeleteSuccess : function(o) {
6714                 hideOverlay();
6715                 
6716                 SUGAR.email2.accounts.refreshInboundAccountTable();
6717                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6718                 SUGAR.email2.accounts.rebuildFolderList();
6719         },
6720
6721         /**
6722          */
6723         ieSaveSuccess : function(o) {
6724                 document.getElementById('saveButton').disabled = false;
6725                 var a = YAHOO.lang.JSON.parse(o.responseText);
6726                 if (a) {
6727                         if(a.error) {
6728                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6729                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6730                         } else {
6731                                 resp = YAHOO.lang.JSON.parse(o.responseText);
6732                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6733                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6734                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6735                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6736                         }
6737                 } else {
6738                      hideOverlay();
6739                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6740                 }
6741
6742         },
6743
6744         /**
6745          */
6746         loadAttachments : function(o) {
6747                 var result = YAHOO.lang.JSON.parse(o.responseText);
6748
6749                 SUGAR.email2.composeLayout.loadAttachments(result);
6750         },
6751
6752         /**
6753          */
6754         loadSignature : function(o) {
6755                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6756                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6757                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6758         },
6759
6760         /**
6761          * Follow up to mark email read|unread|flagged
6762          */
6763         markEmailCleanup : function(o) {
6764                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6765                 if (!ret['status']) {
6766                 hideOverlay();
6767                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6768                 } else {
6769                         SUGAR.email2.contextMenus.markEmailCleanup();
6770                 } // else
6771         },
6772
6773         /**
6774          */
6775         rebuildShowFolders : function(o) {
6776                 var t = YAHOO.lang.JSON.parse(o.responseText);
6777                 var show = document.getElementById('ieAccountListShow');
6778
6779                 SUGAR.email2.util.emptySelectOptions(show);
6780
6781                 for(i=0; i<t.length; i++) { // iterate through assoc array
6782                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6783                         opt.selected = t[i].selected;
6784                         show.options.add(opt);
6785                 }
6786
6787                 SUGAR.email2.accounts.renderTree();
6788         },
6789         /**
6790          */
6791         saveListViewSortOrderPart2 : function() {
6792                 // create the JSON string the func expects
6793                 focusFolderPath = '[ "Home", "' + ieName + '"';
6794
6795                 var f = new String(focusFolder);
6796                 var fEx = f.split('.');
6797
6798                 for(i=0; i<fEx.length; i++) {
6799                         focusFolderPath += ', "' + fEx[i] +'"'
6800                 }
6801
6802                 focusFolderPath += ']';
6803
6804                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6805                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6806         },
6807
6808         /**
6809          *
6810          */
6811         sendEmailCleanUp : function(o) {
6812         var ret;
6813                 hideOverlay();
6814
6815         try {
6816             ret = YAHOO.lang.JSON.parse(o.responseText);
6817             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6818             //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6819         } catch(err) {
6820             if (o.responseText) {
6821                         overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6822                     }
6823             // Else we have an error here.
6824         }
6825         
6826                 if (typeof(SE.grid) != 'undefined')
6827                         SE.listView.refreshGrid();
6828                 //Disabled while address book is disabled
6829
6830                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6831                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6832                 //close the shortcut bar menu
6833                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6834                         if(action_sugar_grp1 == 'DetailView') {
6835                                 showSubPanel('history',null,true);
6836                         } else if(action_sugar_grp1 == 'quickcreate') {
6837                                 closeEmailOverlay();
6838                         }
6839                 }
6840
6841         },
6842
6843         ieSendSuccess : function(o) {
6844                 hideOverlay();
6845                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6846         },
6847
6848         /**
6849          */
6850         settingsFolderRefresh : function(o) {
6851                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6852                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6853                 var user = document.getElementById('userFolders');
6854
6855                 SUGAR.email2.util.emptySelectOptions(user);
6856
6857                 for(i=0; i<ret.userFolders.length; i++) {
6858                         var display = ret.userFolders[i].name;
6859                         var value = ret.userFolders[i].id;
6860                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6861                         var opt = new Option(display, value, selected);
6862                         opt.selected = selected;
6863                         user.options.add(opt);
6864                 }
6865         },
6866
6867         /**
6868          */
6869         startRequest : function(callback, args, forceAbort) {
6870                 if(this.currentRequestObject != null) {
6871                         if(this.forceAbort == true) {
6872                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6873                         }
6874                 }
6875                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6876                 this._reset();
6877         },
6878
6879         requestInProgress : function() {
6880                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6881         },
6882
6883         /**
6884          */
6885         updateFolderSubscriptions : function() {
6886                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6887                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6888                 hideOverlay();
6889         },
6890
6891         /**
6892          */
6893         updateFrameFolder : function() {
6894                 SUGAR.email2.folders.checkEmailAccounts();
6895         },
6896
6897         /**
6898          */
6899         updateUserPrefs : function(o) {
6900                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
6901                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6902         },
6903
6904         /**
6905          */
6906         uploadAttachmentSuccessful : function(o) {
6907                 // clear out field
6908                 document.getElementById('email_attachment').value = '';
6909                 
6910                 var ret = YAHOO.lang.JSON.parse(o.responseText);
6911                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6912                 var overall = document.getElementById('addedFiles' + idx);
6913                 var index = overall.childNodes.length;
6914                 var out =
6915                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6916                                 // remove button
6917                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6918                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6919                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6920                                 // file icon
6921                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6922                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6923                                 // hidden id field
6924                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6925                                 // file name
6926                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6927                                 "<br/>" +
6928                         "</div>";
6929                 overall.innerHTML += out;
6930                 if(SUGAR.email2.util.isIe()) {
6931                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6932                 }
6933
6934                 // hide popup
6935                 SUGAR.email2.addFileDialog.hide();
6936                 // focus attachments
6937                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6938         }
6939 };
6940
6941
6942 ///////////////////////////////////////////////////////////////////////////
6943 ////    PER MODULE CALLBACK OBJECTS
6944 AjaxObject.accounts = {
6945         saveOutboundCleanup : function(o) {
6946                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6947                 SUGAR.email2.accounts.outboundDialog.hide();
6948                 var id = o.responseText;
6949                 SUGAR.email2.accounts.newAddedOutboundId = id;
6950                 },
6951         saveDefaultOutboundCleanup: function(o){
6952
6953         },
6954         callbackEditOutbound : {
6955                 success : function(o)
6956                 {
6957                         var ret = YAHOO.lang.JSON.parse(o.responseText);
6958                         // show overlay
6959                         SUGAR.email2.accounts.showAddSmtp();
6960
6961                         // fill values
6962                         document.getElementById("mail_id").value = ret.id;
6963                         document.getElementById("type").value = ret.type;
6964                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6965                         document.getElementById("mail_name").value = ret.name;
6966                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6967                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6968                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6969                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6970                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6971                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6972                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6973
6974             if(ret.type == 'system-override') {
6975                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6976                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6977             }
6978             else {
6979                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6980                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6981             }
6982             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6983
6984                 },
6985                 failure : AjaxObject.handleFailure,
6986                 timeout : AjaxObject.timeout,
6987                 scope   : AjaxObject
6988         },
6989         callbackDeleteOutbound : {
6990                 success : function(o) {
6991                     var ret = YAHOO.lang.JSON.parse(o.responseText);
6992                     if(ret.is_error)
6993                     {
6994                         if(confirm(ret.error_message))
6995                 {
6996                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6997                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6998                 }
6999                 else
7000                     hideOverlay();
7001                     }
7002                     else
7003                     {
7004                              hideOverlay();
7005                              SUGAR.email2.accounts.refreshOuboundAccountTable();
7006                     }
7007                 },
7008
7009                 failure : AjaxObject.handleFailure,
7010                 timeout : AjaxObject.timeout,
7011                 scope   : AjaxObject
7012         },
7013
7014         callbackCheckMailProgress : {
7015            success : function(o) {
7016                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
7017                    SUGAR.email2.accounts.totalMsgCount = -1;
7018                }
7019
7020                //Check for server timeout / errors
7021                var ret = YAHOO.lang.JSON.parse(o.responseText);
7022                var done = false;
7023
7024                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
7025                    hideOverlay();
7026                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7027                    SUGAR.email2.accounts.totalMsgCount = -1;
7028                //SUGAR.email2.folders.rebuildFolders();
7029                done = true;
7030                }
7031
7032                var currIeId = ret['ieid'];
7033
7034
7035                var serverCount = ret.count;
7036
7037                if (ret['status'] == 'done') {
7038                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
7039                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
7040                            //We are all done
7041                            done = true;
7042                            break;
7043                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
7044                            //Go to next account
7045                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
7046                            ret.count = 0;
7047                            SUGAR.email2.accounts.totalMsgCount = -1;
7048                            break;
7049                        }
7050                    }
7051                }
7052                else if (ret.mbox && ret.totalcount && ret.count) {
7053                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7054                    if (ret.count >= ret.totalcount) {
7055                        serverCount = 0;
7056                    }
7057                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7058                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7059                } else {
7060                        hideOverlay();
7061                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7062                SUGAR.email2.accounts.totalMsgCount = -1;
7063                done = true;
7064                    }
7065
7066                if (done) {
7067                    SUGAR.email2.accounts.totalMsgCount = -1;
7068                    hideOverlay();
7069                    SUGAR.email2.folders.rebuildFolders();
7070                    SE.listView.refreshGrid();
7071                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7072                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7073                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7074                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7075            } else {
7076                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7077                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7078                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7079                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7080                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7081                }
7082            },
7083            failure : AjaxObject.handleFailure,
7084        timeout : AjaxObject.timeout,
7085        scope   : AjaxObject
7086         }
7087 };
7088
7089 ///////////////////////////////////////////////////////////////////////////////
7090 ////    COMPOSE LAYOUT
7091 AjaxObject.composeLayout = {
7092     /**
7093      * Populates the record id
7094      */
7095     saveDraftCleanup : function(o) {
7096         var ret;
7097         hideOverlay();
7098
7099         try {
7100             ret = YAHOO.lang.JSON.parse(o.responseText);
7101             SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7102         } catch(err) {
7103             if (o.responseText) {
7104                 overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7105             }
7106         }
7107     }
7108 };
7109
7110 AjaxObject.composeLayout.callback = {
7111         saveDraft : {
7112                 success : AjaxObject.composeLayout.saveDraftCleanup,
7113                 failure : AjaxObject.handleFailure,
7114                 timeout : AjaxObject.timeout,
7115                 scope   : AjaxObject
7116         }
7117 };
7118
7119 AjaxObject.detailView = {
7120         /**
7121          * Pops-up a printable view of an email
7122          */
7123         displayPrintable : function(o) {
7124                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7125                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7126                 // 2 below must be in global context
7127                 meta = ret.meta;
7128                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7129                 email = ret.meta.email;
7130                 if (typeof(email.cc) == 'undefined') {
7131                   email.cc = "";
7132                 }
7133
7134                 var out = displayTemplate.exec({
7135                         'app_strings'   : app_strings,
7136                         'theme'                 : theme,
7137                         'idx'                   : 'Preview',
7138                         'meta'                  : meta,
7139                         'email'                 : meta.email
7140                 });
7141
7142                 // open popup window
7143                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7144                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7145
7146                 popup.document.write(out);
7147                 popup.document.close();
7148         },
7149
7150         /**
7151          * Takes formatted response and creates a modal pop-over containing a title and content
7152          */
7153         displayView : function(o) {
7154                 var SED = SUGAR.email2.detailView;
7155                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7156
7157                 if(!SED.viewDialog) {
7158                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7159                                 modal:true,
7160                 visible:true,
7161                 fixedcenter:true,
7162                 constraintoviewport: true,
7163                                 shadow  : true
7164                         });
7165             SED.viewDialog.renderEvent.subscribe(function() {
7166                 var content = this.body.firstChild;
7167                 var viewH = YAHOO.util.Dom.getViewportHeight();
7168                 if (content) {
7169                         this.body.style.overflow = "auto";
7170                         this.body.style.width = "800px";
7171                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7172                 }
7173             }, SED.viewDialog);
7174                 } // end lazy load
7175                 SED.viewDialog.setHeader(ret.title);
7176                 SED.viewDialog.setBody(ret.html);
7177                 SED.viewDialog.render();
7178                 SED.viewDialog.show();
7179         },
7180
7181         /**
7182          * Generates a modal popup to populate with the contents of bean's full EditView
7183          */
7184         showQuickCreateForm : function(o) {
7185                 var SED = SUGAR.email2.detailView;
7186                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7187
7188                 if(!SED.quickCreateDialog) {
7189                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7190                                 modal:true,
7191                                 visible:true,
7192                 fixedcenter:true,
7193                 constraintoviewport: true,
7194                                 shadow  : true
7195                         });
7196
7197             SED.quickCreateDialog.renderEvent.subscribe(function() {
7198                 var viewH = YAHOO.util.Dom.getViewportHeight();
7199                 var contH = 0;
7200                 for (var i in this.body.childNodes) {
7201                         if (this.body.childNodes[i].clientHeight) {
7202                                 contH += this.body.childNodes[i].clientHeight;
7203                         } else if (this.body.childNodes[i].offsetHeight) {
7204                                 contH += this.body.childNodes[i].offsetHeight;
7205                         } // if
7206                 }
7207                         this.body.style.width = "800px";
7208                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7209                         this.body.style.overflow = "auto";
7210             }, SED.quickCreateDialog);
7211
7212             SED.quickCreateDialog.hideEvent.subscribe(function(){
7213                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7214                                 /*for(var qsField in qsFields){
7215                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7216                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7217                                 }*/
7218                         });
7219             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7220                 } // end lazy load
7221                 if (ret.html) {
7222                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7223                 }
7224                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7225                 SED.quickCreateDialog.render();
7226                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7227
7228                 SED.quickCreateDialog.ieId = ret.ieId;
7229                 SED.quickCreateDialog.uid = ret.uid;
7230         SED.quickCreateDialog.mbox = ret.mbox;
7231         SED.quickCreateDialog.qcmodule = ret.module;
7232
7233         SED.quickCreateDialog.show();
7234
7235                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7236                 if (editForm) {
7237                   editForm.module.value = 'Emails';
7238                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7239                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7240                   var instId = ret.module + count;
7241                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7242                   SED.quickCreateEmailCallback = function(instId, tableId) {
7243                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7244                           if (typeof(eaw) == "undefined")
7245                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7246                                                 + instId + "','" + tableId + "');", 100);
7247                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7248                   }
7249                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7250                                         + instId + "','" + tableId + "');", 100);
7251                 }
7252         },
7253
7254         saveQuickCreateForm : function(o) {
7255             hideOverlay();
7256                 SUGAR.email2.detailView.quickCreateDialog.hide();
7257                 validate['EditView'] = [ ];
7258         },
7259
7260         saveQuickCreateFormAndReply : function(o) {
7261             hideOverlay();
7262             var ret = YAHOO.lang.JSON.parse(o.responseText);
7263         SUGAR.email2.detailView.quickCreateDialog.hide();
7264         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7265         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7266         if (ret) {
7267             var emailID = ret.id;
7268             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7269         } else {
7270             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7271         }
7272         //Cean the validate cache to prevent errors on the next call
7273         validate['EditView'] = [ ];
7274     },
7275
7276         saveQuickCreateFormAndAddToAddressBook : function(o) {
7277            hideOverlay();
7278                 SUGAR.email2.detailView.quickCreateDialog.hide();
7279                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7280                 validate['EditView'] = [ ];
7281         },
7282
7283         handleAssignmentDialogAssignAction : function() {
7284
7285
7286             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7287
7288             var dist = 'direct';
7289             var users = false;
7290             var rules = false;
7291             var get = "";
7292             var found_teams = false;
7293             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7294             if(!found_teams && assign_user_id == '' )
7295             {
7296                 alert(warning_message);
7297                 return;
7298             }
7299
7300             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7301             var uids = "";
7302             for(i=0; i<emailUids.length; i++) {
7303                 if(uids != '') {
7304                     uids += app_strings.LBL_EMAIL_DELIMITER;
7305                 }
7306                 uids += emailUids[i];
7307             }
7308
7309             var row = SUGAR.email2.grid.getSelectedRows()[0];
7310             var data = SUGAR.email2.grid.getRecord(row).getData();
7311             var ieid = data.ieId;
7312             var mbox = data.mbox;
7313             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7314             SUGAR.email2.contextMenus.assignToDialogue.hide();
7315             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7316
7317         },
7318
7319         handleAssignmentDialogDeleteAction : function() {
7320                 // TO pass list of UIDS/emailIds
7321                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7322                 var row = SUGAR.email2.grid.getSelections()[0];
7323                 var ieid = row.data.ieId;
7324             var mbox = row.data.mbox;
7325         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7326         SUGAR.email2.contextMenus.assignmentDialog.hide();
7327                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7328
7329                 // AJAX Call
7330
7331         },
7332
7333         showEmailDetailView : function(o) {
7334         hideOverlay();
7335         var SED = SUGAR.email2.detailView;
7336                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7337
7338                 if(!SED.quickCreateDialog) {
7339                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7340                                 modal:true,
7341                                 visible:true,
7342                 //fixedcenter:true,
7343                 constraintoviewport: true,
7344                 draggable: true,
7345                                 autofillheight: "body",
7346                                 shadow  : true
7347                         });
7348                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7349                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7350                 var contH = 0;
7351                 for (var i in this.body.childNodes) {
7352                         if (this.body.childNodes[i].offsetHeight)
7353                                 contH += this.body.childNodes[i].offsetHeight;
7354                 }
7355                         this.body.style.overflow = "auto";
7356                         this.body.style.width = "800px";
7357                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7358                         this.center();
7359             }, SED.quickCreateDialog);
7360                 }
7361                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7362                 SED.quickCreateDialog.setBody(ret.html);
7363                 SED.quickCreateDialog.render();
7364         SUGAR.util.evalScript(ret.html);
7365         SED.quickCreateDialog.show();
7366         },
7367
7368         showAssignmentDialogWithData : function(o) {
7369         var SEC = SUGAR.email2.contextMenus;
7370                 hideOverlay();
7371         var ret = YAHOO.lang.JSON.parse(o.responseText);
7372         if (!SEC.assignmentDialog) {
7373                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7374                         visible:false,
7375                 fixedcenter:true,
7376                 constraintoviewport: true,
7377                         modal   : true
7378                 });
7379                 SEC.assignmentDialog.setBody("");
7380                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7381                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7382                 var iev = YAHOO.util.Dom.get("Distribute");
7383                 if (iev) {
7384                         this.body.style.width = "700px";
7385                 }
7386             },  SEC.assignmentDialog);
7387                 SEC.assignmentDialog.render();
7388         }
7389         SEC.assignmentDialog.setBody(ret);
7390         SEC.assignmentDialog.render();
7391         validate = [];
7392         SEC.assignmentDialog.show();
7393         SUGAR.util.evalScript(ret);
7394         },
7395
7396         showImportForm : function(o) {
7397                 var SED = SUGAR.email2.detailView;
7398                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7399         
7400         document.getElementById('quickCreateContent').innerHTML = "";
7401         hideOverlay();
7402         if (!ret) {
7403             return false;
7404         }
7405
7406         if(!SED.importDialog) {
7407             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7408                 modal:true,
7409                 visible:false,
7410                 fixedcenter:true,
7411                 constraintoviewport: true,
7412                 buttons : [{
7413                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7414                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7415                 }]//,
7416                 //scroll : true
7417             });
7418             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7419             SED.importDialog.setBody("");
7420             SED.importDialog.hideEvent.subscribe(function(){
7421                 for(var i in QSFieldsArray) {
7422                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7423                                 QSFieldsArray[i].destroy();
7424                                 delete QSFieldsArray[i];
7425                         }
7426                         if (QSProcessedFieldsArray[i]) {
7427                                 QSProcessedFieldsArray[i] = false;
7428                         } // if
7429                                 }
7430             });
7431             SED.importDialog.renderEvent.subscribe(function() {
7432                 var iev = YAHOO.util.Dom.get("ImportEditView");
7433                 if (iev) {
7434                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7435                         this.body.style.width = "600px";
7436                 }
7437             }, SED.importDialog);
7438             SED.importDialog.render();
7439         } // end lazy load
7440         SED.importDialog.setBody(ret.html);
7441         SED.importDialog.ret = ret;
7442         SUGAR.util.evalScript(ret.html);
7443         SED.importDialog.render();
7444         validate = [];
7445         SED.importDialog.show();
7446         SED.importDialog.focusFirstButton();
7447     },
7448     getImportAction : function(ret) {
7449         if (!check_form('ImportEditView')) return false;
7450         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7451                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7452                 return false;
7453         } // if
7454                 var get = "";
7455         var editView = document.getElementById('ImportEditView');
7456         if (editView.assigned_user_id != null) {
7457             get = get + "&user_id=" + editView.assigned_user_id.value
7458             //var user_id = editView.assigned_user_id.value;
7459         }
7460         var parent_id = editView.parent_id.value;
7461         var parent_type = editView.parent_type.value;
7462         var row = SUGAR.email2.grid.getSelectedRows()[0];
7463         row = SUGAR.email2.grid.getRecord(row);
7464         var data = row.getData();
7465         var ieId = data.ieId;
7466         var mbox = data.mbox;
7467         var serverDelete = editView.serverDelete.checked;
7468         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7469         var uids = "";
7470         for(i=0; i<emailUids.length; i++) {
7471             if(uids != '') {
7472                 uids += app_strings.LBL_EMAIL_DELIMITER;
7473             }
7474             uids += emailUids[i];
7475         }
7476
7477         var action = 'importEmail&uid=';
7478         if (ret.move) {
7479             action = 'moveEmails';
7480             action = action + '&sourceFolder=' + ret['srcFolder'];
7481             action = action + '&sourceIeId=' + ret['srcIeId'];
7482             action = action + '&destinationFolder=' + ret['dstFolder'];
7483             action = action + '&destinationIeId=' + ret['dstIeId'];
7484             action = action + '&emailUids=';
7485         }
7486         if (action.search(/importEmail/) != -1) {
7487             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7488         } else {
7489             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7490         }
7491
7492         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7493         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7494         SUGAR.email2.detailView.importDialog.hide();
7495         document.getElementById('importDialogContent').innerHTML = "";
7496
7497     },
7498     showRelateForm : function(o) {
7499         var SED = SUGAR.email2.detailView;
7500         var ret = YAHOO.lang.JSON.parse(o.responseText);
7501         document.getElementById('quickCreateContent').innerHTML = "";
7502         hideOverlay();
7503         if (!ret) {
7504             return false;
7505         }
7506         dialog_loaded = true;
7507
7508         if(!SED.relateDialog) {
7509             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7510                                 modal:true,
7511                                 visible:true,
7512                 fixedcenter:true,
7513                 width: '800px',
7514                 constraintoviewport: true,
7515                                 buttons : [{
7516                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7517                                         if (!check_form('RelateEditView')) return false;
7518                                         var get = "";
7519                         var editView = document.getElementById('RelateEditView');
7520                         var parent_id = editView.parent_id.value;
7521                         var parent_type = editView.parent_type.value;
7522                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7523                         row  = SUGAR.email2.grid.getRecord(row);
7524                         var ieId = row.getData().ieId;
7525                         var mbox = row.getData().mbox;
7526                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7527                         var uids = "";
7528                         for(i=0; i<emailUids.length; i++) {
7529                             if(uids != '') {
7530                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7531                             }
7532                             uids += emailUids[i];
7533                         }
7534                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7535                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7536                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7537                         SED.relateDialog.hide();
7538                         document.getElementById('relateDialogContent').innerHTML = "";
7539                         }
7540                 }]
7541                         });
7542
7543             SED.relateDialog.hideEvent.subscribe(function(){
7544                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7545                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7546                         delete QSFieldsArray['ImportEditView_parent_name'];
7547                 } // if
7548                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7549                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7550                                 } // if
7551             });
7552
7553             SED.relateDialog.renderEvent.subscribe(function() {
7554                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7555                 var contH = 0;
7556                 for (var i in this.body.childNodes) {
7557                         if (this.body.childNodes[i].clientHeight)
7558                                 contH += this.body.childNodes[i].clientHeight;
7559                 }
7560             }, SED.relateDialog);
7561             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7562                 } // end lazy load
7563
7564         SED.relateDialog.setBody(ret.html);
7565         SED.relateDialog.render();
7566         SUGAR.util.evalScript(ret.html);
7567         SED.relateDialog.show();
7568     }
7569 };
7570 /**
7571  * DetailView callbacks
7572  */
7573 AjaxObject.detailView.callback = {
7574         emailDetail : {
7575                 success : function(o) {
7576                         SUGAR.email2.o = o;
7577                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7578                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7579                 },
7580                 argument: [targetDiv],
7581                 failure : AjaxObject.handleFailure,
7582                 timeout : 0,
7583                 scope   : AjaxObject
7584         },
7585         emailPreview : {
7586                 success : function(o) {
7587                         SUGAR.email2.o = o;
7588                         var ret = YAHOO.lang.JSON.parse(o.responseText);
7589                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7590                 },
7591                 failure : AjaxObject.handleFailure,
7592                 timeout : 0,
7593                 scope   : AjaxObject
7594         },
7595         viewPrint : {
7596                 success : AjaxObject.detailView.displayPrintable,
7597                 failure : AjaxObject.handleFailure,
7598                 timeout : AjaxObject.timeout,
7599                 scope   : AjaxObject
7600         },
7601         viewRaw : {
7602                 success : AjaxObject.detailView.displayView,
7603                 failure : AjaxObject.handleFailure,
7604                 timeout : AjaxObject.timeout,
7605                 scope   : AjaxObject
7606         }
7607 };
7608
7609
7610
7611
7612
7613 AjaxObject.folders = {
7614         /**
7615          * check-mail post actions
7616          */
7617         checkMailCleanup : function(o) {
7618                 hideOverlay();
7619                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7620
7621                 // refresh focus ListView
7622                 SE.listView.refreshGrid();
7623                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7624         },
7625
7626         /**
7627          */
7628         rebuildFolders : function(o) {
7629                 hideOverlay();
7630
7631                 var data = YAHOO.lang.JSON.parse(o.responseText);
7632
7633                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7634                 SUGAR.email2.folders.setSugarFolders();
7635         }
7636 };
7637 AjaxObject.folders.callback = {
7638         checkMail : {
7639                 success : AjaxObject.folders.checkMailCleanup,
7640                 failure : AjaxObject.handleFailure,
7641                 timeout : 600000, // 5 mins
7642                 scope   : AjaxObject
7643         }
7644 }
7645
7646 AjaxObject.rules = {
7647         loadRulesForSettings : function(o) {
7648                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7649                 // assume we have the class we need
7650                 SUGAR.routing.getStrings();
7651                 SUGAR.routing.getDependentDropdowns();
7652         }
7653 };
7654 ////    END PER MODULE CALLBACK OBJECTS
7655 ///////////////////////////////////////////////////////////////////////////
7656
7657
7658 var callback = {
7659         success : AjaxObject.handleSuccess,
7660         failure : AjaxObject.handleFailure,
7661         timeout : AjaxObject.timeout,
7662         scope   : AjaxObject
7663 };
7664 var callbackAccount = {
7665         success : AjaxObject.ieSaveSuccess,
7666         failure : AjaxObject.handleFailure,
7667         timeout : AjaxObject.timeout,
7668         scope   : AjaxObject
7669 };
7670 var callbackAccountDelete = {
7671         success : AjaxObject.ieDeleteSuccess,
7672         failure : AjaxObject.handleFailure,
7673         timeout : AjaxObject.timeout,
7674         scope   : AjaxObject
7675 };
7676 var callbackOutboundTest = {
7677         success : AjaxObject.ieSendSuccess,
7678         failure : AjaxObject.handleFailure,
7679         timeout : AjaxObject.timeout,
7680         scope   : AjaxObject
7681 };
7682
7683
7684
7685 var callbackTeamInfoForSettings = {
7686 success : function (o) {
7687         var data = YAHOO.lang.JSON.parse(o.responseText);
7688         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7689 },
7690 failure : AjaxObject.handleFailure,
7691 timeout : AjaxObject.timeout,
7692 scope   : AjaxObject
7693
7694 };
7695
7696 var callbackStatusForImport = {
7697 success : function (o) {
7698         hideOverlay();
7699         if (o.responseText != "")  {
7700                 var statusString = "";
7701                 var data = YAHOO.lang.JSON.parse(o.responseText);
7702                 for(i=0; i<data.length; i++) {
7703                         statusString = statusString + data[i] + '<br/>';
7704                 }
7705                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7706         }
7707         SE.listView.refreshGrid();
7708
7709 },
7710 failure : AjaxObject.handleFailure,
7711 timeout : AjaxObject.timeout,
7712 scope   : AjaxObject
7713
7714 };
7715 var callbackComposeCache = {
7716         success : AjaxObject.composeCache,
7717         failure : AjaxObject.handleFailure,
7718         timeout : AjaxObject.timeout,
7719         scope   : AjaxObject
7720 };
7721 var callbackDelete = {
7722         success : AjaxObject.handleDeleteReturn,
7723         failure : AjaxObject.handleFailure,
7724         timeout : AjaxObject.timeout,
7725         scope   : AjaxObject
7726 };
7727 var callbackEmailDetailMultiple = {
7728         success : function(o) {
7729                 hideOverlay();
7730                 var retMulti = YAHOO.lang.JSON.parse(o.responseText);
7731                 var ret = new Object();
7732
7733                 for(var i=0; i<retMulti.length; i++) {
7734                         ret = retMulti[i];
7735
7736                         SUGAR.email2._setDetailCache(ret);
7737                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7738                 }
7739         },
7740         failure : AjaxObject.handleFailure,
7741         timeout : 0,
7742         scope   : AjaxObject
7743 };
7744 var callbackListViewSortOrderChange = {
7745         success : AjaxObject.saveListViewSortOrderPart2,
7746         failure : AjaxObject.handleFailure,
7747         timeout : AjaxObject.timeout,
7748         scope   : AjaxObject,
7749         argument        : [ieId, ieName, focusFolder]
7750 };
7751 var callbackEmptyTrash = {
7752         success : function(o) {
7753                 hideOverlay();
7754                 AjaxObject.folderRenameCleanup;
7755         },
7756         failure : AjaxObject.handleFailure,
7757         timeout : AjaxObject.timeout,
7758         scope   : AjaxObject
7759 };
7760 var callbackClearCacheFiles = {
7761         success : function(o) {
7762                 hideOverlay();
7763         },
7764         failure : AjaxObject.handleFailure,
7765         timeout : AjaxObject.timeout,
7766         scope   : AjaxObject
7767 };
7768 var callbackFolderRename = {
7769         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7770         failure : AjaxObject.handleFailure,
7771         timeout : AjaxObject.timeout,
7772         scope   : AjaxObject
7773 };
7774 var callbackFolderDelete = {
7775         success : function(o) {
7776                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7777                 if (ret.status) {
7778                     if (ret.folder_id) {
7779                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7780                         if(node)
7781                                 SUGAR.email2.tree.removeNode(node, true);
7782                     } else if (ret.ieId && ret.mbox) {
7783                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7784                         if(node)
7785                                 SUGAR.email2.tree.removeNode(node, true);
7786                     }
7787                         hideOverlay();
7788                         //SUGAR.email2.folders.loadSettingFolder();
7789                 } else {
7790                         hideOverlay();
7791                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7792                 } // else
7793         },
7794         failure : AjaxObject.handleFailure,
7795         timeout : AjaxObject.timeout,
7796         scope   : AjaxObject
7797 };
7798 var callbackFolderSave = {
7799         success : function(o) {
7800                 var ret = YAHOO.lang.JSON.parse(o.responseText);
7801
7802                 switch(ret.action) {
7803                         case 'newFolderSave':
7804                                 SUGAR.email2.folders.rebuildFolders();
7805                         break;
7806                 }
7807         },
7808         failure : AjaxObject.handleFailure,
7809         timeout : AjaxObject.timeout,
7810         scope   : AjaxObject
7811 };
7812 var callbackFolderSubscriptions = {
7813         success : AjaxObject.updateFolderSubscriptions,
7814         failure : AjaxObject.handleFailure,
7815         timeout : AjaxObject.timeout,
7816         scope   : AjaxObject
7817 };
7818 var callbackFolderUpdate = {
7819         success : AjaxObject.updateFrameFolder,
7820         failure : AjaxObject.handleFailure,
7821         timeout : AjaxObject.timeout,
7822         scope   : AjaxObject
7823 };
7824 var callbackFolders = {
7825         success : AjaxObject.folders.rebuildFolders,
7826         //success : void(true),
7827         failure : AjaxObject.handleFailure,
7828         timeout : AjaxObject.timeout,
7829         scope   : AjaxObject
7830 };
7831 var callbackFullSync = {
7832         success : AjaxObject.fullSyncCleanup,
7833         failure : AjaxObject.handleFailure,
7834         timeout : 9999999999999,
7835         scope   : AjaxObject
7836 };
7837 var callbackGeneric = {
7838         success : function() {
7839                 hideOverlay();
7840         },
7841         failure : AjaxObject.handleFailure,
7842         timeout : AjaxObject.timeout,
7843         scope   : AjaxObject
7844 };
7845 var callbackIeAccountRetrieve = {
7846         success : function(o) {
7847                 // return JSON encoding
7848                 hideOverlay();
7849                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7850                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7851         },
7852         failure : AjaxObject.handleFailure,
7853         timeout : AjaxObject.timeout,
7854         scope   : AjaxObject
7855 };
7856 var callbackImportOneEmail = {
7857         success :  AjaxObject.detailView.showImportForm,
7858         failure : AjaxObject.handleFailure,
7859         timeout : AjaxObject.timeout,
7860         scope   : AjaxObject
7861 };
7862 var callbackRelateEmail = {
7863     success : AjaxObject.detailView.showRelateForm,
7864     failure : AjaxObject.handleFailure,
7865     timeout : AjaxObject.timeout,
7866     scope   : AjaxObject
7867 }
7868 var callbackEmailDetailView = {
7869     success : AjaxObject.detailView.showEmailDetailView,
7870     failure : AjaxObject.handleFailure,
7871     timeout : AjaxObject.timeout,
7872     scope   : AjaxObject
7873 }
7874 var callbackAssignmentDialog = {
7875         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7876         failure : AjaxObject.handleFailure,
7877         timeout : AjaxObject.timeout,
7878         scope   : AjaxObject
7879 };
7880 var callbackAssignmentAction = {
7881         success :  function(o) {
7882                 SE.listView.refreshGrid();
7883                 hideOverlay();
7884                 if(o.responseText != '') {
7885                overlay('Assignment action result', o.responseText, 'alert');
7886             } // if
7887         } ,
7888         failure : AjaxObject.handleFailure,
7889         timeout : AjaxObject.timeout,
7890         scope   : AjaxObject
7891 };
7892 var callbackMoveEmails = {
7893         success :  function(o) {
7894             SE.listView.refreshGrid();
7895                 hideOverlay();
7896                 if(o.responseText != '') {
7897                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7898             } // if
7899         } ,
7900         failure : AjaxObject.handleFailure,
7901         timeout : AjaxObject.timeout,
7902         scope   : AjaxObject
7903 };
7904 var callbackLoadAttachments = {
7905         success : AjaxObject.loadAttachments,
7906         failure : AjaxObject.handleFailure,
7907         timeout : AjaxObject.timeout,
7908         scope   : AjaxObject
7909 };
7910 var callbackLoadRules = {
7911         success : AjaxObject.rules.loadRulesForSettings,
7912         failure : AjaxObject.handleFailure,
7913         timeout : AjaxObject.timeout,
7914         scope   : AjaxObject
7915 };
7916 var callbackLoadSignature = {
7917         success : AjaxObject.loadSignature,
7918         failure : AjaxObject.handleFailure,
7919         timeout : AjaxObject.timeout,
7920         scope   : AjaxObject
7921 };
7922 var callbackDeleteSignature = {
7923         success : AjaxObject.handleDeleteSignature,
7924         failure : AjaxObject.handleFailure,
7925         timeout : AjaxObject.timeout,
7926         scope   : AjaxObject
7927 };
7928 /*var callbackMoveEmails = {
7929     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7930     failure : AjaxObject.handleFailure,
7931     timeout : AjaxObject.timeout,
7932     scope   : AjaxObject
7933 }*/
7934 var callbackOutboundSave = {
7935         success : AjaxObject.accounts.saveOutboundCleanup,
7936         failure : AjaxObject.handleFailure,
7937         timeout : AjaxObject.timeout,
7938         scope   : AjaxObject
7939 };
7940 var callbackDefaultOutboundSave = {
7941         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7942         failure : AjaxObject.handleFailure,
7943         timeout : AjaxObject.timeout,
7944         scope   : AjaxObject
7945 };
7946 var callbackQuickCreate = {
7947         success : AjaxObject.detailView.showQuickCreateForm,
7948         failure : AjaxObject.handleFailure,
7949         timeout : AjaxObject.timeout,
7950         scope   : AjaxObject
7951 };
7952 var callbackQuickCreateSave = {
7953         success : AjaxObject.detailView.saveQuickCreateForm,
7954         failure : AjaxObject.handleFailure,
7955         timeout : AjaxObject.timeout,
7956         scope   : AjaxObject
7957 };
7958 var callbackQuickCreateSaveAndAddToAddressBook = {
7959         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7960         failure : AjaxObject.handleFailure,
7961         timeout : AjaxObject.timeout,
7962         scope   : AjaxObject
7963 };
7964 var callbackQuickCreateSaveAndReply = {
7965     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7966     failure : AjaxObject.handleFailure,
7967     timeout : AjaxObject.timeout,
7968     scope   : AjaxObject
7969 }
7970 var callbackQuickCreateSaveAndReplyCase = {
7971     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7972     failure : AjaxObject.handleFailure,
7973     timeout : AjaxObject.timeout,
7974     scope   : AjaxObject
7975 }
7976 var callbackRebuildShowAccountList = {
7977         success : AjaxObject.rebuildShowFolders,
7978         failure : AjaxObject.handleFailure,
7979         timeout : AjaxObject.timeout,
7980         scope   : AjaxObject
7981 };
7982
7983 var callbackRefreshSugarFolders = {
7984         success : function(o) {
7985                 var t = YAHOO.lang.JSON.parse(o.responseText);
7986                 SUGAR.email2.folders.setSugarFoldersEnd(t);
7987         },
7988         failure : AjaxObject.handleFailure,
7989         timeout : AjaxObject.timeout,
7990         scope   : AjaxObject
7991 };
7992 var callbackReplyForward = {
7993         success : AjaxObject.handleReplyForward,
7994         finish : function(a, retryCount) {
7995                 if (typeof(retryCount) == 'undefined') {
7996                         retryCount = 0;
7997                 } else {
7998                         retryCount++;
7999                 }
8000                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8001                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
8002         try {
8003                         var html = t.getContent();
8004
8005             html = "&nbsp;<div><hr></div>" + a.description;
8006
8007                         t.setContent(html);//
8008
8009             if (a.type != 'draft') {
8010                 // Next step, attach signature
8011                 SUGAR.email2.composeLayout.resizeEditorSetSignature(idx,true);
8012             }
8013
8014                 } catch(e) {
8015                         if (retryCount < 5) {
8016                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
8017                                 return;
8018                         }
8019                 }
8020                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
8021                 if (tabArray != null && tabArray.length > 0) {
8022                         for (i = 0 ; i < tabArray.length ; i++) {
8023                                 var tabObject = tabArray[i];
8024                                 if (tabObject.get("id") == ("composeTab" + idx)) {
8025                                         var tabLabel = a.name;
8026                                 if (tabLabel != null && tabLabel.length > 25) {
8027                                         tabLabel = tabLabel.substring(0, 25) + "...";
8028                                 } // if
8029                                         tabObject.get("labelEl").firstChild.data = tabLabel;
8030                                         break;
8031                                 }
8032                         }
8033                 }
8034
8035                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
8036                 if (a.parent_name != null && a.parent_name != "") {
8037                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
8038                 }
8039                 if (a.parent_type != null && a.parent_type != "") {
8040                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
8041                 }
8042                 if (a.parent_id != null && a.parent_id != "") {
8043                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
8044                 }
8045                 if (a.fromAccounts.status) {
8046                         var addressFrom = document.getElementById('addressFrom' + idx);
8047                 SUGAR.email2.util.emptySelectOptions(addressFrom);
8048                 var fromAccountOpts = a.fromAccounts.data;
8049                 for(i=0; i<fromAccountOpts.length; i++) {
8050                       var key = fromAccountOpts[i].value;
8051                       var display = fromAccountOpts[i].text;
8052                       var opt = new Option(display, key);
8053                       if (fromAccountOpts[i].selected) {
8054                         opt.selected = true;
8055                       }
8056                       addressFrom.options.add(opt);
8057                 }
8058                 } // if
8059                 hideOverlay();
8060
8061         },
8062         failure : AjaxObject.handleFailure,
8063         timeout : AjaxObject.timeout,
8064         scope   : AjaxObject,
8065         argument        : [sendType]
8066 };
8067 var callbackSendEmail = {
8068         success : AjaxObject.sendEmailCleanUp,
8069         failure : AjaxObject.handleFailure,
8070         timeout : AjaxObject.timeout,
8071         scope   : AjaxObject
8072 };
8073 var callbackSettings = {
8074         success : AjaxObject.updateUserPrefs,
8075         failure : AjaxObject.handleFailure,
8076         timeout : AjaxObject.timeout,
8077         scope   : AjaxObject
8078 };
8079 var callbackSettingsFolderRefresh = {
8080         success : AjaxObject.settingsFolderRefresh,
8081         failure : AjaxObject.handleFailure,
8082         timeout : AjaxObject.timeout,
8083         scope   : AjaxObject
8084 };
8085 var callbackLoadSettingFolder = {
8086         success : function(o) {
8087                 AjaxObject.settingsFolderRefresh(o);
8088                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8089         },
8090         failure : AjaxObject.handleFailure,
8091         timeout : AjaxObject.timeout,
8092         scope   : AjaxObject
8093
8094 };
8095 var callbackUploadAttachment = {
8096         success : AjaxObject.uploadAttachmentSuccessful,
8097         upload  : AjaxObject.uploadAttachmentSuccessful,
8098         failure : AjaxObject.handleFailure,
8099         timeout : AjaxObject.timeout,
8100         scope   : AjaxObject
8101 };
8102 var callbackUserPrefs = {
8103         success : function(o) {
8104                 SUGAR.email2.userPrefs = YAHOO.lang.JSON.parse(o.responseText);
8105         },
8106         failure : AjaxObject.handleFailure,
8107         timeout : AjaxObject.timeout,
8108         scope   : AjaxObject
8109 };
8110
8111 var callbackContextmenus = {
8112         markUnread : {
8113                 success : AjaxObject.markEmailCleanup,
8114                 failure : AjaxObject.handleFailure,
8115                 timeout : AjaxObject.timeout,
8116                 scope   : AjaxObject
8117         }
8118 };
8119
8120 var callbackCheckEmail2 = {
8121         success : function(o) {
8122                 var ret = YAHOO.lang.JSON.parse(o.responseText);
8123                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8124
8125
8126         },
8127         failure : AjaxObject.handleFailure,
8128         timeout : AjaxObject.timeout,
8129         scope   : AjaxObject
8130 }// End of File modules/Emails/javascript/ajax.js
8131                                 
8132 /*********************************************************************************
8133  * SugarCRM Community Edition is a customer relationship management program developed by
8134  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8135  * 
8136  * This program is free software; you can redistribute it and/or modify it under
8137  * the terms of the GNU Affero General Public License version 3 as published by the
8138  * Free Software Foundation with the addition of the following permission added
8139  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8140  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8141  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8142  * 
8143  * This program is distributed in the hope that it will be useful, but WITHOUT
8144  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8145  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8146  * details.
8147  * 
8148  * You should have received a copy of the GNU Affero General Public License along with
8149  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8150  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8151  * 02110-1301 USA.
8152  * 
8153  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8154  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8155  * 
8156  * The interactive user interfaces in modified source and object code versions
8157  * of this program must display Appropriate Legal Notices, as required under
8158  * Section 5 of the GNU Affero General Public License version 3.
8159  * 
8160  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8161  * these Appropriate Legal Notices must retain the display of the "Powered by
8162  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8163  * technical reasons, the Appropriate Legal Notices must display the words
8164  * "Powered by SugarCRM".
8165  ********************************************************************************/
8166
8167 function gridInit() {
8168         if(SUGAR.email2.grid) {
8169                 SUGAR.email2.grid.destroy();
8170         }
8171         
8172         e2Grid = {
8173                 init : function() {
8174                 
8175                         var Ck = YAHOO.util.Cookie;
8176                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8177
8178                         if (Ck.get("EmailGridWidths")) {
8179                                 for (var i=0; i < widths.length; i++) {
8180                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8181                                 }
8182                         } else {
8183                                 for (var i=0; i < widths.length; i++) {
8184                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8185                                 }
8186                         }
8187                         
8188                         // changes "F" to an icon
8189                         function flaggedIcon(cell, record, column, value) {
8190                                 if(value != "") {
8191                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8192                                 }
8193                         }
8194                         // changes "A" to replied icon
8195                         function repliedIcon(cell, record, column, value) {
8196                                 if(value != "") {
8197                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8198                                 }
8199                         }
8200                 function attachIcon(cell, record, column, value) {
8201                                 if(value == "1") {
8202                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8203                                 }
8204                         }
8205
8206                         var colModel = 
8207                                 [
8208                                         {
8209                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8210                                                 width: 10, 
8211                                                 sortable: false, 
8212                                                 fixed: true,
8213                                                 resizeable: true,
8214                                                 formatter: attachIcon,
8215                                                 key: 'hasAttach'
8216                                         }, 
8217                                     {
8218                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8219                                                 width: widths[0], 
8220                                                 sortable: true, 
8221                                                 fixed: true,
8222                                                 resizeable: true,
8223                                                 formatter: flaggedIcon,
8224                                                 key: 'flagged'
8225                                         }, 
8226                                         {
8227                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8228                                                 width: widths[1], 
8229                                                 sortable: true, 
8230                                                 fixed: true,
8231                                                 resizeable: true,
8232                                                 formatter: repliedIcon,
8233                                                 key: 'status'
8234                                         },
8235                                         {
8236                                                 label: app_strings.LBL_EMAIL_FROM, 
8237                                                 width: widths[2],
8238                                                 sortable: true,
8239                                                 resizeable: true,
8240                                                 key: 'from'
8241                                         }, 
8242                                         {
8243                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8244                                                 width: widths[3], 
8245                                                 sortable: true,
8246                                                 resizeable: true,
8247                                                 key: 'subject'
8248                                         }, 
8249                                         {
8250                                                 label: mod_strings.LBL_LIST_DATE,
8251                                                 width: widths[4], 
8252                                                 sortable: true,
8253                                                 resizeable: true,
8254                         key: 'date'
8255                                         }, 
8256                                         {
8257                                                 label: app_strings.LBL_EMAIL_TO,
8258                                                 width: widths[5], 
8259                                                 sortable: false,
8260                                                 resizeable: true,
8261                         key: 'to_addrs'
8262                                         }, 
8263                                         {
8264                                                 label: 'uid',
8265                                                 hidden: true,
8266                         key: 'uid'
8267                                         }, 
8268                                         {
8269                                                 label: 'mbox',
8270                                                 hidden: true,
8271                         key: 'mbox'
8272                                         }, 
8273                                         {
8274                                                 label: 'ieId',
8275                                                 hidden: true,
8276                         key: 'ieId'
8277                                         }, 
8278                                         {       
8279                                                 label: 'site_url',
8280                                                 hidden: true,
8281                         key: 'site_url'
8282                                         },
8283                                         {       label: 'seen',
8284                                                 hidden: true,
8285                         key: 'seen'
8286                                         },
8287                                         {       label: 'type',
8288                                                 hidden: true,
8289                         key: 'type'
8290                                         }
8291                                 ];
8292                         
8293                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8294                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8295                                 responseSchema: {
8296                                     resultsList: 'Email',
8297                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8298                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8299                                 }
8300                     });
8301                         var params = {
8302                                         to_pdf : "true",
8303                                         module : "Emails",
8304                                         action : "EmailUIAjax",
8305                                         emailUIAction : "getMessageList",
8306                                         mbox : "INBOX",
8307                                         ieId : "",
8308                                         forceRefresh : "false"
8309                         };
8310                         if(lazyLoadFolder != null) {
8311                                 params['mbox'] = lazyLoadFolder.folder;
8312                                 params['ieId'] = lazyLoadFolder.ieId;
8313                                 //Check if the folder is a Sugar Folder
8314                                 var test = new String(lazyLoadFolder.folder);
8315                                 if(test.match(/SUGAR\./)) {
8316                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8317                                         params['mbox'] = test.substr(6);
8318                                 }
8319                         }
8320                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8321         
8322                         // create the Grid
8323                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8324                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8325                                 dynamicData: true,
8326                                 paginator: new YAHOO.widget.Paginator({ 
8327                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8328                                         containers : ["dt-pag-nav"],
8329                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8330                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8331                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8332                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8333                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8334                                 }),
8335                                 initialRequest:SUGAR.util.paramsToUrl(params),
8336                                 width:  "800px",
8337                                 height: "400px"
8338                         });
8339
8340                         initRowDD();
8341
8342                         //Override Paging request construction
8343                         grid.set("generateRequest", function(oState, oSelf) {
8344                     oState = oState || {pagination:null, sortedBy:null};
8345                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8346                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8347                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8348                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8349                     // Build the request 
8350                     var ret = 
8351                             SUGAR.util.paramsToUrl(oSelf.params) + 
8352                             "&sort=" + sort +
8353                         "&dir=" + dir +
8354                         "&start=" + startIndex +
8355                         ((results !== null) ? "&limit=" + results : "");
8356                     return  ret;
8357                 });
8358                         
8359                         
8360                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8361                                 oPayload = oPayload || { };
8362                                 
8363                                 oPayload.totalRecords = oResponse.meta.total;
8364                                 oPayload.unreadRecords = oResponse.meta.unread;
8365                                 
8366                         var tabObject = SE.innerLayout.get("tabs")[0];
8367                         var mboxTitle = "";
8368                         if (this.params.mbox != null) {
8369                                 mboxTitle = this.params.mbox;
8370                         }
8371                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8372                         tabObject.get("labelEl").firstChild.data = tabtext;
8373                         
8374                         if (SE.tree) {
8375                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8376                                 if (node) {
8377                                         node.data.unseen = oResponse.meta.unread;
8378                                         SE.accounts.renderTree();
8379                                 }
8380                         }
8381                                 return oPayload; 
8382                         }
8383                         
8384                         var resize = grid.resizeGrid = function () {
8385                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8386                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8387                         }
8388                         grid.convertDDRows = function() {
8389                                 var rowEl = this.getFirstTrEl();
8390                                 while (rowEl != null) {
8391                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8392                                         rowEl = this.getNextTrEl(rowEl);
8393                                 }
8394                         }
8395                         
8396                         
8397                         grid.on("columnResizeEvent", function(o) {
8398                                 //Find the index of the column
8399                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8400                                 for (var i=0; i < colSet.length; i++) {
8401                                         if (o.column == colSet[i]) {
8402                                                 //Store it in the cookie
8403                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8404                                         }
8405                                 }
8406                                 //this.resizeGrid();
8407                         }, null, grid); 
8408                         
8409                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8410                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8411                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8412                         grid.render();
8413                         SUGAR.email2.listViewLayout.on("render", resize);
8414                         resize();
8415                         
8416                         //Setup the default load parameters
8417                         SUGAR.email2.grid.params = params;
8418                         
8419                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8420                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8421                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8422                 }
8423         };
8424         e2Grid.init();
8425 };
8426
8427
8428 function initRowDD() {
8429         var sg = SUGAR.email2.grid,
8430         Dom = YAHOO.util.Dom;
8431         sg.DDRow = function(oDataTable, oRecord, elTr) {
8432                 if(oDataTable && oRecord && elTr) {
8433                         this.ddtable = oDataTable;
8434                 this.table = oDataTable.getTableEl();
8435                 this.row = oRecord;
8436                 this.rowEl = elTr;
8437                 this.newIndex = null;
8438                 this.init(elTr);
8439                 this.initFrame(); // Needed for DDProxy
8440                 this.invalidHandleTypes = {};
8441             }   
8442         };
8443         
8444         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8445             _resizeProxy: function() {
8446                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8447                 var dragEl = this.getDragEl(),
8448                     el = this.getEl();
8449                 var xy = Dom.getXY(el);
8450                 
8451                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8452                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8453                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8454                 Dom.setStyle(dragEl, 'display', "");
8455             },
8456             
8457             startDrag: function(x, y) { 
8458                 //Check if we should be dragging a set of rows rather than just the one.
8459                 var selectedRows = this.ddtable.getSelectedRows();
8460                 var iSelected = false;
8461                 for (var i in selectedRows) {
8462                         if (this.rowEl.id == selectedRows[i]) {
8463                                 iSelected = true;
8464                                 break
8465                         }
8466                 }
8467                 if (iSelected) {
8468                         this.rows = [];
8469                         for (var i in selectedRows) {
8470                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8471                         }
8472                 } else {
8473                         this.rows = [this.row];
8474                         this.ddtable.unselectAllRows();
8475                         this.ddtable.selectRow(this.row);
8476                 }
8477                 
8478                 //Initialize the dragable proxy
8479                 var dragEl = this.getDragEl(); 
8480                 var clickEl = this.getEl(); 
8481                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8482                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8483                 Dom.addClass(dragEl, "yui-dt-liner");
8484                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8485                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8486                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8487                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8488             },
8489             
8490             clickValidator: function(e) {
8491                 if (this.row.getData()[0] == " ")
8492                         return false;
8493                 var target = YAHOO.util.Event.getTarget(e);
8494                 return ( this.isValidHandleChild(target) && 
8495                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8496             },
8497             /**
8498              * This funciton checks that the target of the drag is a table row in this
8499              * DDGroup and simply moves the sourceEL to that location as a preview.
8500              */
8501             onDragOver: function(ev, id) {
8502                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8503                 if (node && node != this.targetNode) {
8504                         this.targetNode = node;
8505                         SUGAR.email2.folders.unhighliteAll();
8506                         node.highlight();
8507                 }
8508             },
8509             
8510             onDragOut: function(e, id) {
8511                 if (this.targetNode) {
8512                         SUGAR.email2.folders.unhighliteAll();
8513                         this.targetNode = false;
8514                 }
8515             },
8516             endDrag: function() {
8517                 Dom.setStyle(this.getEl(), "opacity", "");
8518                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8519                 if (this.targetNode) {
8520                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8521                 }
8522                 SUGAR.email2.folders.unhighliteAll();
8523                 this.rows = null;
8524             }
8525         });
8526 }
8527
8528 function AddressSearchGridInit() {
8529     function moduleIcon(elCell, oRecord, oColumn, oData) {
8530         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8531     };
8532     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8533         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8534     };
8535     var checkHeader = '<input type="checkbox" ';
8536     if (SUGAR.email2.util.isIe()) {
8537         checkHeader += 'style="top:-5px" ';
8538     }
8539     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8540     var colModel = 
8541             [{
8542                 label: checkHeader,
8543             width: 30,
8544             formatter: selectionCheckBox,
8545             key: 'bean_id'
8546         },
8547             {
8548                 label: mod_strings.LBL_LIST_TYPE,
8549                 width: 25,
8550                 formatter: moduleIcon,
8551                 key: 'bean_module'
8552         },
8553             {
8554                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8555                 width: 180,
8556                 sortable: true,
8557                 key: 'name'
8558             }, 
8559             {
8560                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8561                 width: 300, 
8562                 sortable: true,
8563                 key: 'email'
8564             }];
8565     
8566     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8567                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8568         responseSchema: {
8569             resultsList: 'Person',
8570             fields: ['name', 'email', 'bean_id', 'bean_module'],
8571                     metaFields: {total: 'TotalCount'}
8572         },
8573         //enable sorting on the server accross all data
8574         remoteSort: true
8575     });
8576     dataModel.params = {
8577                 to_pdf          : true,
8578                 module          : "Emails",
8579                 action          : "EmailUIAjax",
8580                 emailUIAction:"getAddressSearchResults"
8581     }
8582     var rb = document.getElementById('hasRelatedBean').checked;
8583         if (rb) {
8584                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8585                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8586                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8587                 dataModel.params['related_bean_id'] = relatedBeanId;
8588                 dataModel.params['related_bean_type'] = relatedBeanType;
8589                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8590         }
8591     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8592     
8593     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8594         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8595                 dynamicData: true,
8596                 paginator: new YAHOO.widget.Paginator({ 
8597                         rowsPerPage: 25,  
8598                         containers : ["dt-pag-nav-addressbook"],
8599                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8600                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8601                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8602                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8603                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8604                 }),
8605                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8606                 width:  "560px",
8607                 height: "250px"
8608     });
8609         //Override Paging request construction
8610         grid.set("generateRequest", function(oState, oSelf) {
8611         oState = oState || {pagination:null, sortedBy:null};
8612         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8613         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8614         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8615         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8616         // Build the request 
8617         var ret = 
8618             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8619             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8620             ((results !== null) ? "&limit=" + results : "");
8621         return  ret;
8622     });
8623     
8624         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8625                 oPayload = oPayload || { };
8626                 oPayload.totalRecords = oResponse.meta.total;
8627                 return oPayload; 
8628         }
8629         
8630         grid.clickToggleSelect= function(args) {
8631                 var isIE = (args.event.target == null);
8632                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8633                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8634                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8635                 }
8636         }
8637         
8638         grid.reSelectRowsOnRender = function (){
8639             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8640         for (var i = 0; i < rows.length; i++) 
8641         {
8642                 var emailAddress = rows[i].getData("email");
8643             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8644             if(alreadyAdded)
8645             {
8646                 rows[i].setData("selected",  true);
8647                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8648             }
8649             else
8650             {
8651                 rows[i].setData("selected",  false);
8652                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8653             }
8654         }
8655         }
8656         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8657         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8658         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8659     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8660     
8661     grid.render();
8662     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8663     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8664     
8665     grid.toggleSelectCheckbox = function(id,checked){
8666         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8667         row.setData("checked",checked);
8668     };
8669     grid.toggleSelect = function(id, checked) {
8670         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8671         checked = row.getData("selected");
8672         if (!checked)
8673         {
8674             SUGAR.email2.addressBook.grid.selectRow(row);
8675             SE.addressBook.insertContactRowToResultTable(id,null)
8676         } else 
8677         {
8678             SUGAR.email2.addressBook.grid.unselectRow(row);
8679             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8680         }
8681         row.setData("selected", !checked);
8682     };
8683     
8684     grid.toggleSelectAll = function(checked) {
8685         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8686         for (var i = 0; i < rows.length; i++) {
8687                         if (typeof(rows[i]) != "undefined")
8688                                 rows[i].setData("checked",  checked);
8689         }
8690         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8691         for (var i = 0; i < checkBoxes.length; i++) {
8692             checkBoxes[i].checked = checked;
8693         }
8694     };
8695     
8696     //Initialize the grid result table.
8697     AddressSearchResultsGridInit();
8698 }
8699
8700
8701
8702 /**
8703 *  Initalize the results table for the address book selection.
8704 *
8705 */
8706 function AddressSearchResultsGridInit()
8707 {
8708     
8709     /* Full name sort funciton to compare by last name if available */
8710     var fullNameSort = function(a, b, desc) {
8711         // Deal with empty values
8712         if(!YAHOO.lang.isValue(a))
8713             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8714         else if(!YAHOO.lang.isValue(b))
8715             return -1;
8716
8717         var aNames = a.getData("name").split(' ');
8718         var bNames = b.getData("name").split(' ');
8719
8720         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8721         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8722
8723         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8724
8725     };
8726     
8727     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8728                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8729                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8730               
8731     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})},
8732                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8733      
8734      var myDataSource = new YAHOO.util.DataSource([]); 
8735          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8736          myDataSource.responseSchema = { 
8737                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8738                 };                                                                 
8739     
8740          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8741                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8742     
8743      var highlightEditableCell = function(oArgs) {
8744             var elCell = oArgs.target;
8745             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8746                 this.highlightCell(elCell);
8747             }
8748         };
8749       
8750      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8751      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8752      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8753      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8754          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8755      
8756      //Setup the context menus
8757      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8758              var task = p_aArgs[1]; 
8759              if(task) 
8760              { 
8761                  var elRow = this.contextEventTarget; 
8762                  elRow = p_myDataTable.getTrEl(elRow); 
8763          
8764                  if(elRow) 
8765                  { 
8766                      switch(task.index) 
8767                      { 
8768                          case 0:     
8769                              var oRecord = p_myDataTable.getRecord(elRow); 
8770                              p_myDataTable.deleteRow(elRow);  
8771                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8772                      } 
8773                  } 
8774              } 
8775          };
8776      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8777                         {trigger:gridResults.getTbodyEl()}); 
8778          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8779          contextMenu.render("addrSearchResultGrid"); 
8780          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8781 }
8782 // End of File modules/Emails/javascript/grid.js
8783                                 
8784 /*********************************************************************************
8785  * SugarCRM Community Edition is a customer relationship management program developed by
8786  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8787  * 
8788  * This program is free software; you can redistribute it and/or modify it under
8789  * the terms of the GNU Affero General Public License version 3 as published by the
8790  * Free Software Foundation with the addition of the following permission added
8791  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8792  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8793  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8794  * 
8795  * This program is distributed in the hope that it will be useful, but WITHOUT
8796  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8797  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8798  * details.
8799  * 
8800  * You should have received a copy of the GNU Affero General Public License along with
8801  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8802  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8803  * 02110-1301 USA.
8804  * 
8805  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8806  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8807  * 
8808  * The interactive user interfaces in modified source and object code versions
8809  * of this program must display Appropriate Legal Notices, as required under
8810  * Section 5 of the GNU Affero General Public License version 3.
8811  * 
8812  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8813  * these Appropriate Legal Notices must retain the display of the "Powered by
8814  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8815  * technical reasons, the Appropriate Legal Notices must display the words
8816  * "Powered by SugarCRM".
8817  ********************************************************************************/
8818
8819
8820 /******************************************************************************
8821  * Initialize Email 2.0 Application
8822  */
8823
8824 //Override Sugar Languge so quick creates work properly
8825
8826
8827 function email2init() {
8828
8829         //Init Tiny MCE
8830     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
8831     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
8832     if (!SUGAR.util.isTouchScreen()) {
8833          tinyMCE.init({
8834                  convert_urls : false,
8835          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
8836          width: tinyConfig.width,
8837          theme: tinyConfig.theme,
8838          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
8839          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
8840          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
8841          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
8842          plugins : tinyConfig.plugins,
8843          elements : tinyConfig.elements,
8844          language : tinyConfig.language,
8845          extended_valid_elements : tinyConfig.extended_valid_elements,
8846          mode: tinyConfig.mode,
8847          strict_loading_mode : true,
8848                  force_br_newlines : true,
8849          forced_root_block : '',
8850          directionality : (typeof(rtl) == "undefined") ? "ltr" : "rtl"
8851      });
8852     }
8853
8854     // initialze message overlay
8855     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
8856             //iframe        : true,
8857             modal       : false,
8858             autoTabs    : true,
8859             width       : 300,
8860             height      : 120,
8861             shadow      : true
8862         }
8863     );
8864         // Hide Sugar menu
8865         if (SUGAR.themes.tempHideLeftCol)
8866         SUGAR.themes.tempHideLeftCol();
8867
8868         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
8869 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
8870
8871         // set defaults for YAHOO.util.DragDropManager
8872         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
8873
8874         SUGAR.email2.nextYear = new Date();
8875         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
8876
8877         
8878     // initialize and display UI framework (complexLayout.js)
8879     complexLayoutInit();
8880     
8881     // initialize and display grid (grid.js)
8882     gridInit();
8883     
8884     // initialize treeview for folders
8885         //onloadTreeinit();
8886         SUGAR.email2.folders.rebuildFolders(true);
8887         
8888         
8889     //Setup the Message Box overlay
8890     /*Ext.MessageBox.maxWidth = 350;
8891     Ext.MessageBox.minProgressWidth = 350;
8892
8893         ///////////////////////////////////////////////////////////////////////////
8894         ////    CONTEXT MENUS
8895         // detailView array
8896         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
8897 */
8898         var SEC = SUGAR.email2.contextMenus; 
8899         
8900         //Grid menu
8901         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
8902                 trigger: SUGAR.email2.grid.get("element"),
8903                 lazyload: true
8904         });
8905         emailMenu.subscribe("beforeShow", function() {
8906                 var oTarget = this.contextEventTarget;
8907                 if (typeof(oTarget) == "undefined")
8908                   return;
8909                 var grid = SUGAR.email2.grid;
8910                 var selectedRows = grid.getSelectedRows();
8911                 var multipleSelected = (selectedRows.length > 1) ? true: false;
8912                 if (!multipleSelected)
8913                 {
8914                         grid.unselectAllRows();
8915                         grid.selectRow(oTarget);
8916                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
8917                 }
8918                 else if(multipleSelected)
8919                 {
8920                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
8921                 }
8922         });
8923         
8924         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
8925         //us to access individual elements easier by name rather than by index
8926         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
8927                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
8928         emailMenu.addItems([
8929         {
8930             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
8931             id: 'showDetailView',
8932             onclick: { fn: SEC.showDetailView }
8933         },
8934         {
8935             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
8936             onclick: { fn: SEC.openMultiple }
8937         },
8938         {
8939             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
8940             onclick: { fn: SEC.archiveToSugar }
8941         },
8942         {
8943             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
8944             id: 'reply',
8945             onclick: { fn: SEC.replyForwardEmailContext }
8946         },
8947         {
8948             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
8949             id: 'replyAll',
8950             onclick: { fn: SEC.replyForwardEmailContext }
8951         },
8952         {
8953             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
8954             id: 'forward',
8955             onclick: { fn: SEC.replyForwardEmailContext }
8956         },
8957         {
8958             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
8959             id: 'delete',
8960             onclick: { fn: SEC.markDeleted }
8961         },
8962         {
8963             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
8964             id: 'print',
8965             onclick: { fn: SEC.viewPrintable }
8966         },                
8967         // Mark... submenu
8968         {
8969             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
8970             submenu: {
8971                         id: "markEmailMenu",
8972                 itemdata : [
8973                     {
8974                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
8975                         onclick: { fn: SEC.markUnread }
8976                     },
8977                     {
8978                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
8979                         onclick: { fn: SEC.markRead }
8980                     },
8981                     {
8982                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
8983                         onclick: { fn: SEC.markFlagged }
8984                     },
8985                     {
8986                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
8987                         onclick: {  fn: SEC.markUnflagged }
8988                     }
8989                 ]
8990             }
8991          },
8992         {
8993             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
8994                 id: 'assignTo',
8995                 onclick: { fn: SEC.assignEmailsTo }
8996          },
8997          {
8998             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
8999             id: 'relateTo',
9000             onclick: { fn: SEC.relateTo }
9001          }
9002     ]);
9003         SEC.emailListContextMenu.render();
9004         
9005         //Handle the Tree folder menu trigger ourselves
9006         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9007
9008         
9009         //Folder Menu
9010     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9011                 trigger: "",
9012                 lazyload: true 
9013         });
9014     SEC.frameFoldersContextMenu.addItems([
9015                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9016                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9017                         onclick: {  fn: function() {
9018                         var node = SUGAR.email2.clickedFolderNode;
9019                         if (node.data.ieId) {
9020                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9021                     }}
9022                 },
9023                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9024                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9025                         onclick: {  fn: function() {
9026                         var node = SUGAR.email2.clickedFolderNode;
9027                         if (node.data.ieId) {
9028                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9029                     }}
9030                 },
9031                 {
9032                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9033                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9034                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9035                 },
9036                 {
9037                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9038                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9039                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9040                 },
9041                 {
9042                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9043                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9044                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9045                  },
9046                  {
9047                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9048                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9049                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9050                   },
9051                  {
9052                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9053                     onclick: {  fn: function() {
9054                         var node = SUGAR.email2.clickedFolderNode;
9055                         if (node.data.ieId) {
9056                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9057                     }}
9058                   } 
9059         ]);
9060     SEC.frameFoldersContextMenu.render();
9061     
9062     SEC.initContactsMenu = function() {
9063         // contacts
9064         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9065                 trigger: "contacts",
9066                 lazyload: true
9067         });
9068         SEC.contactsContextMenu.addItems([
9069                 {
9070                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9071                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9072                 },
9073                 {
9074                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9075                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9076                 }
9077         ]);
9078         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9079                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9080                 if (oTarget && !grid.isSelected(oTarget)) {
9081                         grid.unselectAllRows();
9082                         grid.selectRow(oTarget);
9083                 }
9084         });
9085         SEC.contactsContextMenu.render();
9086         }
9087         
9088         
9089         // set auto-check timer
9090         SUGAR.email2.folders.startCheckTimer();
9091         // check if we're coming from an email-link click
9092         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9093         
9094         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9095         
9096         //Init fix for YUI 2.7.0 datatable sort.
9097         SUGAR.email2.addressBook.initFixForDatatableSort();
9098 }
9099
9100 function createTreePanel(treeData, params) {
9101         var tree = new YAHOO.widget.TreeView(params.id);
9102         var root = tree.getRoot();
9103         
9104         //if (treeData.nodes && treeData[0].id == "Home")
9105         //      treeData = treeData[0];
9106         return tree;
9107 }
9108
9109 function addChildNodes(parentNode, parentData) {
9110         var Ck = YAHOO.util.Cookie;
9111         var nextyear = SUGAR.email2.nextYear;
9112         var nodes = parentData.nodes || parentData.children;
9113         for (i in nodes) {
9114                 if (typeof(nodes[i]) == 'object') {
9115                         if (nodes[i].data) {
9116                 // See comment about href below.
9117                                 // nodes[i].data.href = '#';
9118                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode);
9119                                 node.action = nodes[i].data.action;
9120                         } else {
9121                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9122                                         addChildNodes(parentNode, nodes[i]);
9123                                         return;
9124                                 }
9125                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9126                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9127                                 if (nodes[i].cls) {
9128                                         nodes[i].className = nodes[i].cls;
9129                                 }
9130                 // Previously, span was added in the label so it was rendering in the tree.
9131                 // Default behavior is to wrap in span if no href property, and since this href
9132                 // doesn't do anything, remove it so that it will be wrapped in spans.
9133                 // nodes[i].href = "#";
9134                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9135                                 //Override YUI child node creation
9136                                 if (nodes[i].children) {
9137                                         nodes[i].nodes = nodes[i].children;
9138                                         nodes[i].children = [ ];
9139                                 }
9140                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9141                         }
9142                         
9143                         if (typeof(nodes[i].nodes) == 'object') {
9144                                 addChildNodes(node, nodes[i]);
9145                         }
9146                 }
9147         }
9148 }
9149
9150 /**
9151  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9152  */
9153 function email2treeinit(tree, treedata, treediv, params) {
9154         //ensure the tree data is not corrupt
9155         if (!treedata) {
9156            return;
9157         }
9158         if (SUGAR.email2.tree) {
9159                 SUGAR.email2.tree.destroy();
9160                 SUGAR.email2.tree = null;
9161         }
9162         
9163         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9164                 id: 'emailtree'
9165         });
9166         
9167         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9168         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9169         tree.subscribe("expandComplete", function(node){
9170                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9171                 for (var i in node.children) {
9172                         SE.accounts.setupDDTarget(node.children[i]);
9173                 }
9174         });
9175         tree.setCollapseAnim("TVSlideOut");
9176         tree.setExpandAnim("TVSlideIn");
9177         var root = tree.root;
9178         while (root.hasChildren()) {
9179                 var node = root.children[0];
9180                 node.destroy();
9181                 tree.removeNode(root.children[0], false);
9182         }
9183         addChildNodes(root, treedata);
9184         tree.render();
9185         SUGAR.email2.accounts.renderTree();
9186 }
9187
9188 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9189         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9190 };
9191
9192
9193 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9194     startDrag: function(x, y) {
9195                 var Dom = YAHOO.util.Dom;       
9196                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9197                 
9198                 this.dragId = "";
9199                 var dragEl = this.getDragEl();  
9200         var clickEl = this.getEl(); 
9201         Dom.setStyle(clickEl, "color", "#AAA");
9202         Dom.setStyle(clickEl, "opacity", "0.25"); 
9203         dragEl.innerHTML = clickEl.innerHTML; 
9204          
9205         Dom.addClass(dragEl, "ygtvcell");
9206         Dom.addClass(dragEl, "ygtvcontent");
9207         Dom.addClass(dragEl, "folderDragProxy");
9208         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9209         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9210         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9211         Dom.setStyle(dragEl, "opacity", "0.5"); 
9212             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9213     },
9214     
9215     onDragOver: function(ev, id) {
9216         var Dom = YAHOO.util.Dom;
9217         if (id != this.dragId)
9218         {
9219                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9220                 if(node.data.cls != "sugarFolder") {
9221                         SUGAR.email2.folders.unhighliteAll();
9222                         return;
9223                 }
9224                 this.dragId = id;
9225                 this.targetNode = node;
9226                 SUGAR.email2.folders.unhighliteAll();
9227                 node.highlight();
9228         }
9229     },
9230     
9231     onDragOut: function(e, id) {
9232         if (this.targetNode) {
9233                 SUGAR.email2.folders.unhighliteAll();
9234                 this.targetNode = false;
9235                 this.dragId = false;
9236         }
9237     },
9238     
9239     endDrag: function() { 
9240         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9241         if (this.targetNode) {
9242                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9243         }
9244     }
9245 });// End of File modules/Emails/javascript/init.js
9246                                 
9247 /*********************************************************************************
9248  * SugarCRM Community Edition is a customer relationship management program developed by
9249  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9250  * 
9251  * This program is free software; you can redistribute it and/or modify it under
9252  * the terms of the GNU Affero General Public License version 3 as published by the
9253  * Free Software Foundation with the addition of the following permission added
9254  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9255  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9256  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9257  * 
9258  * This program is distributed in the hope that it will be useful, but WITHOUT
9259  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9260  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9261  * details.
9262  * 
9263  * You should have received a copy of the GNU Affero General Public License along with
9264  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9265  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9266  * 02110-1301 USA.
9267  * 
9268  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9269  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9270  * 
9271  * The interactive user interfaces in modified source and object code versions
9272  * of this program must display Appropriate Legal Notices, as required under
9273  * Section 5 of the GNU Affero General Public License version 3.
9274  * 
9275  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9276  * these Appropriate Legal Notices must retain the display of the "Powered by
9277  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9278  * technical reasons, the Appropriate Legal Notices must display the words
9279  * "Powered by SugarCRM".
9280  ********************************************************************************/
9281
9282 /**
9283   Complex layout init
9284  */
9285 function complexLayoutInit() {
9286         var se = SUGAR.email2;
9287         var Dom = YAHOO.util.Dom;
9288         se.e2Layout = {
9289         getInnerLayout : function(rows) {
9290                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
9291                 parent: se.complexLayout,  
9292                         border:true,
9293                     hideOnLayout: true,
9294                     height: 400,
9295                                 units: [{
9296                                         position: "center",
9297                                     scroll:false, // grid should autoScroll itself
9298                                     split:true,
9299                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
9300                                 },{
9301                                         position: "bottom",
9302                                     scroll:true,
9303                                     collapse: false,
9304                                     resize: true,
9305                                     useShim:true,
9306                                     height:'250',
9307                                     body: "<div id='listBottom' />"
9308                                 },{
9309                                     position: "right",
9310                                     scroll:true,
9311                                     collapse: false,
9312                                     resize: true,
9313                                     useShim:true,
9314                                     width:'250',
9315                                     body: "<div id='listRight' />",
9316                                     titlebar: false //,header: "right"
9317                                 }]
9318             });
9319                 se.complexLayout.on("render", function(){
9320                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
9321                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9322                                 SUGAR.email2.listViewLayout.set("height", height);
9323                                 SUGAR.email2.listViewLayout.render();
9324                 });
9325             se.listViewLayout.render();
9326             //CSS hack for now
9327             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
9328             var rp = se.listViewLayout.resizePreview = function() {
9329                 var pre = Dom.get("displayEmailFramePreview");
9330                 if (pre) {
9331                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
9332                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
9333                 }
9334             };
9335             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
9336             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
9337             se.e2Layout.setPreviewPanel(rows);
9338             se.previewLayout = se.listViewLayout;
9339             return se.listViewLayout;
9340         },
9341         
9342         getInnerLayout2Rows : function() {
9343             return this.getInnerLayout(true);
9344         },
9345         getInnerLayout2Columns : function() {
9346             return this.getInnerLayout(false);
9347         },
9348         
9349         init : function(){
9350             // initialize state manager, we will use cookies
9351 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
9352                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
9353                 se.complexLayout = new YAHOO.widget.Layout("container", {
9354                         border:true,
9355                 hideOnLayout: true,
9356                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
9357                 width: Dom.getViewportWidth() - 40,
9358                 units: [{
9359                         position: "center",
9360                     scroll:false,
9361                     body: "<div id='emailtabs'></div>"
9362                 },
9363                 {
9364                         position: "left",
9365                         scroll: true,
9366                         body: "<div id='lefttabs'></div>",
9367                     collapse: true,
9368                     width: 210,
9369                     minWidth: 100,
9370                     resize:true,
9371                     useShim:true,
9372                     titlebar: true,
9373                     header: "&nbsp;"
9374                 },
9375                 {
9376                     header: Dom.get('footerLinks').innerHTML,
9377                                         position: 'bottom',
9378                                         id: 'mbfooter',
9379                                         height: 22,
9380                                         border: false
9381                 }]
9382             });
9383                 se.complexLayout.render();
9384                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
9385                         tp.addTab(new YAHOO.widget.Tab({ 
9386                                 label: "Inbox",
9387                                 scroll : true,
9388                                 content : "<div id='listViewDiv'/>",
9389                                 id : "center",
9390                                 active : true
9391                         }));
9392                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
9393                         tp.appendTo(centerEl);
9394                         //CSS hack for now
9395                         tp.get("element").style.borderRight = "1px solid #666"
9396                         
9397                         var listV =  this.getInnerLayout2Rows();
9398                         listV.set("height", tp.get("element").clientHeight - 25);
9399                         listV.render();
9400             
9401             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
9402             var folderTab = new YAHOO.widget.Tab({ 
9403                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
9404                                 scroll : true,
9405                                 content : "<div id='emailtree'/>",
9406                                 id : "tree",
9407                                 active : true
9408                         });
9409             folderTab.on("activeChange", function(o){ 
9410                 if (o.newValue) {
9411                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
9412                 }
9413             });
9414             se.leftTabs.addTab(folderTab);
9415             
9416             var tabContent = SUGAR.util.getAndRemove("searchTab");
9417             var searchTab = new YAHOO.widget.Tab({ 
9418                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
9419                                 scroll : true,
9420                                 content : tabContent.innerHTML,
9421                                 id : tabContent.id
9422                         });
9423             searchTab.on("activeChange", function(o){ 
9424                 if (o.newValue) 
9425                 {
9426                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
9427                    //Setup the calendars if needed
9428                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "searchDateFrom_trigger", singleClick : true, step : 1, weekNumbers:false});
9429                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "searchDateTo_trigger", singleClick : true, step : 1, weekNumbers:false});
9430                    
9431                        //Initalize sqs object for assigned user name 
9432                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
9433                        
9434                        //Attach event handler for when the relate module option is selected for the correct sqs object
9435                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
9436                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
9437                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
9438                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
9439                        
9440                        //If enter key is pressed, perform search
9441                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
9442                        for(var i=0; i < addKeyPressFields.length;i++)
9443                        {
9444                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
9445                                 if (e.keyCode == 13) {
9446                                         YAHOO.util.Event.stopEvent(e);
9447                                         SUGAR.email2.search.searchAdvanced();
9448                                 }
9449                        });
9450                        }
9451                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
9452                        enableQS(true);
9453                        //Clear parent values if selecting another parent type.
9454                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
9455                            function(){ 
9456                                document.getElementById('data_parent_id_search').value =''; 
9457                                document.getElementById('data_parent_name_search').value =''; 
9458                            });
9459                 
9460                 }
9461             });
9462             se.leftTabs.addTab(searchTab);
9463             
9464             var resizeTabBody = function() {
9465                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
9466                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
9467             }
9468             resizeTabBody();
9469             se.complexLayout.on("render", resizeTabBody);
9470             se.leftTabs.on("activeTabChange", resizeTabBody);
9471                         //hack to allow left pane scroll bar to fully show
9472                 var lefttabsDiv = document.getElementById('lefttabs');
9473                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
9474                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
9475                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
9476           
9477         },
9478         initSQSObject: function(formName,fieldName)
9479         {
9480             var fullFieldName = formName + '_' + fieldName; //SQS Convention
9481             var resultName = fullFieldName + '_' + 'results';
9482             
9483             if (QSFieldsArray[fullFieldName] != null) 
9484             {
9485                 QSFieldsArray[fullFieldName].destroy();
9486                 delete QSFieldsArray[fullFieldName];
9487             }
9488             if (QSProcessedFieldsArray[fullFieldName])
9489             QSProcessedFieldsArray[fullFieldName] = false;
9490
9491             if( Dom.get(resultName) )
9492             {
9493                 var obj = document.getElementById(resultName);
9494                 obj.parentNode.removeChild(obj);
9495             }
9496         },
9497         setPreviewPanel: function(rows) {
9498                 if (rows) {
9499                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
9500                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
9501                 Dom.get("listRight").innerHTML = "";
9502                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
9503             } else {
9504                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
9505                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
9506                 Dom.get("listBottom").innerHTML = "";
9507                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
9508             }
9509         }
9510     };
9511         se.e2Layout.init();
9512 }
9513
9514 var myBufferedListenerObject = new Object();
9515 myBufferedListenerObject.refit = function() {
9516     if(SUGAR.email2.grid) {
9517         SUGAR.email2.grid.autoSize();
9518     }
9519 }
9520 // End of File modules/Emails/javascript/complexLayout.js
9521                                 
9522 /*********************************************************************************
9523  * SugarCRM Community Edition is a customer relationship management program developed by
9524  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9525  * 
9526  * This program is free software; you can redistribute it and/or modify it under
9527  * the terms of the GNU Affero General Public License version 3 as published by the
9528  * Free Software Foundation with the addition of the following permission added
9529  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9530  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9531  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9532  * 
9533  * This program is distributed in the hope that it will be useful, but WITHOUT
9534  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9535  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9536  * details.
9537  * 
9538  * You should have received a copy of the GNU Affero General Public License along with
9539  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9540  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9541  * 02110-1301 USA.
9542  * 
9543  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9544  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9545  * 
9546  * The interactive user interfaces in modified source and object code versions
9547  * of this program must display Appropriate Legal Notices, as required under
9548  * Section 5 of the GNU Affero General Public License version 3.
9549  * 
9550  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9551  * these Appropriate Legal Notices must retain the display of the "Powered by
9552  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9553  * technical reasons, the Appropriate Legal Notices must display the words
9554  * "Powered by SugarCRM".
9555  ********************************************************************************/
9556
9557 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9558 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9559 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9560 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9561 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9562 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9563 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9564 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9565 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9566 '               <input type="hidden" id="composeType" name="composeType">' +
9567 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9568 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9569 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9570 '               <input type="hidden" id="sendTo" name="sendTo">' +
9571 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9572 '               <input type="hidden" id="sendCc" name="sendCc">' +
9573 '               <input type="hidden" id="setEditor" name="setEditor">' +
9574 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9575 '               <input type="hidden" id="parent_id" name="parent_id">' +
9576 '               <input type="hidden" id="parent_type" name="parent_type">' +
9577 '               <input type="hidden" id="attachments" name="attachments">' +
9578 '               <input type="hidden" id="documents" name="documents">' +
9579 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9580 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9581 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9582 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9583 '                       <tr>' +
9584 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9585 '                                       <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>' +
9586 '                                       <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>' +
9587 '                                       <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>' +
9588 '                                       <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>' +
9589 '</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>' + 
9590 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9591 '<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>' +
9592 '                       </td></tr></tbody></table></th>'     +
9593 '                       </tr>' +
9594 '                       <tr>' +
9595 '                               <td>' +
9596 '                                       <div style="margin:5px;">' +
9597 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9598 '                                               <tr>' +
9599 '                                                       <td class="emailUILabel" NOWRAP >' +
9600 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9601 '                                                       </td>' +
9602 '                                                       <td class="emailUIField" NOWRAP>' +
9603 '                                                               <div>' +
9604 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9605 '                                                               </div>' +
9606 '                                                       </td>' +
9607 '                                               </tr>' +
9608 '                                               <tr>' +
9609 '                                                       <td class="emailUILabel" NOWRAP>' +
9610 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9611 '                                   {app_strings.LBL_EMAIL_TO}:' +
9612 '                               </button>' + 
9613 '                                                       </td>' +
9614 '                                                       <td class="emailUIField" NOWRAP>' +
9615 '                                                               <div class="ac_autocomplete">' +
9616 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9617 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9618 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9619 '                                                               </div>' +
9620 '                                                       </td>' +
9621 '                                               </tr>' +
9622 '                                               <tr id="add_addr_options_tr{idx}">' +
9623 '                                                       <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>'+
9624 '                                               </tr>'+
9625 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9626 '                                                       <td class="emailUILabel" NOWRAP>' +
9627 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9628 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9629 '                               </button>' + 
9630 '                                                       </td>' +
9631 '                                                       <td class="emailUIField" NOWRAP>' +
9632 '                                                               <div class="ac_autocomplete">' +
9633 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9634 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9635 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9636 '                                                               </div>' +
9637 '                                                       </td>' +
9638 '                                               </tr>' +
9639 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9640 '                                                       <td class="emailUILabel" NOWRAP>' +
9641 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9642 '                               {app_strings.LBL_EMAIL_BCC}:' +
9643 '                               </button>' + 
9644 '                                                       </td>' +
9645 '                                                       <td class="emailUIField" NOWRAP>' +
9646 '                                                               <div class="ac_autocomplete">' +
9647 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9648 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9649 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9650 '                                                               </div>' +
9651 '                                                       </td>' +
9652 '                                               </tr>' +
9653 '                                               <tr>' +
9654 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9655 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9656 '                                                       </td>' +
9657 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9658 '                                                               <div class="ac_autocomplete">' +
9659 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9660 '                                                               </div>' +
9661 '                                                       </td>' +
9662 '                                               </tr>' +
9663 '                                       </table>' +
9664 '                                       </div>' +
9665 '                               </td>'   +
9666 '                       </tr>' +
9667 '               </table>' +
9668 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9669 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9670 '                       <div style="padding:5px;">' +
9671 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9672 '                                       <tr>' +
9673 '                                               <th>' +
9674 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9675 '                                                       <br />' +
9676 '                                                       &nbsp;' +
9677 '                                               </th>' +
9678 '                                       </tr>' +
9679 '                                       <tr>' +
9680 '                                               <td>' +
9681 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9682 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9683 '                                               </td>' +
9684 '                                       </tr>' +
9685 '                                       <tr>' +
9686 '                                               <td>' +
9687 '                                                       &nbsp;' +
9688 '                                                       <br />' +
9689 '                                                       &nbsp;' +
9690 '                                               </td>' +
9691 '                                       </tr>' +
9692 '                                       <tr>' +
9693 '                                               <th>' +
9694 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9695 '                                                       <br />' +
9696 '                                                       &nbsp;' +
9697 '                                               </th>' +
9698 '                                       </tr>' +
9699 '                                       <tr>' +
9700 '                                               <td>' +
9701 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9702 '                                                       <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>' +
9703 '                                               </td>' +
9704 '                                       </tr>' +
9705 '                                       <tr>' +
9706 '                                               <td>' +
9707 '                                                       &nbsp;' +
9708 '                                                       <br />' +
9709 '                                                       &nbsp;' +
9710 '                                               </td>' +
9711 '                                       </tr>' +
9712 '                                       <tr>' +
9713 '                                               <th>' +
9714 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9715 '                                                       <br />' +
9716 '                                                       &nbsp;' +
9717 '                                               </th>' +
9718 '                                       </tr>' +
9719 '                                       <tr>' +
9720 '                                               <td>' +
9721 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9722 '                                               </td>' +
9723 '                                       </tr>' +
9724 '                               </table>' +
9725 '                       </div>' +
9726 '               </div>' +
9727 '       </form>' +
9728 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9729 '             <div style="padding:5px;">' +
9730 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9731 '                               <table border="0" width="100%">' +
9732 '                                       <tr>' +
9733 '                                               <td NOWRAP style="padding:2px;">' +
9734 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9735 '                                               </td>' +
9736 '                                       </tr>' +
9737 '                                       <tr>' +
9738 '                                               <td NOWRAP style="padding:2px;">' +
9739 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9740 '                                               </td>' +
9741 '                                       </tr>' +
9742 '                               </table>' +
9743 '                               <br />' +
9744 '                               <table border="0" width="100%">' +
9745 '                                       <tr>' +
9746 '                                               <td NOWRAP style="padding:2px;">' +
9747 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9748 '                                               </td>' +
9749 '                                       </tr>' +
9750 '                                       <tr>' +
9751 '                                               <td NOWRAP style="padding:2px;">' +
9752 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9753 '                                               </td>' +
9754 '                                       </tr>' +
9755 '                               </table>' +
9756 '                               <table border="0" width="100%">' +
9757 '                                       <tr>' +
9758 '                                               <td NOWRAP style="padding:2px;">' +
9759 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9760 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9761 '                                               </td>' +
9762 '                                       </tr>' +
9763 '                               </table>' +
9764 '         </form>' +
9765 '                       </div> ' +
9766 '               </div>' +
9767 '</div>';
9768 // End of File modules/Emails/javascript/composeEmailTemplate.js
9769                                 
9770 /*********************************************************************************
9771  * SugarCRM Community Edition is a customer relationship management program developed by
9772  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9773  * 
9774  * This program is free software; you can redistribute it and/or modify it under
9775  * the terms of the GNU Affero General Public License version 3 as published by the
9776  * Free Software Foundation with the addition of the following permission added
9777  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9778  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9779  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9780  * 
9781  * This program is distributed in the hope that it will be useful, but WITHOUT
9782  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9783  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9784  * details.
9785  * 
9786  * You should have received a copy of the GNU Affero General Public License along with
9787  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9788  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9789  * 02110-1301 USA.
9790  * 
9791  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9792  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9793  * 
9794  * The interactive user interfaces in modified source and object code versions
9795  * of this program must display Appropriate Legal Notices, as required under
9796  * Section 5 of the GNU Affero General Public License version 3.
9797  * 
9798  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9799  * these Appropriate Legal Notices must retain the display of the "Powered by
9800  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9801  * technical reasons, the Appropriate Legal Notices must display the words
9802  * "Powered by SugarCRM".
9803  ********************************************************************************/
9804
9805 SUGAR.email2.templates['displayOneEmail'] = 
9806 '<div class="emailDetailTable" style="height:100%">' +
9807 '<div id="viewMenuDiv{idx}"></div>' + 
9808 '<div width="100%" class="displayEmailValue">' +
9809 '                                       <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>' +
9810 '                                       <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>' +
9811 '                                       <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>' +
9812 '                                       <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>' +
9813 '                                       <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>' +
9814 '                                       <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>' +
9815 '                                       <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>' +
9816 '                                       <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>' +
9817 '                                       <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>' +
9818 '</div>' +
9819 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9820 '                               <tr>' +
9821 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9822 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9823 '                                       </td>' +
9824 '                                       <td width="99%" class="displayEmailValue">' +
9825 '                                               {email.from_addr}' +
9826 '                                       </td>' +
9827 '                               </tr>' +
9828 '                               <tr>' +
9829 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9830 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9831 '                                       </td>' +
9832 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9833 '                                               <b>{email.name}</b>' +
9834 '                                       </td>' +
9835 '                               </tr>' +
9836 '                               <tr>' +
9837 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9838 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9839 '                                       </td>' +
9840 '                                       <td class="displayEmailValue">' +
9841 '                                               {email.date_start} {email.time_start}' +
9842 '                                       </td>' +
9843 '                               </tr>' +
9844 '                               <tr>' +
9845 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9846 '                                               {app_strings.LBL_EMAIL_TO}:' +
9847 '                                       </td>' +
9848 '                                       <td class="displayEmailValue">' +
9849 '                                               {email.toaddrs}' +
9850 '                                       </td>' +
9851 '                               </tr>' +
9852 '                               <tr>{meta.cc}</tr>' +
9853 '                               <tr>{email.attachments}</tr>' +
9854 '                       </table>' +
9855 '                       <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>' +
9856 //'                           {email.description}' +
9857 '</div>'
9858 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9859                                 
9860 /*********************************************************************************
9861  * SugarCRM Community Edition is a customer relationship management program developed by
9862  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9863  * 
9864  * This program is free software; you can redistribute it and/or modify it under
9865  * the terms of the GNU Affero General Public License version 3 as published by the
9866  * Free Software Foundation with the addition of the following permission added
9867  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9868  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9869  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9870  * 
9871  * This program is distributed in the hope that it will be useful, but WITHOUT
9872  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9873  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9874  * details.
9875  * 
9876  * You should have received a copy of the GNU Affero General Public License along with
9877  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9878  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9879  * 02110-1301 USA.
9880  * 
9881  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9882  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9883  * 
9884  * The interactive user interfaces in modified source and object code versions
9885  * of this program must display Appropriate Legal Notices, as required under
9886  * Section 5 of the GNU Affero General Public License version 3.
9887  * 
9888  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9889  * these Appropriate Legal Notices must retain the display of the "Powered by
9890  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9891  * technical reasons, the Appropriate Legal Notices must display the words
9892  * "Powered by SugarCRM".
9893  ********************************************************************************/
9894
9895 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9896 '<body onload="javascript:window.print();">' + 
9897 '<style>' + 
9898 'body {' + 
9899 '       margin: 0px;' + 
9900 '       font-family: helvetica, impact, sans-serif;' +
9901 '       font-size : 12pt;' +
9902 '} ' +
9903 'table {' +
9904 '       padding:10px;' +
9905 '}' +
9906 '</style>' +
9907 '<div>' +
9908 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9909 '       <tr>' +
9910 '               <td>' +
9911 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9912 '                               <tr>' +
9913 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9914 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9915 '                                       </td>' +
9916 '                                       <td width="99%" class="displayEmailValue">' +
9917 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9918 '                                       </td>' +
9919 '                               </tr>' +
9920 '                               <tr>' +
9921 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9922 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9923 '                                       </td>' +
9924 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9925 '                                               <b>{email.name}</b>' +
9926 '                                       </td>' +
9927 '                               </tr>' +
9928 '                               <tr>' +
9929 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9930 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9931 '                                       </td>' +
9932 '                                       <td class="displayEmailValue">' +
9933 '                                               {email.date_start} {email.time_start}' +
9934 '                                       </td>' +
9935 '                               </tr>' +
9936 '                               <tr>' +
9937 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9938 '                                               {app_strings.LBL_EMAIL_TO}:' +
9939 '                                       </td>' +
9940 '                                       <td class="displayEmailValue">' +
9941 '                                               {email.toaddrs}' +
9942 '                                       </td>' +
9943 '                               </tr>' +
9944 '                               {email.cc}' +
9945 '                               {email.attachments}' +
9946 '                       </table>' +
9947 '               </td>' +
9948 '       </tr>' +
9949 '       <tr>' +
9950 '               <td>' +
9951 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9952 '                               <tr>' +
9953 '                                       <td style="border-top: 1px solid #333;">' +
9954 '                                               <div style="padding:5px;">' +
9955                                                         '{email.description}' +
9956 '                                               </div>' +
9957 '                                       </td>' +
9958 '                               </tr>' +
9959 '                       </table>' +
9960 '               </td>' +
9961 '       </tr>' +
9962 '</table>' +
9963 '</div>' +
9964 '</body></html>';
9965 // End of File modules/Emails/javascript/viewPrintable.js
9966                                 
9967 /*********************************************************************************
9968  * SugarCRM Community Edition is a customer relationship management program developed by
9969  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9970  *
9971  * This program is free software; you can redistribute it and/or modify it under
9972  * the terms of the GNU Affero General Public License version 3 as published by the
9973  * Free Software Foundation with the addition of the following permission added
9974  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9975  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9976  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9977  *
9978  * This program is distributed in the hope that it will be useful, but WITHOUT
9979  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9980  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9981  * details.
9982  *
9983  * You should have received a copy of the GNU Affero General Public License along with
9984  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9985  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9986  * 02110-1301 USA.
9987  *
9988  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9989  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9990  *
9991  * The interactive user interfaces in modified source and object code versions
9992  * of this program must display Appropriate Legal Notices, as required under
9993  * Section 5 of the GNU Affero General Public License version 3.
9994  *
9995  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9996  * these Appropriate Legal Notices must retain the display of the "Powered by
9997  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9998  * technical reasons, the Appropriate Legal Notices must display the words
9999  * "Powered by SugarCRM".
10000  ********************************************************************************/
10001 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
10002 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;}
10003 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');}
10004 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;}}
10005 if(QSProcessedFieldsArray[qs_index_id]){continue;}
10006 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
10007 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}
10008 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="";}}
10009 this.oldValue="";}});if(/^(billing_|shipping_)?account_name$/.exec(qsFields[qsField].name))
10010 {search.clearFields=function(){};search.setFields=function(data,filter)
10011 {var label_str='';var label_data_str='';var current_label_data_str='';var label_data_hash=new Array();for(var i in this.fields){for(var key in this.qs_obj.field_list){if(this.fields[i]==this.qs_obj.field_list[key]&&document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&document.getElementById(this.qs_obj.populate_list[key]+'_label')&&this.qs_obj.populate_list[key].match(filter)){var displayValue=data[i].replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');var data_label=document.getElementById(this.qs_obj.populate_list[key]+'_label').innerHTML.replace(/\n/gi,'');label_and_data=data_label+' '+displayValue;if(document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]]&&!label_data_hash[data_label])
10012 {label_str+=data_label+' \n';label_data_str+=label_and_data+'\n';label_data_hash[data_label]=true;current_label_data_str+=data_label+' '+document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value+'\n';}}}}
10013 if(label_str!=current_label_data_str&&current_label_data_str!=label_data_str){module_key=(typeof document.forms[form_id].elements['module']!='undefined')?document.forms[form_id].elements['module'].value:'app_strings';warning_label=SUGAR.language.translate(module_key,'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM')+'\n\n'+label_data_str;if(!confirm(warning_label))
10014 {this.updateFields(data,/account_id/);}else{if(Dom.get('shipping_checkbox'))
10015 {if(this.inputElement.id=='shipping_account_name')
10016 {filter=Dom.get('shipping_checkbox').checked?/(account_id|office_phone)/:filter;}else if(this.inputElement.id=='billing_account_name'){filter=Dom.get('shipping_checkbox').checked?filter:/(account_id|office_phone|billing)/;}}else if(Dom.get('alt_checkbox')){filter=Dom.get('alt_checkbox').checked?filter:/^(?!alt)/;}
10017 this.updateFields(data,filter);}}else{this.updateFields(data,filter);}};}
10018 if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
10019 search.itemSelectEvent.subscribe(function(e,args){var data=args[2];var fields=this.fields;this.setFields(data,/\S/);if(typeof(this.qs_obj['post_onblur_function'])!='undefined'){collection_extended=new Array();for(var i in fields){for(var key in this.qs_obj.field_list){if(fields[i]==this.qs_obj.field_list[key]){collection_extended[this.qs_obj.field_list[key]]=data[i];}}}
10020 eval(this.qs_obj['post_onblur_function']+'(collection_extended, this.qs_obj.id)');}});search.textboxFocusEvent.subscribe(function(){this.oldValue=this.getInputEl().value;});search.selectionEnforceEvent.subscribe(function(e,args){if(this.oldValue!=args[1]){this.clearFields();}else{this.getInputEl().value=this.oldValue;}});search.dataReturnEvent.subscribe(function(e,args){if(this.getInputEl().value.length==0&&args[2].length>0){var data=[];for(var key in this.qs_obj.field_list){data[data.length]=args[2][0][this.qs_obj.field_list[key]];}
10021 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});search.typeAheadEvent.subscribe(function(e,args){this.getInputEl().value=this.getInputEl().value.replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
10022 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
10023 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}
10024 // End of File include/javascript/quicksearch.js
10025