]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/sugar_grp_emails.js
Release 6.1.6
[Github/sugarcrm.git] / include / javascript / sugar_grp_emails.js
1
2 /* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
3
4 /**
5  * @class a YAHOO.util.DDProxy implementation. During the drag over event, the
6  * dragged element is inserted before the dragged-over element.
7  *
8  * @extends YAHOO.util.DDProxy
9  * @constructor
10  * @param {String} id the id of the linked element
11  * @param {String} sGroup the group of related DragDrop objects
12  */
13 function ygDDList(id, sGroup) {
14
15         if (id) {
16                 this.init(id, sGroup);
17                 this.initFrame();
18                 //this.logger = new ygLogger("ygDDList");
19         }
20
21         var s = this.getDragEl().style;
22         s.borderColor = "transparent";
23         s.backgroundColor = "#f6f5e5";
24         s.opacity = 0.76;
25         s.filter = "alpha(opacity=76)";
26 }
27
28 ygDDList.prototype = new YAHOO.util.DDProxy();
29
30 ygDDList.prototype.borderDiv = null;
31 ygDDList.prototype.originalDisplayProperties = Array();
32
33 ygDDList.prototype.startDrag = function(x, y) {
34         //this.logger.debug(this.id + " startDrag");
35
36         var dragEl = this.getDragEl();
37         var clickEl = this.getEl();
38
39         dragEl.innerHTML = clickEl.innerHTML;
40         dragElObjects = dragEl.getElementsByTagName('object');
41
42         
43         dragEl.className = clickEl.className;
44         dragEl.style.color = clickEl.style.color;
45         dragEl.style.border = "1px solid #aaa";
46
47         // save the style of the object 
48         clickElRegion = YAHOO.util.Dom.getRegion(clickEl);
49         
50         this.borderDiv = document.createElement('div'); // create a div to display border
51         this.borderDiv.style.height = (clickElRegion.bottom - clickElRegion.top) + 'px';
52         this.borderDiv.style.border = '2px dashed #cccccc';
53         
54         for(i in clickEl.childNodes) { // hide contents of the target elements contents
55                 if(typeof clickEl.childNodes[i].style != 'undefined') {
56                         this.originalDisplayProperties[i] = clickEl.childNodes[i].style.display;
57                         clickEl.childNodes[i].style.display = 'none';
58                 }
59
60         }
61         clickEl.appendChild(this.borderDiv);
62 };
63
64 ygDDList.prototype.endDrag = function(e) {
65         // disable moving the linked element
66         var clickEl = this.getEl();
67
68         clickEl.removeChild(this.borderDiv); // remove border div
69         
70         for(i in clickEl.childNodes) { // show target elements contents
71                 if(typeof clickEl.childNodes[i].style != 'undefined') {
72                         clickEl.childNodes[i].style.display = this.originalDisplayProperties[i];
73                 }
74         }
75         
76         if(this.clickHeight) 
77             clickEl.style.height = this.clickHeight;
78         else 
79                 clickEl.style.height = '';
80         
81         if(this.clickBorder) 
82             clickEl.style.border = this.clickBorder;
83         else 
84                 clickEl.style.border = '';
85                 
86         dragEl = this.getDragEl();
87         dragEl.innerHTML = '';
88
89         this.afterEndDrag(e);
90 };
91
92 ygDDList.prototype.afterEndDrag = function(e) {
93
94 }
95
96 ygDDList.prototype.onDrag = function(e, id) {
97     
98 };
99
100 ygDDList.prototype.onDragOver = function(e, id) {
101         // this.logger.debug(this.id.toString() + " onDragOver " + id);
102         var el;
103         
104     if ("string" == typeof id) {
105         el = YAHOO.util.DDM.getElement(id);
106     } else { 
107         el = YAHOO.util.DDM.getBestMatch(id).getEl();
108     }
109     
110         dragEl = this.getDragEl();
111         elRegion = YAHOO.util.Dom.getRegion(el);
112             
113 //    this.logger.debug('id: ' + el.id);
114 //    this.logger.debug('size: ' + (elRegion.bottom - elRegion.top));
115 //    this.logger.debug('getPosY: ' + YAHOO.util.DDM.getPosY(el));
116         var mid = YAHOO.util.DDM.getPosY(el) + (Math.floor((elRegion.bottom - elRegion.top) / 2));
117 //    this.logger.debug('mid: ' + mid);
118         
119 //    this.logger.debug(YAHOO.util.DDM.getPosY(dragEl) + " <  " + mid);
120 //    this.logger.debug("Y: " + YAHOO.util.Event.getPageY(e));
121         
122         if (YAHOO.util.DDM.getPosY(dragEl) < mid ) { // insert on top triggering item
123                 var el2 = this.getEl();
124                 var p = el.parentNode;
125                 p.insertBefore(el2, el);
126         }
127         if (YAHOO.util.DDM.getPosY(dragEl) >= mid ) { // insert below triggered item
128                 var el2 = this.getEl();
129                 var p = el.parentNode;
130                 p.insertBefore(el2, el.nextSibling);
131         }
132 };
133
134 ygDDList.prototype.onDragEnter = function(e, id) {
135         // this.logger.debug(this.id.toString() + " onDragEnter " + id);
136         // this.getDragEl().style.border = "1px solid #449629";
137 };
138
139 ygDDList.prototype.onDragOut = function(e, id) {
140     // I need to know when we are over nothing
141         // this.getDragEl().style.border = "1px solid #964428";
142 }
143
144 /////////////////////////////////////////////////////////////////////////////
145
146 function ygDDListBoundary(id, sGroup) {
147         if (id) {
148                 this.init(id, sGroup);
149                 //this.logger = new ygLogger("ygDDListBoundary");
150                 this.isBoundary = true;
151         }
152 }
153
154 ygDDListBoundary.prototype = new YAHOO.util.DDTarget();
155 // End of File include/javascript/yui/ygDDList.js
156                                 
157 /*********************************************************************************
158  * SugarCRM is a customer relationship management program developed by
159  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
160  *
161  * This program is free software; you can redistribute it and/or modify it under
162  * the terms of the GNU Affero General Public License version 3 as published by the
163  * Free Software Foundation with the addition of the following permission added
164  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
165  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
166  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
167  *
168  * This program is distributed in the hope that it will be useful, but WITHOUT
169  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
170  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
171  * details.
172  *
173  * You should have received a copy of the GNU Affero General Public License along with
174  * this program; if not, see http://www.gnu.org/licenses or write to the Free
175  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
176  * 02110-1301 USA.
177  *
178  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
179  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
180  *
181  * The interactive user interfaces in modified source and object code versions
182  * of this program must display Appropriate Legal Notices, as required under
183  * Section 5 of the GNU Affero General Public License version 3.
184  *
185  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
186  * these Appropriate Legal Notices must retain the display of the "Powered by
187  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
188  * technical reasons, the Appropriate Legal Notices must display the words
189  * "Powered by SugarCRM".
190  ********************************************************************************/
191 (function(){if(SUGAR.EmailAddressWidget)return;var Dom=YAHOO.util.Dom;SUGAR.EmailAddressWidget=function(module){if(!SUGAR.EmailAddressWidget.count[module])SUGAR.EmailAddressWidget.count[module]=0;this.count=SUGAR.EmailAddressWidget.count[module];SUGAR.EmailAddressWidget.count[module]++;this.module=module;this.id=this.module+this.count;if(document.getElementById(module+'_email_widget_id'))
192 document.getElementById(module+'_email_widget_id').value=this.id;SUGAR.EmailAddressWidget.instances[this.id]=this;}
193 SUGAR.EmailAddressWidget.instances={};SUGAR.EmailAddressWidget.count={};SUGAR.EmailAddressWidget.prototype={emailTemplate:'<tr id="emailAddressRow">'+'<td nowrap="NOWRAP"><input type="text" name="emailAddress{$index}" id="emailAddress0" size="30"/></td>'+'<td><span>&nbsp;</span><img id="removeButton0" name="0" src="index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName=delete_inline.gif"/></td>'+'<td align="center"><input type="radio" name="emailAddressPrimaryFlag" id="emailAddressPrimaryFlag0" value="emailAddress0" enabled="true" checked="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressOptOutFlag[]" id="emailAddressOptOutFlag0" value="emailAddress0" enabled="true"/></td>'+'<td align="center"><input type="checkbox" name="emailAddressInvalidFlag[]" id="emailAddressInvalidFlag0" value="emailAddress0" enabled="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedFlag0" id="emailAddressVerifiedFlag0" value="true"/></td>'+'<td><input type="hidden" name="emailAddressVerifiedValue0" id="emailAddressVerifiedValue0" value=""/></td></tr>',numberEmailAddresses:0,replyToFlagObject:new Object(),verifying:false,enterPressed:false,tabPressed:false,emailView:"",emailIsRequired:false,tabIndex:-1,prefillEmailAddresses:function(tableId,o){for(i=0;i<o.length;i++){o[i].email_address=o[i].email_address.replace('&#039;',"'");this.addEmailAddress(tableId,o[i].email_address,o[i].primary_address,o[i].reply_to_address,o[i].opt_out,o[i].invalid_email);}},retrieveEmailAddress:function(event){var callbackFunction=function success(data){var vals=YAHOO.lang.JSON.parse(data.responseText);var target=vals.target;event=this.getEvent(event);if(vals.email){var email=vals.email;if(email!=''&&/\d+$/.test(target)){var matches=target.match(/\d+$/);var targetNumber=matches[0];var optOutEl=Dom.get(this.id+'emailAddressOptOutFlag'+targetNumber);if(optOutEl){optOutEl.checked=email['opt_out']==1?true:false;}
194 var invalidEl=Dom.get(this.id+'emailAddressInvalidFlag'+targetNumber);if(invalidEl){invalidEl.checked=email['invalid_email']==1?true:false;}}}
195 var index=/[a-z]*\d?emailAddress(\d+)/i.exec(target)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
196 var verifiedTextNode=document.createElement('span');verifiedTextNode.innerHTML='';verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifyElementFlag.value="true";this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);this.verifyElementValue.value=Dom.get(this.id+'emailAddress'+index).value;this.verifying=false;var savePressed=false;if(event){var elm=document.activeElement||event.explicitOriginalTarget;if(typeof elm.type!='undefined'&&/submit|button/.test(elm.type.toLowerCase())){savePressed=true;}}
197 if(savePressed||this.enterPressed){setTimeout("SUGAR.EmailAddressWidget.instances."+this.id+".forceSubmit()",2100);}else if(this.tabPressed){Dom.get(this.id+'emailAddressPrimaryFlag'+index).focus();}}
198 var event=this.getEvent(event);var targetEl=this.getEventElement(event);var index=/[a-z]*\d?emailAddress(\d+)/i.exec(targetEl.id)[1];var verifyElementFlag=Dom.get(this.id+'emailAddressVerifiedFlag'+index);this.verifyElementValue=Dom.get(this.id+'emailAddressVerifiedValue'+index);verifyElementFlag.value=(trim(targetEl.value)==''||targetEl.value==this.verifyElementValue.value)?"true":"false"
199 if(verifyElementFlag.parentNode.childNodes.length>1){verifyElementFlag.parentNode.removeChild(verifyElementFlag.parentNode.lastChild);}
200 if(/emailAddress\d+$/.test(targetEl.id)&&isValidEmail(targetEl.value)&&!this.verifying&&verifyElementFlag.value=="false"){verifiedTextNode=document.createElement('span');verifyElementFlag.parentNode.appendChild(verifiedTextNode);verifiedTextNode.innerHTML=SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS');this.verifying=true;var cObj=YAHOO.util.Connect.asyncRequest('GET','index.php?module=Contacts&action=RetrieveEmail&target='+targetEl.id+'&email='+targetEl.value,{success:callbackFunction,failure:callbackFunction,scope:this});}},handleKeyDown:function(event){var e=this.getEvent(event);var eL=this.getEventElement(e);if((kc=e["keyCode"])){this.enterPressed=(kc==13)?true:false;this.tabPressed=(kc==9)?true:false;if(this.enterPressed||this.tabPressed){this.retrieveEmailAddress(e);if(this.enterPressed);this.freezeEvent(e);}}},getEvent:function(event){return(event?event:window.event);},getEventElement:function(e){return(e.srcElement?e.srcElement:(e.target?e.target:e.currentTarget));},freezeEvent:function(e){if(e.preventDefault)e.preventDefault();e.returnValue=false;e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation();return false;},addEmailAddress:function(tableId,address,primaryFlag,replyToFlag,optOutFlag,invalidFlag){if(this.addInProgress)
201 return;this.addInProgress=true;if(!address)
202 address="";var insertInto=Dom.get(tableId);var parentObj=insertInto.parentNode;var newContent=document.createElement("input");var nav=new String(navigator.appVersion);var newContentPrimaryFlag;if(SUGAR.isIE){newContentPrimaryFlag=document.createElement("<input name='emailAddressPrimaryFlag' />");}else{newContentPrimaryFlag=document.createElement("input");}
203 var newContentReplyToFlag=document.createElement("input");var newContentOptOutFlag=document.createElement("input");var newContentInvalidFlag=document.createElement("input");var newContentVerifiedFlag=document.createElement("input");var newContentVerifiedValue=document.createElement("input");var removeButton=document.createElement("img");var tbody=document.createElement("tbody");var tr=document.createElement("tr");var td1=document.createElement("td");var td2=document.createElement("td");var td3=document.createElement("td");var td4=document.createElement("td");var td5=document.createElement("td");var td6=document.createElement("td");var td7=document.createElement("td");var td8=document.createElement("td");newContent.setAttribute("type","text");newContent.setAttribute("name",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("id",this.id+"emailAddress"+this.numberEmailAddresses);newContent.setAttribute("tabindex",this.tabIndex);newContent.setAttribute("size","30");if(address!=''){newContent.setAttribute("value",address);}
204 removeButton.setAttribute("id",this.id+"removeButton"+this.numberEmailAddresses);removeButton.setAttribute("class","id-ff-remove");removeButton.setAttribute("name",this.numberEmailAddresses);removeButton.eaw=this;removeButton.setAttribute("src","index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=id-ff-remove.png");removeButton.onclick=function(){this.eaw.removeEmailAddress(this.name);};newContentPrimaryFlag.setAttribute("type","radio");newContentPrimaryFlag.setAttribute("name",this.id+"emailAddressPrimaryFlag");newContentPrimaryFlag.setAttribute("id",this.id+"emailAddressPrimaryFlag"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentPrimaryFlag.setAttribute("enabled","true");newContentReplyToFlag.setAttribute("type","radio");newContentReplyToFlag.setAttribute("name",this.id+"emailAddressReplyToFlag");newContentReplyToFlag.setAttribute("id",this.id+"emailAddressReplyToFlag"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentReplyToFlag.setAttribute("enabled","true");newContentReplyToFlag.eaw=this;newContentReplyToFlag['onclick']=function(){var form=document.forms[this.eaw.emailView];if(!form){form=document.forms['editContactForm'];}
205 var nav=new String(navigator.appVersion);if(nav.match(/MSIE/gim)){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){form.elements[i].checked=false;}}}
206 for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressReplyToFlag/gim)&&form.elements[i].type=='radio'&&id!=this.eaw.id){this.eaw.replyToFlagObject[this.eaw.id]=false;}}
207 if(this.eaw.replyToFlagObject[this.id]){this.eaw.replyToFlagObject[this.id]=false;this.checked=false;}else{this.eaw.replyToFlagObject[this.id]=true;this.checked=true;}}
208 newContentOptOutFlag.setAttribute("type","checkbox");newContentOptOutFlag.setAttribute("name",this.id+"emailAddressOptOutFlag[]");newContentOptOutFlag.setAttribute("id",this.id+"emailAddressOptOutFlag"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentOptOutFlag.setAttribute("enabled","true");newContentOptOutFlag.eaw=this;newContentOptOutFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentInvalidFlag.setAttribute("type","checkbox");newContentInvalidFlag.setAttribute("name",this.id+"emailAddressInvalidFlag[]");newContentInvalidFlag.setAttribute("id",this.id+"emailAddressInvalidFlag"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("value",this.id+"emailAddress"+this.numberEmailAddresses);newContentInvalidFlag.setAttribute("enabled","true");newContentInvalidFlag.eaw=this;newContentInvalidFlag['onClick']=function(){this.eaw.toggleCheckbox(this)};newContentVerifiedFlag.setAttribute("type","hidden");newContentVerifiedFlag.setAttribute("name",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("id",this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses);newContentVerifiedFlag.setAttribute("value","true");newContentVerifiedValue.setAttribute("type","hidden");newContentVerifiedValue.setAttribute("name",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("id",this.id+"emailAddressVerifiedValue"+this.numberEmailAddresses);newContentVerifiedValue.setAttribute("value",address);this.emailView=(this.emailView=='')?'EditView':this.emailView;addToValidateVerified(this.emailView,this.id+"emailAddressVerifiedFlag"+this.numberEmailAddresses,'bool',false,SUGAR.language.get('app_strings','LBL_VERIFY_EMAIL_ADDRESS'));tr.setAttribute("id",this.id+"emailAddressRow"+this.numberEmailAddresses);td1.setAttribute("nowrap","NOWRAP");td3.setAttribute("align","center");td4.setAttribute("align","center");td5.setAttribute("align","center");td6.setAttribute("align","center");td1.appendChild(newContent);td1.appendChild(document.createTextNode(" "));spanNode=document.createElement('span');spanNode.innerHTML='&nbsp;';td2.appendChild(spanNode);if(this.numberEmailAddresses!=0||typeof(this.emailIsRequired)=="undefined"||!this.emailIsRequired)
209 td2.appendChild(removeButton);td3.appendChild(newContentPrimaryFlag);td4.appendChild(newContentReplyToFlag);td5.appendChild(newContentOptOutFlag);td6.appendChild(newContentInvalidFlag);td7.appendChild(newContentVerifiedFlag);td8.appendChild(newContentVerifiedValue);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);if(typeof(this.module)!='undefined'&&this.module=='Users'){tr.appendChild(td4);}else{tr.appendChild(td5);tr.appendChild(td6);}
210 tr.appendChild(td7);tr.appendChild(td8);tbody.appendChild(tr);insertInto.appendChild(tbody);parentObj.insertBefore(Dom.get('targetBody'),insertInto);if(primaryFlag=='1'||(this.numberEmailAddresses==0)){newContentPrimaryFlag.setAttribute("checked",'true');}
211 if(replyToFlag=='1'){newContentReplyToFlag.setAttribute("checked","true");}
212 if(replyToFlag=='1'){this.replyToFlagObject[newContentReplyToFlag.id]=true;}else{this.replyToFlagObject[newContentReplyToFlag.id]=false;}
213 if(optOutFlag=='1'){newContentOptOutFlag.setAttribute("checked",'true');}
214 if(invalidFlag=='1'){newContentInvalidFlag.setAttribute("checked","true");}
215 newContent.eaw=this;newContent.onblur=function(e){this.eaw.retrieveEmailAddress(e)};newContent.onkeydown=function(e){this.eaw.handleKeyDown(e)};addToValidate(this.emailView,this.id+'emailAddress'+this.numberEmailAddresses,'email',this.emailIsRequired,SUGAR.language.get('app_strings','LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR'));this.numberEmailAddresses++;this.addInProgress=false;},removeEmailAddress:function(index){removeFromValidate(this.emailView,this.id+'emailAddress'+index);var oNodeToRemove=Dom.get(this.id+'emailAddressRow'+index);oNodeToRemove.parentNode.removeChild(oNodeToRemove);var removedIndex=parseInt(index);if(this.numberEmailAddresses!=removedIndex){for(var x=removedIndex+1;x<this.numberEmailAddresses;x++){Dom.get(this.id+'emailAddress'+x).setAttribute("name",this.id+"emailAddress"+(x-1));Dom.get(this.id+'emailAddress'+x).setAttribute("id",this.id+"emailAddress"+(x-1));if(Dom.get(this.id+'emailAddressInvalidFlag'+x)){Dom.get(this.id+'emailAddressInvalidFlag'+x).setAttribute("id",this.id+"emailAddressInvalidFlag"+(x-1));}
216 if(Dom.get(this.id+'emailAddressOptOutFlag'+x)){Dom.get(this.id+'emailAddressOptOutFlag'+x).setAttribute("id",this.id+"emailAddressOptOutFlag"+(x-1));}
217 if(Dom.get(this.id+'emailAddressPrimaryFlag'+x)){Dom.get(this.id+'emailAddressPrimaryFlag'+x).setAttribute("id",this.id+"emailAddressPrimaryFlag"+(x-1));}
218 Dom.get(this.id+'emailAddressVerifiedValue'+x).setAttribute("id",this.id+"emailAddressVerifiedValue"+(x-1));Dom.get(this.id+'emailAddressVerifiedFlag'+x).setAttribute("id",this.id+"emailAddressVerifiedFlag"+(x-1));var rButton=Dom.get(this.id+'removeButton'+x);rButton.setAttribute("name",(x-1));rButton.setAttribute("id",this.id+"removeButton"+(x-1));Dom.get(this.id+'emailAddressRow'+x).setAttribute("id",this.id+'emailAddressRow'+(x-1));}}
219 this.numberEmailAddresses--;if(this.numberEmailAddresses==0){return;}
220 var primaryFound=false;for(x=0;x<this.numberEmailAddresses;x++){if(Dom.get(this.id+'emailAddressPrimaryFlag'+x).checked){primaryFound=true;}}
221 if(!primaryFound){Dom.get(this.id+'emailAddressPrimaryFlag0').checked=true;Dom.get(this.id+'emailAddressPrimaryFlag0').value=this.id+'emailAddress0';}},toggleCheckbox:function(el)
222 {var form=document.forms[this.emailView];if(!form){form=document.forms['editContactForm'];}
223 if(SUGAR.isIE){for(i=0;i<form.elements.length;i++){var id=new String(form.elements[i].id);if(id.match(/emailAddressInvalidFlag/gim)&&form.elements[i].type=='checkbox'&&id!=el.id){form.elements[i].checked=false;}}
224 el.checked=true;}},forceSubmit:function(){var theForm=Dom.get(this.emailView);if(theForm){theForm.action.value='Save';if(!check_form(this.emailView)){return false;}
225 if(this.emailView=='EditView'){theForm.submit();}else if(this.emailView=='QuickCreate'){SUGAR.subpanelUtils.inlineSave(theForm.id,theForm.module.value.toLowerCase());}}}};emailAddressWidgetLoaded=true;})();// End of File include/SugarEmailAddress/SugarEmailAddress.js
226                                 
227 /*********************************************************************************
228  * SugarCRM is a customer relationship management program developed by
229  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
230  *
231  * This program is free software; you can redistribute it and/or modify it under
232  * the terms of the GNU Affero General Public License version 3 as published by the
233  * Free Software Foundation with the addition of the following permission added
234  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
235  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
236  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
237  *
238  * This program is distributed in the hope that it will be useful, but WITHOUT
239  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
240  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
241  * details.
242  *
243  * You should have received a copy of the GNU Affero General Public License along with
244  * this program; if not, see http://www.gnu.org/licenses or write to the Free
245  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
246  * 02110-1301 USA.
247  *
248  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
249  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
250  *
251  * The interactive user interfaces in modified source and object code versions
252  * of this program must display Appropriate Legal Notices, as required under
253  * Section 5 of the GNU Affero General Public License version 3.
254  *
255  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
256  * these Appropriate Legal Notices must retain the display of the "Powered by
257  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
258  * technical reasons, the Appropriate Legal Notices must display the words
259  * "Powered by SugarCRM".
260  ********************************************************************************/
261 if(typeof(SUGAR.collection)=="undefined"){SUGAR.collection=function(form_name,field_name,module,popupData){this.more_status=false;this.form=form_name;this.field=field_name;this.field_element_name=this.form+'_'+this.field;this.module=module;this.fields_count=0;this.extra_fields_count=0;this.first=true;this.primary_field="";this.cloneField=new Array();this.sqs_clone="";this.secondaries_values=new Array();this.update_fields=new Object();this.show_more_image=true;};SUGAR.collection.prototype={remove:function(num){var radio_els=this.get_radios();var div_el;if(radio_els.length==1){div_el=document.getElementById(this.field_element_name+'_input_div_'+num);var input_els=div_el.getElementsByTagName('input');input_els[0].value='';input_els[1].value='';if(this.primary_field){div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);radio_els=div_el.getElementsByTagName('input');radio_els[0].checked=false;}}else{div_el=document.getElementById(this.field_element_name+'_input_div_'+num);if(!div_el)
262 div_el=document.getElementById(this.field_element_name+'_radio_div_'+num);var tr_to_remove=document.getElementById('lineFields_'+this.field_element_name+'_'+num);div_el.parentNode.parentNode.parentNode.removeChild(tr_to_remove);var div_id='lineFields_'+this.field_element_name+'_'+num;if(typeof sqs_objects[div_id.replace("_field_","_")]!='undefined'){delete(sqs_objects[div_id.replace("_field_","_")]);}
263 var checked=false;for(var k=0;k<radio_els.length;k++){if(radio_els[k].checked){checked=true;}}
264 var primary_checked=document.forms[this.form].elements[this.field+"_allowed_to_check"];var allowed_to_check=true;if(primary_checked&&primary_checked.value=='false'){allowed_to_check=false;}
265 if(/EditView/.test(this.form)&&!checked&&typeof radio_els[0]!='undefined'&&allowed_to_check){radio_els[0].checked=true;this.changePrimary(true);this.js_more();this.js_more();}
266 if(radio_els.length==1){this.more_status=false;if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display!='none'){document.getElementById('more_'+this.field_element_name).style.display='none';}
267 this.show_arrow_label(false);this.js_more();}else{this.js_more();this.js_more();}}},get_radios:function(){return YAHOO.util.Selector.query('input[name^=primary]',document.getElementById(this.field_element_name+'_table'));},add:function(values){this.fields_count++;var Field0=this.init_clone(values);this.cloneField[1].appendChild(Field0);enableQS(true);this.changePrimary(false);if(document.getElementById('more_'+this.field_element_name)&&document.getElementById('more_'+this.field_element_name).style.display=='none'){document.getElementById('more_'+this.field_element_name).style.display='';}
268 if(!this.is_expanded()){this.js_more();this.show_arrow_label(true);}},add_secondaries:function(){clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects=='undefined'||typeof sqs_objects[clone_id]=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else if(typeof document.getElementById(this.form+'_'+this.field+'_collection_0')=='undefined'){setTimeout('collection["'+this.field_element_name+'"].add_secondaries();',1000);}else{this.create_clone();enableQS();this.changePrimary(true);for(key in this.secondaries_values){if(isInteger(key)){this.add(this.secondaries_values[key]);}}
269 this.js_more();this.js_more();}
270 initEditView(document.forms[this.form]);},init_clone:function(values){if(typeof this.cloneField[0]=='undefined'){return;}
271 if(typeof values=="undefined"){values=new Array();values['name']="";values['id']="";}
272 var count=this.fields_count;Field0=SUGAR.isIE?SUGAR.collection.safe_clone(this.cloneField[0],true):this.cloneField[0].cloneNode(true);Field0.id="lineFields_"+this.field_element_name+"_"+count;for(var ii=0;ii<Field0.childNodes.length;ii++){if(typeof(Field0.childNodes[ii].tagName)!='undefined'&&Field0.childNodes[ii].tagName=="TD"){for(var jj=0;jj<Field0.childNodes[ii].childNodes.length;jj++){currentNode=Field0.childNodes[ii].childNodes[jj];this.process_node(Field0.childNodes[ii],currentNode,values);}}}
273 return Field0;},process_node:function(parentNode,currentNode,values){if(parentNode.className=='td_extra_field'){if(parentNode.id){parentNode.id='';}
274 var toreplace=this.field+"_collection_extra_0";var re=new RegExp(toreplace,'g');parentNode.innerHTML=parentNode.innerHTML.replace(re,this.field+"_collection_extra_"+this.fields_count);}else if(currentNode.tagName&&currentNode.tagName=='SPAN'){currentNode.id=/_input/.test(currentNode.id)?this.field_element_name+'_input_div_'+this.fields_count:this.field_element_name+'_radio_div_'+this.fields_count;if(/_input/.test(currentNode.id)){currentNode.name='teamset_div';}
275 var input_els=currentNode.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].tagName&&input_els[x].tagName=='INPUT'){this.process_node(parentNode,input_els[x],values);}}}else if(currentNode.name){var toreplace=this.field+"_collection_0";var re=new RegExp(toreplace,'g');var name=currentNode.name;var new_name=name.replace(re,this.field+"_collection_"+this.fields_count);switch(name){case toreplace:var sqs_id=this.form+'_'+new_name;if(typeof this.sqs_clone!='undefined'){var sqs_clone=YAHOO.lang.JSON.stringify(this.sqs_clone);eval('sqs_objects[sqs_id]='+sqs_clone);for(var pop_field in sqs_objects[sqs_id]['populate_list']){if(typeof sqs_objects[sqs_id]['populate_list'][pop_field]=='string'){sqs_objects[sqs_id]['populate_list'][pop_field]=sqs_objects[sqs_id]['populate_list'][pop_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}
276 for(var req_field in sqs_objects[sqs_id]['required_list']){if(typeof sqs_objects[sqs_id]['required_list'][req_field]=='string'){sqs_objects[sqs_id]['required_list'][req_field]=sqs_objects[sqs_id]['required_list'][req_field].replace(RegExp('_0','g'),"_"+this.fields_count);}}}
277 currentNode.name=new_name;currentNode.id=new_name;currentNode.value=values['name'];break;case"id_"+toreplace:currentNode.name=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.id=new_name.replace(RegExp('_0','g'),"_"+this.fields_count);currentNode.value=values['id'];break;case"btn_"+toreplace:currentNode.name=new_name;currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(re,this.field+"_collection_"+this.fields_count);currentNode.attributes['onclick'].value=currentNode.attributes['onclick'].value.replace(RegExp(this.field+"_collection_extra_0",'g'),this.field+"_collection_extra_"+this.fields_count);break;case"allow_new_value_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;break;case"remove_"+toreplace:currentNode.name=new_name;currentNode.id=new_name;currentNode.setAttribute('collection_id',this.field_element_name);currentNode.setAttribute('remove_id',this.fields_count);currentNode.onclick=function(){collection[this.getAttribute('collection_id')].remove(this.getAttribute('remove_id'));};break;case"primary_"+this.field+"_collection":currentNode.id=new_name;currentNode.value=this.fields_count;currentNode.checked=false;currentNode.setAttribute('defaultChecked','');break;default:alert(toreplace+'|'+currentNode.name+'|'+name+'|'+new_name);break;}}},js_more:function(val){if(this.show_more_image){var more_=document.getElementById('more_img_'+this.field_element_name);var arrow=document.getElementById('arrow_'+this.field);var radios=this.get_radios();if(this.more_status==false){more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";this.more_status=true;var hidden_count=0;for(var k=0;k<radios.length;k++){if(radios[k].type&&radios[k].type=='radio'){if(radios[k].checked){radios[k].parentNode.parentNode.parentNode.style.display='';}else{radios[k].parentNode.parentNode.parentNode.style.display='none';hidden_count++;}}}
278 if(hidden_count==radios.length){radios[0].parentNode.parentNode.parentNode.style.display='';}
279 arrow.value='hide';}else{more_.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";this.more_status=false;for(var k=0;k<radios.length;k++){if(isInteger(k)){radios[k].parentNode.parentNode.parentNode.style.display='';}}
280 arrow.value='show';}
281 var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.innerHTML=arrow.value=='show'?SUGAR.language.get('app_strings','LBL_HIDE'):SUGAR.language.get('app_strings','LBL_SHOW');}}},create_clone:function(){var oneField=document.getElementById('lineFields_'+this.field_element_name+'_0');this.cloneField[0]=SUGAR.isIE?SUGAR.collection.safe_clone(oneField,true):oneField.cloneNode(true);this.cloneField[1]=oneField.parentNode;this.more_status=true;var clone_id=this.form+'_'+this.field+'_collection_0';if(typeof sqs_objects[clone_id]!='undefined'){var clone=YAHOO.lang.JSON.stringify(sqs_objects[clone_id]);eval('this.sqs_clone='+clone);}},validateTemSet:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));var has_primary=false;var primary_field_id=fieldname+'_collection_0';for(t in input_elements){primary_field_id=fieldname+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){has_primary=true;}
282 break;}}
283 if(!has_primary){return false;}
284 return true;}
285 return true;},getTeamIdsfromUI:function(formname,fieldname){var team_ids=new Array();var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){input_elements=YAHOO.util.Selector.query('input[type=hidden]',document.getElementById(table_element_id));for(t=0;t<input_elements.length;t++){if(input_elements[t].id.match("id_"+fieldname+"_collection_")!=null){team_ids.push(input_elements[t].value);}}}
286 return team_ids;},getPrimaryTeamidsFromUI:function(formname,fieldname){var table_element_id=formname+'_'+fieldname+'_table';if(document.getElementById(table_element_id)){var input_elements=YAHOO.util.Selector.query('input[type=radio]',document.getElementById(table_element_id));for(t in input_elements){var primary_field_id='id_'+document.forms[formname][fieldname].name+'_collection_'+input_elements[t].value;if(input_elements[t].type&&input_elements[t].type=='radio'&&input_elements[t].checked==true){if(document.forms[formname].elements[primary_field_id].value!=''){return document.forms[formname].elements[primary_field_id].value;}}}}
287 return'';},changePrimary:function(noAdd){var old_primary=this.primary_field;var radios=this.get_radios();for(var k=0;k<radios.length;k++){var qs_id=radios[k].id.replace('primary_','');if(radios[k].checked){this.primary_field=qs_id;}else{qs_id=qs_id+'_'+k;}
288 qs_id=this.form+'_'+qs_id;if(typeof sqs_objects[qs_id]!='undefined'&&sqs_objects[qs_id]['primary_field_list']){for(var ii=0;ii<sqs_objects[qs_id]['primary_field_list'].length;ii++){if(radios[k].checked&&qs_id!=old_primary){sqs_objects[qs_id]['field_list'].push(sqs_objects[qs_id]['primary_field_list'][ii]);sqs_objects[qs_id]['populate_list'].push(sqs_objects[qs_id]['primary_populate_list'][ii]);}else if(old_primary==qs_id&&!radios[k].checked){sqs_objects[qs_id]['field_list'].pop();sqs_objects[qs_id]['populate_list'].pop();}}}}
289 if(noAdd){enableQS(false);}
290 this.first=false;},js_more_detail:function(id){var more_img=document.getElementById('more_img_'+id);if(more_img.style.display=='inline'){more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=advanced_search.gif";}else{more_img.src="index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=basic_search.gif";}},replace_first:function(values){for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){var name_field=document.getElementById(this.field+"_collection_"+i);var id_field=document.getElementById("id_"+this.field+"_collection_"+i);name_field.value=values['name'];id_field.value=values['id'];break;}}},clean_up:function(){var divsToClean=new Array();var isFirstFieldEmpty=false;var divCount=0;for(var i=0;i<=this.fields_count;i++){var div_el=document.getElementById(this.field_element_name+'_input_div_'+i);if(div_el){input_els=div_el.getElementsByTagName('input');for(var x=0;x<input_els.length;x++){if(input_els[x].id&&input_els[x].id==(this.field+'_collection_'+i)&&trim(input_els[x].value)==''){if(divCount==0){isFirstFieldEmpty=true;}else{divsToClean.push(i);}}}
291 divCount++;}}
292 for(var j=0;j<divsToClean.length;j++){this.remove(divsToClean[j]);}
293 return isFirstFieldEmpty;},show_arrow_label:function(show){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){more_div.style.display=show?'':'none';}},is_expanded:function(){var more_div=document.getElementById('more_div_'+this.field_element_name);if(more_div){return more_div.style.display=='';}
294 return false;}}
295 SUGAR.collection.safe_clone=function(e,recursive)
296 {if(e.nodeName=="#text")
297 {return document.createTextNode(e.data);}
298 if(!e.tagName)return false;var newNode=document.createElement(e.tagName);if(!newNode)return false;var properties=['class','style','name','type','valign','border','width','height','top','bottom','left','right','scope','row','columns','src','href','className','align','nowrap'];for(var i in properties)
299 {if(e[properties[i]])
300 {if((properties[i]!='style'||!SUGAR.isIE)&&(properties[i]!='href'||e.tagName=='a'||e.tagName=='iframe'))
301 newNode[properties[i]]=e[properties[i]];}}
302 if(recursive)
303 {for(var i in e.childNodes)
304 {if(e.childNodes[i].nodeName&&(!e.className||e.className!="yui-ac-container"))
305 {var child=SUGAR.collection.safe_clone(e.childNodes[i],true);if(child)newNode.appendChild(child);}}}
306 return newNode;}}// End of File include/SugarFields/Fields/Collection/SugarFieldCollection.js
307                                 
308 /*********************************************************************************
309  * SugarCRM is a customer relationship management program developed by
310  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
311  *
312  * This program is free software; you can redistribute it and/or modify it under
313  * the terms of the GNU Affero General Public License version 3 as published by the
314  * Free Software Foundation with the addition of the following permission added
315  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
316  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
317  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
318  *
319  * This program is distributed in the hope that it will be useful, but WITHOUT
320  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
321  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
322  * details.
323  *
324  * You should have received a copy of the GNU Affero General Public License along with
325  * this program; if not, see http://www.gnu.org/licenses or write to the Free
326  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
327  * 02110-1301 USA.
328  *
329  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
330  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
331  *
332  * The interactive user interfaces in modified source and object code versions
333  * of this program must display Appropriate Legal Notices, as required under
334  * Section 5 of the GNU Affero General Public License version 3.
335  *
336  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
337  * these Appropriate Legal Notices must retain the display of the "Powered by
338  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
339  * technical reasons, the Appropriate Legal Notices must display the words
340  * "Powered by SugarCRM".
341  ********************************************************************************/
342 SUGAR.inboundEmail={};Rot13={map:null,convert:function(a){Rot13.init();var s="";for(i=0;i<a.length;i++){var b=a.charAt(i);s+=((b>='A'&&b<='Z')||(b>='a'&&b<='z')?Rot13.map[b]:b);}
343 return s;},init:function(){if(Rot13.map!=null)
344 return;var map=new Array();var s="abcdefghijklmnopqrstuvwxyz";for(i=0;i<s.length;i++)
345 map[s.charAt(i)]=s.charAt((i+13)%26);for(i=0;i<s.length;i++)
346 map[s.charAt(i).toUpperCase()]=s.charAt((i+13)%26).toUpperCase();Rot13.map=map;},write:function(a){return Rot13.convert(a);}}
347 function getEncryptedPassword(login,password,mailbox){var words=new Array(login,password,mailbox);for(i=0;i<3;i++){word=words[i];if(word.indexOf('&')>0){fragment1=word.substr(0,word.indexOf('&'));fragment2=word.substr(word.indexOf('&')+1,word.length);newWord=fragment1+'::amp::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
348 if(word.indexOf('+')>0){fragment1=word.substr(0,word.indexOf('+'));fragment2=word.substr(word.indexOf('+')+1,word.length);newWord=fragment1+'::plus::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}
349 if(word.indexOf('%')>0){fragment1=word.substr(0,word.indexOf('%'));fragment2=word.substr(word.indexOf('%')+1,word.length);newWord=fragment1+'::percent::'+fragment2;words[i]=newWord;word=newWord;fragment1='';fragment2='';}}
350 return words;}
351 function ie_test_open_popup_with_submit(module_name,action,pageTarget,width,height,mail_server,protocol,port,login,password,mailbox,ssl,personal,formName,ie_id)
352 {if(!formName)formName="testSettingsView";var words=getEncryptedPassword(login,password,mailbox);var isPersonal=(personal)?'true':'false';if(!isDataValid(formName,true)){return;}
353 URL='index.php?'
354 +'module='+module_name
355 +'&to_pdf=1'
356 +'&action='+action
357 +'&target='+pageTarget
358 +'&target1='+pageTarget
359 +'&server_url='+mail_server
360 +'&email_user='+words[0]
361 +'&protocol='+protocol
362 +'&port='+port
363 +'&email_password='+words[1]
364 +'&mailbox='+words[2]
365 +'&ssl='+ssl
366 +'&ie_id='+ie_id
367 +'&personal='+isPersonal;var SI=SUGAR.inboundEmail;if(!SI.testDlg){SI.testDlg=new YAHOO.widget.SimpleDialog("testSettingsDiv",{width:width+"px",draggable:true,dragOnly:true,close:true,constraintoviewport:true,modal:true,loadingText:SUGAR.language.get("app_strings","LBL_EMAIL_LOADING")});SI.testDlg._updateContent=function(o){var w=this.cfg.config.width.value+"px";this.setBody(o.responseText);if(this.evalJS)
368 SUGAR.util.evalScript(o.responseText);if(!SUGAR.isIE)
369 this.body.style.width=w}}
370 var title=SUGAR.language.get('Emails','LBL_TEST_SETTINGS');if(typeof(title)=="undefined"||title=="undefined")
371 title=SUGAR.language.get('InboundEmail','LBL_TEST_SETTINGS');SI.testDlg.setHeader(title);SI.testDlg.setBody(SUGAR.language.get("app_strings","LBL_EMAIL_LOADING"));SI.testDlg.render(document.body);var Connect=YAHOO.util.Connect;if(Connect.url)URL=Connect.url+"&"+url;Connect.asyncRequest("GET",URL,{success:SI.testDlg._updateContent,failure:SI.testDlg.hide,scope:SI.testDlg});SI.testDlg.show();}
372 function isDataValid(formName,validateMonitoredFolder){var formObject=document.getElementById(formName);var errors=new Array();var out=new String();if(trim(formObject.server_url.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_SERVER'));}
373 if(trim(formObject.email_user.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_USER'));}
374 if(formObject.protocol.protocol==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PROTOCOL'));}
375 if(formObject.protocol.value=='imap'&&validateMonitoredFolder){if(trim(formObject.mailbox.value)==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_MONITORED_FOLDER'));}}
376 if(formObject.port.value==""){errors.push(SUGAR.language.get('app_strings','LBL_EMAIL_ERROR_PORT'));}
377 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";}
378 out+=errors[i];}
379 alert(out);return false;}else{return true;}}
380 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?'
381 +'module='+module_name
382 +'&to_pdf=1'
383 +'&action='+action
384 +'&target='+pageTarget
385 +'&target1='+pageTarget
386 +'&server_url='+mail_server
387 +'&email_user='+words[0]
388 +'&protocol='+protocol
389 +'&port='+port
390 +'&email_password='+words[1]
391 +'&mailbox='+words[2]
392 +'&ssl='+ssl
393 +'&personal='+isPersonal
394 +'&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)
395 this.body.style.width=w}}
396 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();}
397 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;}}}
398 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';}}}
399 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='';}
400 else{mailbox.value="INBOX";mailbox.disabled=false;try{mailbox.style.display="none";trashFolderRow.style.display="none";sentFolderRow.style.display="none";trashFolderRow1.style.display="none";subscribeFolderButton.style.display="none";}catch(e){};label_inbox.style.display="none";}}// End of File modules/InboundEmail/InboundEmail.js
401                                 
402 /*********************************************************************************
403  * SugarCRM is a customer relationship management program developed by
404  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
405  * 
406  * This program is free software; you can redistribute it and/or modify it under
407  * the terms of the GNU Affero General Public License version 3 as published by the
408  * Free Software Foundation with the addition of the following permission added
409  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
410  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
411  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
412  * 
413  * This program is distributed in the hope that it will be useful, but WITHOUT
414  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
415  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
416  * details.
417  * 
418  * You should have received a copy of the GNU Affero General Public License along with
419  * this program; if not, see http://www.gnu.org/licenses or write to the Free
420  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
421  * 02110-1301 USA.
422  * 
423  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
424  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
425  * 
426  * The interactive user interfaces in modified source and object code versions
427  * of this program must display Appropriate Legal Notices, as required under
428  * Section 5 of the GNU Affero General Public License version 3.
429  * 
430  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
431  * these Appropriate Legal Notices must retain the display of the "Powered by
432  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
433  * technical reasons, the Appropriate Legal Notices must display the words
434  * "Powered by SugarCRM".
435  ********************************************************************************/
436
437 SUGAR.email2 = {
438     cache : new Object(),
439     o : null, // holder for reference to AjaxObject's return object (used in composeDraft())
440     reGUID : new RegExp(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i),
441     templates : {},
442     tinyInstances : {
443         currentHtmleditor : ''
444     },
445
446     /**
447      * preserves hits from email server
448      */ 
449     _setDetailCache : function(ret) {
450         if(ret.meta) {
451             var compKey = ret.meta.mbox + ret.meta.uid;
452
453             if(!SUGAR.email2.cache[compKey]) {
454                 SUGAR.email2.cache[compKey] = ret;
455             }
456         }
457     },
458
459     autoSetLayout : function() {
460         var c = document.getElementById('container');
461         var tHeight = YAHOO.util.Dom.getViewportHeight() - YAHOO.util.Dom.getY(c) - 35;
462         //Ensure a minimum height.
463         tHeight = Math.max(tHeight, 550);
464         c.style.height = tHeight + "px";
465         SUGAR.email2.complexLayout.set('height', tHeight);
466         SUGAR.email2.complexLayout.set('width', YAHOO.util.Dom.getViewportWidth() - 40);
467         SUGAR.email2.complexLayout.render();
468         SUGAR.email2.listViewLayout.resizePreview();        
469     }
470 };
471
472 /**
473  * Shows overlay progress message
474  */
475 function overlayModal(title, body) {
476     overlay(title, body);
477 }
478 function overlay(reqtitle, body, type, additconfig) {
479     var config = { };
480     if (typeof(additconfig) == "object") {
481         var config = additconfig;
482     }
483     config.type = type;
484     config.title = reqtitle;
485     config.msg = body;
486     YAHOO.SUGAR.MessageBox.show(config);
487 };
488
489 function hideOverlay() {
490         YAHOO.SUGAR.MessageBox.hide();
491 };
492 // End of File modules/Emails/javascript/EmailUIShared.js
493                                 
494 /*********************************************************************************
495  * SugarCRM is a customer relationship management program developed by
496  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
497  * 
498  * This program is free software; you can redistribute it and/or modify it under
499  * the terms of the GNU Affero General Public License version 3 as published by the
500  * Free Software Foundation with the addition of the following permission added
501  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
502  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
503  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
504  * 
505  * This program is distributed in the hope that it will be useful, but WITHOUT
506  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
507  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
508  * details.
509  * 
510  * You should have received a copy of the GNU Affero General Public License along with
511  * this program; if not, see http://www.gnu.org/licenses or write to the Free
512  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
513  * 02110-1301 USA.
514  * 
515  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
516  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
517  * 
518  * The interactive user interfaces in modified source and object code versions
519  * of this program must display Appropriate Legal Notices, as required under
520  * Section 5 of the GNU Affero General Public License version 3.
521  * 
522  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
523  * these Appropriate Legal Notices must retain the display of the "Powered by
524  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
525  * technical reasons, the Appropriate Legal Notices must display the words
526  * "Powered by SugarCRM".
527  ********************************************************************************/
528
529
530 (function() {
531         var sw = YAHOO.SUGAR,
532                 Event = YAHOO.util.Event,
533                 Connect = YAHOO.util.Connect,
534             Dom = YAHOO.util.Dom
535             SE = SUGAR.email2;
536
537 ///////////////////////////////////////////////////////////////////////////////
538 ////    EMAIL ACCOUNTS
539 SE.accounts = {
540     outboundDialog : null,
541     inboundAccountEditDialog : null,
542     inboundAccountsSettingsTable : null,
543     outboundAccountsSettingsTable : null,
544     testOutboundDialog : null,
545     errorStyle : 'input-error',
546     normalStyle : '',
547     newAddedOutboundId : '',
548
549     /**
550      * makes async call to retrieve an outbound instance for editting
551      */
552      //EXT111
553     editOutbound : function(obi) {
554
555             AjaxObject.startRequest(AjaxObject.accounts.callbackEditOutbound, urlStandard + "&emailUIAction=editOutbound&outbound_email=" + obi);
556
557     },
558     deleteOutbound : function(obi) {
559
560         if(obi.match(/^(add|line|sendmail)+/)) {
561             alert('Invalid Operation');
562         } else {
563                 overlay(app_strings.LBL_EMAIL_DELETING_OUTBOUND, app_strings.LBL_EMAIL_ONE_MOMENT);
564             AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&outbound_email=" + obi);
565         }
566     },
567     //EXT111
568     getReplyAddress : function() {
569         var primary = '';
570
571         for(var i=0; i<SE.userPrefs.current_user.emailAddresses.length; i++) {
572             var addy = SE.userPrefs.current_user.emailAddresses[i];
573
574             if(addy.primary_address == "1") {
575                 primary = addy.email_address;
576             }
577
578             if(addy.reply_to == "1") {
579                 return addy.email_address;
580             }
581         }
582
583         return primary;
584     },
585
586     /**
587      * Called on "Accounts" tab activation event
588      */
589     lazyLoad : function() {
590
591         this._setupInboundAccountTable();
592         this._setupOutboundAccountTable();
593
594     },
595
596     _setupInboundAccountTable: function()
597     {
598         //Setup the inbound mail settings
599         if(!this.inboundAccountsSettingsTable)
600         {
601                   this.customImageFormatter = function(elLiner, oRecord, oColumn, oData) {
602                                         var clckEvent = oColumn.key;
603                                         var imgSrc = "";
604                                         var is_group = oRecord.getData("is_group");
605                                         if(!is_group)
606                                         {
607                                         if(oColumn.key == 'edit')
608                                         {
609                                                 clckEvent = "SUGAR.email2.accounts.getIeAccount('"+ oRecord.getData('id') +"')";
610                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
611                                         }
612                                         else if(oColumn.key == 'delete')
613                                         {
614                                                 clckEvent = "SUGAR.email2.accounts.deleteIeAccount('"+ oRecord.getData('id') +"','" + oRecord.getData('group_id') +"')";
615                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
616                                         }
617                                 elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
618                                         }
619                    };
620
621                    this.showBoolean = function(el, oRecord, oColumn, oData)
622                    {
623                        var is_group = oRecord.getData("is_group");
624                        var bChecked = oData;
625                        bChecked = (bChecked) ? " checked" : "";
626                        if(!is_group)
627                        {
628                        el.innerHTML = "<input type=\"radio\"" + bChecked +
629                            " name=\"col" + oColumn.getId() + "-radio\"" +
630                            " class=\"yui-dt-radio\">";
631                        }
632                    };
633
634
635                 YAHOO.widget.DataTable.Formatter.customImage = this.customImageFormatter;
636                 YAHOO.widget.DataTable.Formatter.showBoolean = this.showBoolean;
637
638                 var typeHoverHelp = '&nbsp;<div id="rollover"><a href="#" class="rollover">'+
639                                     '<img border="0" src="themes/default/images/helpInline.gif">' +
640                                     '<div style="text-align:left"><span>' + mod_strings.LBL_EMAIL_INBOUND_TYPE_HELP + '</span></div></a></div>';
641
642
643                 this.ieColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_SETTINGS_NAME }, {key:'server_url',label:ie_mod_strings.LBL_SERVER_URL},
644                                       {key:'is_active',label:ie_mod_strings.LBL_STATUS_ACTIVE,formatter:"checkbox",className:'yui-cstm-cntrd-liner'},
645                                       {key:'is_default',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPDEFAULT,formatter:"showBoolean",className:'yui-cstm-cntrd-liner'},
646                                       {key:'type',label:mod_strings.LBL_LIST_TYPE + typeHoverHelp },
647                                       {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"customImage",className:'yui-cstm-cntrd-liner'},
648                                       {key:'delete',label:app_strings.LBL_EMAIL_DELETE,formatter:"customImage",className:'yui-cstm-cntrd-liner'}];
649                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=rebuildShowAccount";
650                 this.ieDataSource = new YAHOO.util.DataSource(query);
651                         this.ieDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
652                         this.ieDataSource.responseSchema = {
653                                 resultsList: "account_list",
654                                 fields: [{key:'id'},{key:'name'},'is_active',{key:'server_url'},'is_group','group_id','is_default','has_groupfolder','type']
655                         };
656                 this.inboundAccountsSettingsTable = new YAHOO.widget.DataTable("inboundAccountsTable", this.ieColumnDefs, this.ieDataSource);
657                         this.inboundAccountsSettingsTable.subscribe("checkboxClickEvent", function(oArgs){
658
659                     var elCheckbox = oArgs.target;
660                     var oColumn = this.getColumn(elCheckbox);
661                         if(oColumn.key == 'is_active')
662                         {
663                                 var oRecord = this.getRecord(elCheckbox);
664                                 oRecord.setData("is_active",elCheckbox.checked);
665                                 var t_id = oRecord.getData('id');
666                         var isGroupFolder = oRecord.getData('has_groupfolder');
667
668                         if(isGroupFolder)
669                             SUGAR.email2.folders.updateSubscriptions();
670                         else
671                         SUGAR.email2.folders.setFolderSelection();
672
673                         }
674                 });
675                         var lastDefaultSelectedId = "";
676                 this.inboundAccountsSettingsTable.subscribe("radioClickEvent", function(oArgs){
677
678                     var elRadio = oArgs.target;
679                     var oColumn = this.getColumn(elRadio);
680                         if(oColumn.key == 'is_default')
681                         {
682                                 var oRecord = this.getRecord(elRadio);
683                                 var t_id = oRecord.getData('id');
684                                 var t_isGroup = oRecord.getData('is_group');
685                                 if(t_id != lastDefaultSelectedId && !t_isGroup)
686                                 {
687                                                 SUGAR.default_inbound_accnt_id = t_id; //Set in the global space for access during compose
688                                         lastDefaultSelectedId = t_id;
689                                         AjaxObject.startRequest(callbackDefaultOutboundSave, urlStandard + "&emailUIAction=saveDefaultOutbound&id="+ t_id);
690                                 }
691                                 else if(t_isGroup)
692                                    YAHOO.util.Event.preventDefault(oArgs.event); //Do not allow users to select group mailboxes as a default.
693
694                         }
695                 });
696
697                         this.inboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.inboundAccountsSettingsTable.onEventHighlightRow);
698                         this.inboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.inboundAccountsSettingsTable.onEventUnhighlightRow);
699         }
700     },
701      _setupOutboundAccountTable: function()
702     {
703         if(!this.outboundAccountsSettingsTable)
704         {
705                 this.obImageFormatter = function(elLiner, oRecord, oColumn, oData) {
706                                         var clckEvent = oColumn.key;
707                                         var imgSrc = "";
708                                         var isEditable = oRecord.getData("is_editable");
709                                         var type = oRecord.getData("type");
710                                         if(isEditable)
711                                         {
712                                         if(oColumn.key == 'edit')
713                                         {
714                                                 clckEvent = "SUGAR.email2.accounts.editOutbound('"+ oRecord.getData('id') +"')";
715                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
716                                         }
717                                         else if(oColumn.key == 'delete' && type == 'user')
718                                         {
719                                                 clckEvent = "SUGAR.email2.accounts.deleteOutbound('"+ oRecord.getData('id')+"')";
720                                                 imgSrc = 'index.php?entryPoint=getImage&amp;themeName=Sugar&amp;imageName='+oColumn.key+'_inline.gif';
721                                         }
722                                         if(imgSrc != '')
723                                     elLiner.innerHTML = '<img onclick="'+clckEvent+'" src="'+imgSrc+'" align="absmiddle" border="0"/>';
724                                         }
725                 };
726
727                 //Custom formatter to display any error messages.
728                         this.messageDisplay = function(elLiner, oRecord, oColumn, oData) {
729
730                     if(SUGAR.email2.composeLayout.outboundAccountErrors == null)
731                                             SUGAR.email2.composeLayout.outboundAccountErrors = {};
732
733                         var id = oRecord.getData('id');
734                                         var message = oRecord.getData("errors");
735                                         if(message != '')
736                                         {
737                                     elLiner.innerHTML = '<span class="required">' + message + '</span>';
738                                         //Add the id and message for all outbound accounts.
739                                         SUGAR.email2.composeLayout.outboundAccountErrors[id] = message;
740                                         }
741                                         else
742                                         {
743                                             if(typeof(SUGAR.email2.composeLayout.outboundAccountErrors[id]) != 'undefined' )
744                                             delete SUGAR.email2.composeLayout.outboundAccountErrors[id];
745                                         }
746                 };
747                 YAHOO.widget.DataTable.Formatter.actionsImage = this.obImageFormatter;
748                 YAHOO.widget.DataTable.Formatter.messageDisplay = this.messageDisplay;
749
750                 this.obAccntsColumnDefs = [{key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME }, {key:'mail_smtpserver',label:app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER},
751                                                                    {key:'edit',label:mod_strings.LBL_BUTTON_EDIT,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
752                                                                    {key:'delete', label:app_strings.LBL_EMAIL_DELETE,formatter:"actionsImage",className:'yui-cstm-cntrd-liner'},
753                                                                    {key:'messages',label:'', formatter:"messageDisplay",className:'yui-cstm-cntrd-liner'}];
754
755                 var query = "index.php?module=Emails&action=EmailUIAjax&to_pdf=true&emailUIAction=retrieveAllOutbound";
756                 this.obDataSource = new YAHOO.util.DataSource(query);
757                         this.obDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
758                         this.obDataSource.responseSchema = {
759
760                                 resultsList: "outbound_account_list",
761                                 fields: ['id','name','is_editable','mail_smtpserver','type','errors']
762                         };
763
764                 this.outboundAccountsSettingsTable = new YAHOO.widget.DataTable("outboundAccountsTable", this.obAccntsColumnDefs, this.obDataSource);
765
766
767                         this.outboundAccountsSettingsTable.subscribe("rowMouseoverEvent", this.outboundAccountsSettingsTable.onEventHighlightRow);
768                         this.outboundAccountsSettingsTable.subscribe("rowMouseoutEvent", this.outboundAccountsSettingsTable.onEventUnhighlightRow);
769                 this.outboundAccountsSettingsTable.subscribe("postRenderEvent",this.rebuildMailerOptions);
770         }
771     },
772     /**
773      * Displays a modal diaglogue to edit outbound account settings
774      */
775     showEditInboundAccountDialogue : function(clear) {
776
777         if(!this.inboundAccountEditDialog) {
778                 var EAD = this.inboundAccountEditDialog = new YAHOO.widget.Dialog("editAccountDialogue", {
779                 modal:true,
780                                 visible:true,
781                 fixedcenter:true,
782                 constraintoviewport: true,
783                 width   : "600px",
784                 shadow  : true
785             });
786                         EAD.showEvent.subscribe(function() {
787                 var el = this.element;
788                 var viewH = YAHOO.util.Dom.getViewportHeight();
789                 if (this.header && el && viewH - 50 < el.clientHeight) {
790                     var body = this.header.nextElementSibling;
791                                         body.style.overflow = "auto";
792                     body.style.height = (viewH - 50) + "px";
793                 }
794             }, EAD);
795             EAD.setHeader(mod_strings.LBL_EMAIL_ACCOUNTS_INBOUND);
796                         Dom.removeClass("editAccountDialogue", "yui-hidden");
797
798         } // end lazy load
799
800         if(clear == undefined || clear == true)
801         {
802                 SE.accounts.clearInboundAccountEditScreen();
803                 //Set default protocol to IMAP when creating new records
804                 document.forms['ieAccount'].elements['protocol'].value = "imap";
805                 SE.accounts.setPortDefault();
806         }
807
808         //Check if we should display username/password fields for outbound account if errors were detected.
809         this.checkOutBoundSelection();
810
811         this.inboundAccountEditDialog.render();
812         this.inboundAccountEditDialog.show();
813         SUGAR.util.setEmailPasswordDisplay('email_password', clear == false);
814     },
815
816     /**
817     *  Set all fields on the outbound edit form to either enabled/disabled
818     *  except for the username/password.
819     *
820     */
821     toggleOutboundAccountDisabledFields: function(disable)
822     {
823         var fields = ['mail_name', 'mail_smtpserver','mail_smtpport','mail_smtpauth_req'];
824         for(var i=0;i<fields.length;i++)
825         {
826             document.getElementById(fields[i]).disabled = disable;
827         }
828         if(disable)
829             Dom.addClass("mail_smtpssl_row", "yui-hidden");
830         else
831             Dom.removeClass('mail_smtpssl_row', "yui-hidden");
832
833     },
834     /**
835     * Refresh the inbound accounts table.
836     */
837     refreshInboundAccountTable : function()
838     {
839             this.inboundAccountsSettingsTable.getDataSource().sendRequest('',
840                 {
841                         success: this.inboundAccountsSettingsTable.onDataReturnInitializeTable,
842                                 scope: this.inboundAccountsSettingsTable }
843                         );
844     },
845     /**
846     * Refresh the outbound accounts table.
847     */
848     refreshOuboundAccountTable : function()
849     {
850             this.outboundAccountsSettingsTable.getDataSource().sendRequest('',
851                 {
852                         success: this.outboundAccountsSettingsTable.onDataReturnInitializeTable,
853                                 scope: this.outboundAccountsSettingsTable }
854                         );
855     },
856     /**
857      * Displays a modal diaglogue to add a SMTP server
858      */
859     showAddSmtp : function() {
860         // lazy load dialogue
861         if(!this.outboundDialog) {
862                 this.outboundDialog = new YAHOO.widget.Dialog("outboundDialog", {
863                 modal:true,
864                                 visible:true,
865                 fixedcenter:true,
866                 constraintoviewport: true,
867                 width   : "750px",
868                 shadow  : true
869             });
870             this.outboundDialog.setHeader(app_strings.LBL_EMAIL_ACCOUNTS_OUTBOUND);
871             this.outboundDialog.hideEvent.subscribe(function(){
872                 //If add was used to bring this dialog up, and we are hiding without creating one, then set it back to the first option
873                 var out = Dom.get("outbound_email");
874                 if (out && out.value == "SYSTEM_ADD")
875                 {
876                         out.value = out.options[0].value;
877                 }
878                 //Check if we should display username/password for system account.
879                 SE.accounts.checkOutBoundSelection();
880                 return true;
881             });
882
883             Dom.removeClass("outboundDialog", "yui-hidden");
884         } // end lazy load
885
886         // clear out form
887         var form = document.getElementById('outboundEmailForm');
888         for(i=0; i<form.elements.length; i++) {
889             if(form.elements[i].name == 'mail_smtpport') {
890                 form.elements[i].value = 25;
891             } else if(form.elements[i].type != 'button' && form.elements[i].type != 'checkbox') {
892                 form.elements[i].value = '';
893             } else if(form.elements[i].type == 'checkbox') {
894                 form.elements[i].checked = false;
895             }
896         }
897         //Render the SMTP buttons
898         if ( !SUGAR.smtpButtonGroup ) {
899             SUGAR.smtpButtonGroup = new YAHOO.widget.ButtonGroup("smtpButtonGroup");
900             SUGAR.smtpButtonGroup.subscribe('checkedButtonChange', function(e)
901             {
902                 SUGAR.email2.accounts.changeEmailScreenDisplay(e.newValue.get('value'));
903                 document.getElementById('smtp_settings').style.display = '';
904                 form.mail_smtptype.value = e.newValue.get('value');
905             });
906             YAHOO.widget.Button.addHiddenFieldsToForm(form);
907         }
908         //Hide Username/Password
909         SUGAR.email2.accounts.smtp_authenticate_field_display();
910         //Unset readonly fields
911         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
912         SUGAR.email2.accounts.changeEmailScreenDisplay('other');
913                 this.outboundDialog.render();
914         this.outboundDialog.show();
915     },
916
917     /**
918      * Accounts' Advanced Settings view toggle
919      */
920     toggleAdv : function() {
921         var adv = document.getElementById("ie_adv");
922         if(adv.style.display == 'none') {
923             adv.style.display = "";
924         } else {
925             adv.style.display = 'none';
926         }
927     },
928
929         smtp_authenticate_field_display : function() {
930                 var smtpauth_req = document.getElementById("mail_smtpauth_req");
931                 document.getElementById("smtp_auth1").style.display = smtpauth_req.checked ? "" : "none";
932                 document.getElementById("smtp_auth2").style.display = smtpauth_req.checked ? "" : "none";
933         },
934
935     /**
936      * Changes the display used in the outbound email SMTP dialog to match the
937      */
938     changeEmailScreenDisplay : function(smtptype, isSystemAccount)
939     {
940         document.getElementById("smtpButtonGroupTD").style.display = '';
941         document.getElementById("chooseEmailProviderTD").style.display = '';
942         document.getElementById("mailsettings1").style.display = '';
943         document.getElementById("mailsettings2").style.display = '';
944         document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_MAIL_SMTPPASS;
945         document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_MAIL_SMTPPORT;
946         document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_MAIL_SMTPSERVER;
947         document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_MAIL_SMTPUSER;
948
949         switch (smtptype) {
950         case "yahoomail":
951             document.getElementById("mail_smtpserver").value = 'plus.smtp.mail.yahoo.com';
952             document.getElementById("mail_smtpport").value = '465';
953             document.getElementById("mail_smtpauth_req").checked = true;
954             var ssl = document.getElementById("mail_smtpssl");
955             for(var j=0;j<ssl.options.length;j++) {
956                 if(ssl.options[j].text == 'SSL') {
957                     ssl.options[j].selected = true;
958                     break;
959                 }
960             }
961             document.getElementById("mailsettings1").style.display = 'none';
962             document.getElementById("mailsettings2").style.display = 'none';
963             document.getElementById("mail_smtppass_label").innerHTML =
964             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPPASS;
965             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_YAHOOMAIL_SMTPUSER;
966             break;
967         case "gmail":
968             document.getElementById("mail_smtpserver").value = 'smtp.gmail.com';
969             document.getElementById("mail_smtpport").value = '587';
970             document.getElementById("mail_smtpauth_req").checked = true;
971             var ssl = document.getElementById("mail_smtpssl");
972             for(var j=0;j<ssl.options.length;j++) {
973                 if(ssl.options[j].text == 'TLS') {
974                     ssl.options[j].selected = true;
975                     break;
976                 }
977             }
978             document.getElementById("mailsettings1").style.display = 'none';
979             document.getElementById("mailsettings2").style.display = 'none';
980             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_GMAIL_SMTPPASS;
981             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_GMAIL_SMTPUSER;
982             break;
983         case "exchange":
984             if ( document.getElementById("mail_smtpserver").value == 'plus.smtp.mail.yahoo.com'
985                     || document.getElementById("mail_smtpserver").value == 'smtp.gmail.com' ) {
986                 document.getElementById("mail_smtpserver").value = '';
987             }
988             document.getElementById("mail_smtpport").value = '25';
989             document.getElementById("mail_smtpauth_req").checked = true;
990             document.getElementById("mailsettings1").style.display = '';
991             document.getElementById("mailsettings2").style.display = '';
992             document.getElementById("mail_smtppass_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPASS;
993             document.getElementById("mail_smtpport_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPPORT;
994             document.getElementById("mail_smtpserver_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPSERVER;
995             document.getElementById("mail_smtpuser_label").innerHTML = mod_strings.LBL_EXCHANGE_SMTPUSER;
996             break;
997         }
998         if ( (typeof isSystemAccount != 'undefined') && isSystemAccount )
999         {
1000             document.getElementById("smtpButtonGroupTD").style.display = 'none';
1001             document.getElementById("chooseEmailProviderTD").style.display = 'none';
1002             document.getElementById("mailsettings2").style.display = 'none';
1003         }
1004
1005         SUGAR.email2.accounts.smtp_authenticate_field_display();
1006     },
1007
1008     /**
1009     * Fill the gmail default values for inbound accounts.
1010     */
1011     fillInboundGmailDefaults: function () {
1012
1013         document.forms['ieAccount'].elements['server_url'].value = "imap.gmail.com";
1014         document.forms['ieAccount'].elements['ssl'].checked = true;
1015         document.forms['ieAccount'].elements['protocol'].value = "imap";
1016         SUGAR.email2.accounts.setPortDefault();
1017         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1018     },
1019     /**
1020      * Sets Port field to selected protocol and SSL settings defaults
1021      */
1022     setPortDefault : function() {
1023         var prot = document.getElementById('protocol');
1024         var ssl  = document.getElementById('ssl');
1025         var port = document.getElementById('port');
1026         var stdPorts= new Array("110", "143", "993", "995");
1027         var stdBool    = new Boolean(false);
1028         var mailboxdiv = document.getElementById("mailboxdiv");
1029         var trashFolderdiv = document.getElementById("trashFolderdiv");
1030         var sentFolderdiv = document.getElementById("sentFolderdiv");
1031                 var monitoredFolder = document.getElementById("subscribeFolderButton");
1032         if(port.value == '') {
1033             stdBool.value = true;
1034         } else {
1035             for(i=0; i<stdPorts.length; i++) {
1036                 if(stdPorts[i] == port.value) {
1037                     stdBool.value = true;
1038                 }
1039             }
1040         }
1041
1042         if(stdBool.value == true) {
1043             if(prot.value == 'imap' && ssl.checked == false) { // IMAP
1044                 port.value = "143";
1045             } else if(prot.value == 'imap' && ssl.checked == true) { // IMAP-SSL
1046                 port.value = '993';
1047             } else if(prot.value == 'pop3' && ssl.checked == false) { // POP3
1048                 port.value = '110';
1049             } else if(prot.value == 'pop3' && ssl.checked == true) { // POP3-SSL
1050                 port.value = '995';
1051             }
1052         }
1053
1054         if (prot.value == 'imap') {
1055                 mailboxdiv.style.display = "";
1056                 trashFolderdiv.style.display = "";
1057                 sentFolderdiv.style.display = "";
1058                 monitoredFolder.style.display = "";
1059                 if (document.getElementById('mailbox').value == "") {
1060                         document.getElementById('mailbox').value = "INBOX";
1061                 }
1062         } else {
1063                 mailboxdiv.style.display = "none";
1064                 trashFolderdiv.style.display = "none";
1065                 sentFolderdiv.style.display = "none";
1066                         monitoredFolder.style.display = "none";
1067                 document.getElementById('mailbox').value = "";
1068         } // else
1069     },
1070
1071     /**
1072      * Draws/removes red boxes around required fields.
1073      */
1074     ieAccountError : function(style) {
1075         document.getElementById('server_url').className = style;
1076         document.getElementById('email_user').className = style;
1077         document.getElementById('email_password').className = style;
1078         document.getElementById('protocol').className = style;
1079         document.getElementById('port').className = style;
1080     },
1081
1082     checkOutBoundSelection: function() {
1083         var select = Dom.get('outbound_email');
1084         if (!select || select.selectedIndex == -1) { return; }
1085
1086         var v = select.options[select.selectedIndex].value;
1087
1088         if(v == '')
1089         {
1090                 select.options[select.selectedIndex].selected = false;
1091                 v = select.options[0].value;
1092         }
1093         else if (v == 'SYSTEM_ADD')
1094                 SUGAR.email2.accounts.showAddSmtp();
1095
1096         var foundError = false;
1097         var errorAccounts = SUGAR.email2.composeLayout.outboundAccountErrors;
1098                 for(i in errorAccounts)
1099                 {
1100                     if(v == i)
1101                     {
1102                         foundError = true;
1103                         break;
1104                     }
1105                 }
1106
1107                 //Should username/password fields for outbound account.
1108                 if(foundError)
1109                     this.toggleInboundOutboundFields(true);
1110                 else
1111                     this.toggleInboundOutboundFields(false);
1112
1113
1114
1115     },
1116     toggleInboundOutboundFields : function (display)
1117     {
1118         if(display)
1119         {
1120             Dom.removeClass("inboundAccountRequiredUsername", "yui-hidden");
1121                     Dom.removeClass("inboundAccountRequiredPassword", "yui-hidden");
1122         }
1123         else
1124         {
1125             Dom.addClass("inboundAccountRequiredUsername", "yui-hidden");
1126                     Dom.addClass("inboundAccountRequiredPassword", "yui-hidden");
1127         }
1128     },
1129     /**
1130      * rebuilds the select options for mailer options
1131      */
1132     rebuildMailerOptions : function() {
1133         var select = document.forms['ieAccount'].elements['outbound_email'];
1134         SE.util.emptySelectOptions(select);
1135
1136         //Get the available sugar mailers
1137         var a_outbound = SE.accounts.outboundAccountsSettingsTable.getRecordSet().getRecords();
1138
1139         for(i=0;i<a_outbound.length;i++)
1140         {
1141                 var t_record = a_outbound[i];
1142                 var key = t_record.getData('id');
1143                 var display = t_record.getData('name') + ' - ' + t_record.getData('mail_smtpserver');
1144
1145                 var opt = new Option(display, key);
1146                 select.options.add(opt);
1147                 if (key == SE.accounts.newAddedOutboundId) {
1148                         select.options.selectedIndex = i;
1149                 }
1150         }
1151
1152         select.options.add(new Option('',''));
1153         select.options.add(new Option(mod_strings.LBL_ADD_OUTBOUND_ACCOUNT,'SYSTEM_ADD'));
1154         //Hide/Show username password fields if necessary.
1155         SE.accounts.checkOutBoundSelection();
1156     },
1157     /**
1158      * Empties all the fields in the accounts edit view
1159      */
1160     clearInboundAccountEditScreen:function() {
1161
1162         document.getElementById('ie_id').value = '';
1163         document.getElementById('ie_name').value = '';
1164         document.getElementById('ie_from_name').value = SE.userPrefs.current_user.full_name;
1165         document.getElementById('ie_from_addr').value = this.getReplyAddress();
1166         document.getElementById('reply_to_addr').value = '';
1167         document.getElementById('server_url').value = '';
1168         document.getElementById('email_user').value = '';
1169         document.getElementById('email_password').value = '';
1170         document.getElementById('port').value = '';
1171         document.getElementById('inbound_mail_smtpuser').value = '';
1172         document.getElementById('inbound_mail_smtppass').value = '';
1173         document.ieAccount.protocol.options[0].selected = true;
1174         // handle SSL
1175         document.getElementById('ssl').checked = false;
1176         SUGAR.util.setEmailPasswordDisplay('email_password', false);
1177     },
1178
1179     /**
1180      * Populates an account's fields in Settings->Accounts
1181      */
1182     fillIeAccount:function(jsonstr) {
1183         var o = JSON.parse(jsonstr);
1184
1185         document.getElementById('ie_id').value = o.id;
1186         document.getElementById('ie_name').value = o.name;
1187         if (o.stored_options != null) {
1188                 document.getElementById('ie_from_name').value = o.stored_options.from_name == 'undefined' ? '' : o.stored_options.from_name;
1189                 document.getElementById('ie_from_addr').value = o.stored_options.from_addr == 'undefined' ? '' : o.stored_options.from_addr;
1190                 document.getElementById('reply_to_addr').value = typeof(o.stored_options.reply_to_addr) == 'undefined' ? '' : o.stored_options.reply_to_addr;
1191                 if (o.stored_options.trashFolder != null) {
1192                         document.getElementById('trashFolder').value = o.stored_options.trashFolder;
1193                 }
1194                 if (o.stored_options.sentFolder != null) {
1195                         document.getElementById('sentFolder').value = o.stored_options.sentFolder;
1196                 }
1197         }
1198         document.getElementById('server_url').value = o.server_url;
1199         document.getElementById('email_user').value = o.email_user;
1200         document.getElementById('port').value = o.port;
1201         document.getElementById('group_id').value = o.group_id;
1202         document.getElementById('mailbox').value = o.mailbox;
1203
1204
1205         var i = 0;
1206
1207         // handle SSL
1208         if(typeof(o.service[2]) != 'undefined') {
1209             document.getElementById('ssl').checked = true;
1210         }
1211
1212         // handle protocol
1213         if(document.getElementById('protocol').value != o.protocol) {
1214             var prot = document.getElementById('protocol');
1215             for(i=0; i<prot.options.length; i++) {
1216                 if(prot.options[i].value == o.service[3]) {
1217                     prot.options[i].selected = true;
1218                     this.setPortDefault();
1219                 }
1220             }
1221         }
1222  // handle SMTP selection
1223         if(o.stored_options != null && typeof(o.stored_options.outbound_email) != 'undefined') {
1224             var opts = document.getElementById('outbound_email').options;
1225             for(i=0; i<opts.length; i++) {
1226                 if(opts[i].value == o.stored_options.outbound_email) {
1227                     opts[i].selected = true;
1228                 }
1229             }
1230         }
1231     },
1232
1233     deleteIeAccount : function(IeAccountID,IeGroupID) {
1234         if(confirm(app_strings.LBL_EMAIL_IE_DELETE_CONFIRM))
1235         {
1236             overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
1237
1238             AjaxObject.target = 'frameFlex';
1239             AjaxObject.startRequest(callbackAccountDelete, urlStandard + '&emailUIAction=deleteIeAccount&ie_id='+IeAccountID+'&group_id='+IeGroupID);
1240             SUGAR.email2.accounts.refreshInboundAccountTable();
1241          }
1242      },
1243
1244        // Null check for Outbound Settings.
1245     checkOutboundSettings: function() {
1246         var errorMessage = '';
1247         var isError = false;
1248         if (typeof document.forms['outboundEmailForm'] != 'undefined') {
1249             var mailName = document.getElementById('mail_name').value;
1250             var smtpServer = document.getElementById('mail_smtpserver').value;
1251             var smtpPort = document.getElementById('mail_smtpport').value;
1252
1253             var mailsmtpauthreq = document.getElementById('mail_smtpauth_req');
1254             if(trim(mailName) == '') {
1255                 isError = true;
1256                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_NAME + "<br/>";
1257             }
1258             if(trim(smtpServer) == '') {
1259                 isError = true;
1260                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPSERVER + "<br/>";
1261             }
1262             if(trim(smtpPort) == '') {
1263                 isError = true;
1264                 errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPPORT + "<br/>";
1265             }
1266             if(mailsmtpauthreq.checked) {
1267                 if(trim(document.getElementById('mail_smtpuser').value) == '') {
1268                     isError = true;
1269                     errorMessage += app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER + "<br/>";
1270                 }
1271             }
1272         }
1273         if(isError) {
1274             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1275             return false;
1276         } else {
1277             return true;
1278         }
1279     },
1280
1281     testOutboundSettings: function() {
1282         var errorMessage = '';
1283         var isError = false;
1284         var fromAddress = document.getElementById("outboundtest_from_address").value;
1285         if (trim(fromAddress) == "") {
1286             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1287             overlay(mod_strings.ERR_MISSING_REQUIRED_FIELDS, errorMessage, 'alert');
1288             return false;
1289
1290         }
1291         else if (!isValidEmail(fromAddress)) {
1292             errorMessage += app_strings.LBL_EMAIL_SETTINGS_FROM_TO_EMAIL_ADDR + "<br/>";
1293             overlay(mod_strings.ERR_INVALID_REQUIRED_FIELDS, errorMessage, 'alert');
1294             return false;
1295         }
1296
1297         //Hide the dialogue and show an in progress indicator.
1298         SE.accounts.testOutboundDialog.hide();
1299         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT, 'plain');
1300
1301         //If the outbound mail type is a system override we need to re-enable the post fields otherwise
1302         //nothing is sent in the request.
1303         var outboundType = document.forms['outboundEmailForm'].elements['type'].value;
1304         SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1305
1306         YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1307         if(outboundType == 'system-override')
1308             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
1309
1310         var data = "&emailUIAction=testOutbound&outboundtest_from_address=" +  fromAddress;
1311         AjaxObject.startRequest(callbackOutboundTest, urlStandard + data);
1312
1313     },
1314
1315     testOutboundSettingsDialog: function() {
1316         //Ensure that all settings are correct before proceeding to send test email.
1317         if(!SE.accounts.checkOutboundSettings())
1318             return;
1319
1320         // lazy load dialogue
1321         if(!SE.accounts.testOutboundDialog) {
1322                 SE.accounts.testOutboundDialog = new YAHOO.widget.Dialog("testOutboundDialog", {
1323                 modal:true,
1324                                 visible:true,
1325                 fixedcenter:true,
1326                 constraintoviewport: true,
1327                 width   : 600,
1328                 shadow  : true
1329             });
1330             SE.accounts.testOutboundDialog.setHeader(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS);
1331             Dom.removeClass("testOutboundDialog", "yui-hidden");
1332         } // end lazy load
1333         SE.accounts.testOutboundDialog.render();
1334         SE.accounts.testOutboundDialog.show();
1335     },
1336
1337     /**
1338      * Saves Outbound email settings
1339      */
1340     saveOutboundSettings : function() {
1341         if(SE.accounts.checkOutboundSettings()) {
1342             //Enable the form fields for the post.
1343             SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
1344             YAHOO.util.Connect.setForm(document.getElementById("outboundEmailForm"));
1345             AjaxObject.startRequest(callbackOutboundSave, urlStandard + "&emailUIAction=saveOutbound");
1346         } else {
1347             return false;
1348         }
1349     },
1350
1351     saveIeAccount : function() {
1352
1353         //Before saving check if there are any error messages associated with the outbound account.
1354         var outboundID = document.getElementById('outbound_email').value;
1355
1356         if( SE.accounts.checkIeCreds({'valiateTrash': true,'validateFromAddr': true,'validateOutbound' :true,
1357             'validateSMTPCreds':true}) )
1358         {
1359             document.getElementById('saveButton').disabled = true;
1360
1361             overlay(app_strings.LBL_EMAIL_IE_SAVE, app_strings.LBL_EMAIL_ONE_MOMENT);
1362
1363             var formObject = document.getElementById('ieAccount');
1364             YAHOO.util.Connect.setForm(formObject);
1365
1366             AjaxObject._reset();
1367             AjaxObject.target = 'frameFlex';
1368             AjaxObject.startRequest(callbackAccount, urlStandard + '&emailUIAction=saveIeAccount');
1369         }
1370     },
1371
1372     testSettings : function() {
1373         form = document.getElementById('ieAccount');
1374
1375         if(SE.accounts.checkIeCreds()) {
1376             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);
1377         }
1378     },
1379
1380     getFoldersListForInboundAccountForEmail2 : function() {
1381         form = document.getElementById('ieAccount');
1382         if(SE.accounts.checkIeCreds()) {
1383                 var mailBoxValue = form.mailbox.value;
1384                 if (form.searchField.value.length > 0) {
1385                         mailBoxValue = "";
1386                 } // if
1387             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 );
1388         } // if
1389
1390     },
1391
1392     checkIeCreds : function(validateRules) {
1393         if(typeof(validateRules) == 'undefined')
1394             validateRules = {};
1395
1396         var errors = new Array();
1397         var out = new String();
1398
1399         var ie_name = Dom.get('ie_name').value;
1400         var fromAddress = Dom.get('ie_from_addr').value;
1401         var server_url = Dom.get('server_url').value;
1402         var email_user = Dom.get('email_user').value;
1403         var email_password = Dom.get('email_password').value;
1404         var protocol = Dom.get('protocol').value;
1405         var port = Dom.get('port').value;
1406         var oe = Dom.get('outbound_email');
1407         var oe_value = typeof(oe.options[oe.selectedIndex]) == 'undefined' ? "" : oe.options[oe.selectedIndex].value;
1408
1409         var outboundUserName = Dom.get('inbound_mail_smtpuser').value;
1410         var outboundPass = Dom.get('inbound_mail_smtppass').value;
1411
1412         //If the username and password were provided then ignore the error messge
1413
1414         var outboundCredentialsFound = false;
1415
1416         if(outboundUserName != "" && outboundPass != "")
1417             outboundCredentialsFound = true;
1418
1419         var validateSMTPCreds = (typeof(validateRules.validateSMTPCreds) != 'undefined' && validateRules.validateSMTPCreds);
1420
1421         if ( SE.composeLayout.outboundAccountErrors != null && SE.composeLayout.outboundAccountErrors[oe_value] != null
1422              && validateSMTPCreds)
1423         {
1424             if(trim(outboundUserName) == "") {
1425                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPUSER);
1426             }
1427             if(trim(outboundPass) == "") {
1428                 errors.push(app_strings.LBL_EMAIL_ACCOUNTS_SMTPPASS);
1429             }
1430         }
1431
1432         if(trim(ie_name) == "") {
1433             errors.push(app_strings.LBL_EMAIL_ERROR_NAME);
1434         }
1435
1436         if ( typeof(validateRules.validateFromAddr) != 'undefined' && validateRules.validateFromAddr)
1437         {
1438             if(trim(fromAddress) == "" || !isValidEmail(fromAddress) ) {
1439                 errors.push(app_strings.LBL_EMAIL_ERROR_FROM_ADDRESS);
1440             }
1441         }
1442
1443
1444         if( (typeof(validateRules.validateOutbound) != 'undefined' && validateRules.validateOutbound) && ( trim(oe_value) == ""
1445              || trim(oe_value) == "SYSTEM_ADD") ) {
1446             errors.push(app_strings.LBL_EMAIL_ERROR_NO_OUTBOUND);
1447         }
1448         if(trim(server_url) == "") {
1449             errors.push(app_strings.LBL_EMAIL_ERROR_SERVER);
1450         }
1451         if(trim(email_user) == "") {
1452             errors.push(app_strings.LBL_EMAIL_ERROR_USER);
1453         }
1454         if(protocol == "") {
1455             errors.push(app_strings.LBL_EMAIL_ERROR_PROTOCOL);
1456         }
1457         if (protocol == 'imap') {
1458                 var mailbox = document.getElementById('mailbox').value;
1459                 if (trim(mailbox) == "") {
1460                         errors.push(app_strings.LBL_EMAIL_ERROR_MONITORED_FOLDER);
1461                 } // if
1462                 if (typeof(validateRules.valiateTrash) != 'undefined' && validateRules.valiateTrash) {
1463                         var trashFolder = document.getElementById('trashFolder').value;
1464                         if (trim(trashFolder) == "") {
1465                                 errors.push(app_strings.LBL_EMAIL_ERROR_TRASH_FOLDER);
1466                         } // if
1467                         } // if
1468         }
1469         if(port == "") {
1470             errors.push(app_strings.LBL_EMAIL_ERROR_PORT);
1471         }
1472
1473         if(errors.length > 0) {
1474             out = app_strings.LBL_EMAIL_ERROR_DESC;
1475             for(i=0; i<errors.length; i++) {
1476                 if(out != "") {
1477                     out += "\n";
1478                 }
1479                 out += errors[i];
1480             }
1481
1482             alert(out);
1483             return false;
1484         } else {
1485
1486             return true;
1487         }
1488     },
1489
1490     getIeAccount : function(ieId) {
1491         if(ieId == '')
1492             return;
1493
1494         overlay(app_strings.LBL_EMAIL_SETTINGS_RETRIEVING_ACCOUNT, app_strings.LBL_EMAIL_ONE_MOMENT);
1495                 var query = "&emailUIAction=getIeAccount&ieId=" + ieId;
1496
1497         AjaxObject.startRequest(callbackIeAccountRetrieve, urlStandard + query);
1498     },
1499
1500     /**
1501      * Iterates through TreeView nodes to apply styles dependent nature of node
1502      */
1503     renderTree:function() {
1504         SE.util.cascadeNodes(SE.tree.getRoot(), SE.accounts.setNodeStyle);
1505         SE.tree.render();
1506     },
1507
1508     //Sets the style for any nodes that need it.
1509     setNodeStyle : function(node) {
1510         if (!node.data.origText) {
1511             node.data.origText = node.data.text;
1512         }
1513         //Set unread
1514         if (typeof(node.data.unseen) != 'undefined') {
1515                 if (node.data.unseen > 0) {
1516                                 node.setUpLabel('<b>' + node.data.origText + '(' + node.data.unseen + ')<b>');
1517                         }
1518                         else {
1519                                 node.setUpLabel(node.data.origText);
1520                         }
1521         } else {
1522                 node.setUpLabel('<span>' + node.data.origText + '</span>');
1523         }
1524         SE.accounts.setupDDTarget(node);
1525     },
1526
1527     setupDDTarget : function(node) {
1528         if (node.ddTarget) {
1529                 node.ddTarget.removeFromGroup();
1530                 delete node.ddTarget;
1531         }
1532         var id = node.getElId();
1533         var num = id.substring(4);
1534         if (node.data.origText != SUGAR.language.get("Emails", "LNK_MY_INBOX") &&
1535                         node.data.origText != SUGAR.language.get("Emails", "LNK_MY_DRAFTS") &&
1536                         node.data.origText != SUGAR.language.get("Emails", "LNK_SENT_EMAIL_LIST")) {
1537
1538                 node.ddTarget = new SUGAR.email2.folders.folderDD("ygtvcontentel" + num);
1539         }
1540         else if (node.data.origText == SUGAR.language.get("Emails", "LNK_MY_INBOX")){
1541                 node.ddTarget = new YAHOO.util.DDTarget("ygtvcontentel" + num);
1542         }
1543     },
1544
1545     /**
1546      * Async call to rebuild the folder list.  After a folder delete or account delete
1547      */
1548     rebuildFolderList : function() {
1549         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
1550         AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=rebuildFolders');
1551     },
1552
1553     /**
1554      * Returns the number of remote accounts the user has active.
1555      */
1556     getAccountCount : function() {
1557         var tree = SE.tree;
1558         var count = 0;
1559         for(i=0; i<tree._nodes.length; i++) {
1560             var node = tree._nodes[i];
1561
1562             if(typeof(node) != 'undefined' && node.data.ieId) {
1563                 count++;
1564             }
1565         }
1566         return count;
1567     }
1568 };
1569 ////    END ACCOUNTS
1570 ///////////////////////////////////////////////////////////////////////////////
1571
1572
1573
1574
1575 ///////////////////////////////////////////////////////////////////////////////
1576 ////    CONTEXT MENU CALLS
1577 SE.contextMenus = {
1578
1579     assignToDialogue : null,
1580     /**
1581      * Archives from context menu
1582      * @param Array uids
1583      * @param string ieId
1584      * @param string folder
1585      */
1586     _archiveToSugar : function(uids, ieId, folder) {
1587         var ser = '';
1588
1589         for(var i=0; i<uids.length; i++) { // using 1 index b/c getSelectedRowIds doubles the first row's id
1590             if(ser != "") ser += app_strings.LBL_EMAIL_DELIMITER;
1591             ser += uids[i];
1592         }
1593         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1594     },
1595
1596     /**
1597      * Archives from context menu
1598      */
1599     archiveToSugar : function(menuItem) {
1600         SE.contextMenus.emailListContextMenu.hide();
1601
1602         var rows = SE.grid.getSelectedRows();
1603         var uids = [];
1604         /* iterate through available rows JIC a row is deleted - use first available */
1605         for(var i=0; i<rows.length; i++) {
1606             uids[i] = SE.grid.getRecord(rows[0]).getData().uid;
1607         }
1608         var data = SE.grid.getRecord(rows[0]).getData();
1609         SE.contextMenus._archiveToSugar(uids, data.ieId, data.mbox);
1610     },
1611
1612     /**
1613      * Popup the printable version and start system's print function.
1614      */
1615     viewPrintable : function(menuItem) {
1616         var rows = SE.grid.getSelectedRows();
1617         var data = SE.grid.getRecord(rows[0]).getData();
1618         SE.detailView.viewPrintable(data.ieId, data.uid, data.mbox);
1619     },
1620
1621     /**
1622      * Marks email flagged on mail server
1623      */
1624     markRead : function(type, contextMenuId) {
1625         SE.contextMenus.markEmail('read');
1626     },
1627
1628     /**
1629      * Assign this emails to people based on assignment rules
1630      */
1631     assignEmailsTo : function(type, contextMenuId) {
1632         if(!SE.contextMenus.assignToDialogue)
1633         {
1634                 SE.contextMenus.assignToDialogue = new YAHOO.widget.Dialog("assignToDiv", {
1635                 modal:true,
1636                                 visible:false,
1637                 fixedcenter:true,
1638                 constraintoviewport: true,
1639                 width   : "600px",
1640                 shadow  : true
1641             });
1642             SE.contextMenus.assignToDialogue.setHeader(app_strings.LBL_EMAIL_ASSIGN_TO);
1643             enableQS(true);
1644         }
1645
1646         Dom.removeClass("assignToDiv", "yui-hidden");
1647         SE.contextMenus.assignToDialogue.render();
1648         SE.contextMenus.assignToDialogue.show();
1649     },
1650
1651     /**
1652      * Marks email flagged on mail server
1653      */
1654     markFlagged : function(contextMenuId) {
1655         SE.contextMenus.markEmail('flagged');
1656     },
1657
1658     /**
1659      * Marks email unflagged on mail server
1660      */
1661     markUnflagged : function(contextMenuId) {
1662         SE.contextMenus.markEmail('unflagged');
1663     },
1664
1665     /**
1666      * Marks email unread on mail server
1667      */
1668     markUnread : function() {
1669         SE.contextMenus.markEmail('unread');
1670     },
1671
1672     /**
1673      * Deletes an email from context menu
1674      */
1675     markDeleted : function() {
1676         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
1677                 document.getElementById('_blank').innerHTML = "";
1678                 SE.contextMenus.markEmail('deleted');
1679         }
1680     },
1681
1682     /**
1683      * generic call API to apply a flag to emails on the server and on sugar
1684      * @param string type "read" | "unread" | "flagged" | "deleted"
1685      */
1686     markEmail : function(type) {
1687         SE.contextMenus.emailListContextMenu.hide();
1688
1689         //var dm = SE.grid.getStore();
1690         //var uids = SE.grid.getSelectedRowIds();
1691         //var indexes = SE.grid.getSelectedRowIndexes();
1692         var rows = SE.grid.getSelectedRows();
1693         if (rows.length == 0)
1694                 rows = [SE.contextMenus.currentRow];
1695         var ser = [ ];
1696
1697         for(var i=0; i<rows.length; i++) {
1698             ser.push(SE.grid.getRecord(rows[i]).getData().uid);
1699         }
1700
1701         ser = YAHOO.lang.JSON.stringify(ser);
1702
1703         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1704         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1705
1706
1707         var count = 0;
1708
1709
1710         if(type == 'read' || type == 'deleted') {
1711             // mark read
1712             for(var j=0; j<rows.length; j++) {
1713                 if(SE.grid.getRecord(rows[j]).getData().seen == '0') {
1714                     count = count + 1;
1715                     SE.grid.getRecord(rows[j]).setData("seen", "1");
1716                 }
1717             }
1718            //bug# 40257 - adding if condition to check the ieId (Id of a sugar mail box) , which would be null for search email results
1719             if(ieId){
1720             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1721             var unseenCount = node.data.unseen;
1722             if (isNaN(unseenCount)) {
1723                 unseenCount = 0;
1724             }
1725             var finalCount = parseInt(unseenCount) - count;
1726             node.data.unseen = finalCount;
1727
1728             SE.accounts.renderTree();
1729             }
1730         } else if(type == 'unread') {
1731             // mark unread
1732             for(var j=0; j<rows.length; j++) {
1733                 if(SE.grid.getRecord(rows[j]).getData().seen == '1') { // index [9] is the seen flag
1734                     count = count + 1;
1735                 }
1736             }
1737
1738             var node = SE.folders.getNodeFromIeIdAndMailbox(ieId, folder);
1739             var unseenCount = node.data.unseen;
1740             if (isNaN(unseenCount)) {
1741                 unseenCount = 0;
1742             }
1743             var finalCount = parseInt(unseenCount) + count;
1744             node.data.unseen = finalCount;
1745             SE.accounts.renderTree();
1746         }
1747
1748         if (type == 'unread') {
1749                 for(var i=0; i<rows.length; i++) {
1750                     SE.cache[folder + SE.grid.getRecord(rows[i]).getData().uid] = null;
1751                 } // for
1752         }
1753
1754                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
1755         AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=' + type + '&uids=' + ser + "&ieId=" + ieId + "&folder=" + folder);
1756     },
1757
1758     /**
1759      * refreshes the ListView to show changes to cache
1760      */
1761     markEmailCleanup : function() {
1762         SE.accounts.renderTree();
1763         hideOverlay();
1764         SE.listView.refreshGrid();
1765     },
1766
1767         showAssignmentDialog : function() {
1768                 if (SE.contextMenus.assignmentDialog == null) {
1769                         AjaxObject.startRequest(callbackAssignmentDialog, urlStandard + '&emailUIAction=getAssignmentDialogContent');
1770                 } else {
1771                         SE.contextMenus.assignmentDialog.show();
1772                 } // else
1773         },
1774
1775         /**
1776      * shows the import dialog with only relate visible.
1777      */
1778     relateTo : function() {
1779         SE.contextMenus.emailListContextMenu.hide();
1780
1781         var rows = SE.grid.getSelectedRows();
1782         var data = SE.grid.getRecord(rows[0]).getData();
1783         var ieId = data.ieId;
1784         var folder = data.mbox;
1785         var uids = [];
1786         /* iterate through available rows JIC a row is deleted - use first available */
1787         for(var i=0; i<rows.length; i++) {
1788             uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
1789         }
1790         var ser = JSON.stringifyNoSecurity(uids);
1791
1792         AjaxObject.startRequest(callbackRelateEmail, urlStandard + '&emailUIAction=getRelateForm&uid=' + ser + "&ieId=" + ieId + "&mbox=" + folder);
1793     },
1794
1795         /**
1796      * shows the import dialog with only relate visible.
1797      */
1798     showDetailView : function() {
1799         SE.contextMenus.emailListContextMenu.hide();
1800         var rows = SE.grid.getSelectedRows();
1801         if (rows.length > 1) {
1802                 alert(app_strings.LBL_EMAIL_SELECT_ONE_RECORD);
1803                 return;
1804         }
1805         var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1806         var folder = SE.grid.getRecord(rows[0]).getData().mbox;
1807         /* iterate through available rows JIC a row is deleted - use first available */
1808         var uid = SE.grid.getRecord(rows[0]).getData().uid;
1809         SE.contextMenus.showEmailDetailViewInPopup(ieId, uid, folder);
1810     },
1811
1812     /**
1813      *
1814      */
1815     showEmailDetailViewInPopup : function(ieId,uid, folder) {
1816         overlay(app_strings.LBL_EMAIL_RETRIEVING_RECORD, app_strings.LBL_EMAIL_ONE_MOMENT);
1817         AjaxObject.startRequest(callbackEmailDetailView, urlStandard + '&emailUIAction=getEmail2DetailView&uid=' + uid + "&ieId=" + ieId + "&mbox=" + folder + "&record=" + uid);
1818     },
1819
1820     /**
1821      * Opens multiple messages from ListView context click
1822      */
1823     openMultiple : function() {
1824         SE.contextMenus.emailListContextMenu.hide();
1825
1826         var rows = SE.grid.getSelectedRows();
1827         var uids = SE.listView.getUidsFromSelection();
1828
1829         if(uids.length > 0) {
1830             var mbox = SE.grid.getRecord(rows[0]).getData().mbox;
1831             var ieId = SE.grid.getRecord(rows[0]).getData().ieId;
1832             SE.detailView.populateDetailViewMultiple(uids, mbox, ieId, true);
1833         }
1834     },
1835
1836     /**
1837      * Replies/forwards email
1838      */
1839     replyForwardEmailContext : function() {
1840         SE.contextMenus.emailListContextMenu.hide();
1841
1842         var indexes = SE.grid.getSelectedRows();
1843         //var dm = SE.grid.getDataModel();
1844         var type = this.id;
1845
1846         for(var i=0; i<indexes.length; i++) {
1847             var row = SE.grid.getRecord(indexes[i]).getData();
1848             SE.composeLayout.c0_replyForwardEmail(row.ieId, row.uid, row.mbox, type);
1849         }
1850     },
1851
1852     //show menu functions
1853     showEmailsListMenu : function(grid, row) {
1854
1855        var data = row.getData();
1856        var draft = (data.type == "draft");
1857        var menu = SE.contextMenus.emailListContextMenu;
1858        var folderNode;
1859
1860        if (SE.tree)
1861        {
1862                if (data.mbox == 'sugar::Emails')
1863                    folderNode = SE.folders.getNodeFromIeIdAndMailbox('folder', data.ieId);
1864                else
1865                    folderNode = SE.folders.getNodeFromIeIdAndMailbox(data.ieId, data.mbox);
1866
1867                if (  folderNode != null && typeof(folderNode) != "undefined"  && typeof(folderNode.data) != "undefined"
1868                    && ((folderNode.data.is_group != null) && (folderNode.data.is_group == 'true'))
1869                   ||  (folderNode != null && folderNode.data.isGroup != null && folderNode.data.isGroup == "true"))
1870                        menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false); //Assign emails item
1871                else
1872                    menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true); //Assign emails item
1873        }
1874        else
1875            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", true);
1876
1877        menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", draft);
1878        menu.getItem(menu.itemsMapping.reply).cfg.setProperty("disabled", draft);
1879        menu.getItem(menu.itemsMapping.replyAll).cfg.setProperty("disabled", draft);
1880        menu.getItem(menu.itemsMapping.forward).cfg.setProperty("disabled", draft);
1881        menu.getItem(menu.itemsMapping.mark).cfg.setProperty("disabled", draft);
1882
1883
1884        if (data.mbox == "sugar::Emails")
1885        {
1886            //Allow users to reassign imported emails
1887            menu.getItem(menu.itemsMapping.assignTo).cfg.setProperty("disabled", false);
1888            menu.getItem(menu.itemsMapping.archive).cfg.setProperty("disabled", true);
1889            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", false);
1890            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", false);
1891        }
1892        else
1893        {
1894            menu.getItem(menu.itemsMapping.viewRelationships).cfg.setProperty("disabled", true);
1895            menu.getItem(menu.itemsMapping.relateTo).cfg.setProperty("disabled", true);
1896        }
1897     },
1898
1899     showFolderMenu : function(grid, rowIndex, event) {
1900        event.stopEvent();
1901        var coords = event.getXY();
1902        SE.contextMenus.emailListContextMenu.showAt([coords[0], coords[1]]);
1903     }
1904 };
1905
1906 SE.contextMenus.dv = {
1907     archiveToSugar : function(contextMenuId) {
1908
1909         SE.contextMenus._archiveToSugar(uids, ieId, folder);
1910     },
1911
1912     replyForwardEmailContext : function(all) {
1913         SE.contextMenus.detailViewContextMenu.hide();
1914     }
1915
1916 };
1917
1918
1919
1920
1921
1922 ////    END SE.contextMenus
1923 ///////////////////////////////////////////////////////////////////////////////
1924
1925
1926
1927 ///////////////////////////////////////////////////////////////////////////////
1928 ////    DETAIL VIEW
1929 SE.detailView = {
1930     consumeMetaDetail : function(ret) {
1931         // handling if the Email drafts
1932         if(ret.type == 'draft') {
1933             SE.composeLayout.c0_composeDraft();
1934             return;
1935         }
1936
1937
1938         // cache contents browser-side
1939         SE._setDetailCache(ret);
1940
1941         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
1942         // 2 below must be in global context
1943         meta = ret.meta;
1944         meta['panelId'] = SE.util.getPanelId();
1945
1946         email = ret.meta.email;
1947         var out = displayTemplate.exec({
1948             'app_strings' : app_strings,
1949             'theme' : theme,
1950             'idx' : targetDiv.id,
1951             'meta' : meta,
1952             'email' : meta.email,
1953             'linkBeans' : linkBeans
1954         });
1955         var tabLabel = meta.email.name;
1956         if (tabLabel != null && tabLabel.length > 25) {
1957                 tabLabel = tabLabel.substring(0, 25) + "...";
1958         } // if
1959         targetDiv.set("label", tabLabel);
1960         targetDiv.set("content", out);
1961
1962         var displayEmailFrameDiv = document.getElementById('displayEmailFrameDiv' + targetDiv.id);
1963         if (SUGAR.email2.util.isIe()) {
1964                 displayEmailFrameDiv.style.height = "390px";
1965         } else {
1966                 displayEmailFrameDiv.style.height = "410px";
1967         }
1968
1969         var displayFrame = document.getElementById('displayEmailFrame' + targetDiv.id);
1970         displayFrame.contentWindow.document.write(email.description);
1971         displayFrame.contentWindow.document.close();
1972
1973         // hide archive links
1974         if(ret.meta.is_sugarEmail) {
1975                         document.getElementById("archiveEmail" + targetDiv.id).style.display = "none";
1976             document.getElementById("btnEmailView" + targetDiv.id).style.display = "none";
1977         } else {
1978             if (document.getElementById("showDeialViewForEmail" + targetDiv.id))
1979                 document.getElementById("showDeialViewForEmail" + targetDiv.id).style.display = "none";
1980         } // else
1981
1982     },
1983
1984     consumeMetaPreview : function(ret) {
1985         // cache contents browser-side
1986         SE._setDetailCache(ret);
1987
1988
1989
1990         var currrow = SE.grid.getLastSelectedRecord();
1991         currrow = SE.grid.getRecord(currrow);
1992         if (!currrow) {
1993             document.getElementById('_blank').innerHTML = '';
1994             return;
1995         }
1996         // handling if the Email drafts
1997         if(ret.type == 'draft'){
1998             if (currrow.getData().uid == ret.uid) {
1999                 SE.composeLayout.c0_composeDraft();
2000             }
2001             return;
2002         }
2003
2004         if (currrow.getData().uid != ret.meta.uid) {
2005            return;
2006         }
2007
2008         // remove loading sprite
2009         document.getElementById('_blank').innerHTML = '<iframe id="displayEmailFramePreview"/>';
2010         var displayTemplate = new YAHOO.SUGAR.Template(SE.templates['displayOneEmail']);
2011         meta = ret.meta;
2012         meta['panelId'] = SE.util.getPanelId();
2013         email = ret.meta.email;
2014
2015         document.getElementById('_blank').innerHTML = displayTemplate.exec({
2016             'app_strings' : app_strings,
2017             'theme' : theme,
2018             'idx' : 'Preview',
2019             'meta' : meta,
2020             'email' :meta.email,
2021             'linkBeans' : linkBeans
2022         });
2023        // document.getElementById('_blank').innerHTML = meta.email;
2024        /* displayTemplate.append('_blank', {
2025             'app_strings' : app_strings,
2026             'theme' : theme,
2027             'idx' : 'Preview',
2028             'meta' : meta,
2029             'email' :meta.email,
2030             'linkBeans' : linkBeans
2031         });*/
2032
2033         var displayFrame = document.getElementById('displayEmailFramePreview');
2034         displayFrame.contentWindow.document.write(email.description);
2035         displayFrame.contentWindow.document.close();
2036
2037         SE.listViewLayout.resizePreview();
2038
2039         // hide archive links
2040         if(ret.meta.is_sugarEmail) {
2041             document.getElementById("archiveEmailPreview").innerHTML = "&nbsp;";
2042             document.getElementById("btnEmailViewPreview").style.display = "none";
2043             document.getElementById("archiveEmail" + meta['panelId']).style.display = "none";
2044         } else {
2045           //hide view relationship link
2046                  document.getElementById("showDeialViewForEmail" + meta['panelId']).style.display = "none";
2047         }
2048     },
2049
2050     /**
2051      * wraps emailDelete() for single messages, comes from preview or tab
2052      */
2053     emailDeleteSingle : function(ieId, uid, mbox) {
2054         if(confirm(app_strings.LBL_EMAIL_DELETE_CONFIRM)) {
2055             // find active panel and close if the user double clicked the email to view.
2056             var activeTabId = SE.util.getPanelId();
2057             if(activeTabId != 'Preview')
2058                 SE.innerLayout.get("activeTab").close();
2059
2060             document.getElementById('_blank').innerHTML = "";
2061                 var ser = [ ];
2062                         ser.push(uid);
2063                 uid = JSON.stringifyNoSecurity(ser);
2064             this.emailDelete(ieId, uid, mbox);
2065         }
2066     },
2067
2068     /**
2069      * Sends async call to delete a given message
2070      * @param
2071      */
2072     emailDelete : function(ieId, uid, mbox) {
2073        overlay(app_strings.LBL_EMAIL_DELETING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2074        AjaxObject.startRequest(callbackContextmenus.markUnread, urlStandard + '&emailUIAction=markEmail&type=deleted&uids=' +
2075            uid + "&ieId=" + ieId + "&folder=" + mbox);
2076     },
2077
2078     /**
2079      * retrieves one email to display in the preview pane.
2080      */
2081     getEmailPreview : function() {
2082         var row = SUGAR.email2.listView.currentRow;
2083         var data = row.getData();
2084             if (data && !(SUGAR.email2.contextMenus.emailListContextMenu.cfg.getProperty("visible") && data.type =='draft')) {
2085                var setRead = (data['seen'] == 0) ? true : false;
2086                    SUGAR.email2.listView.markRead(SUGAR.email2.listView.currentRowIndex, row);
2087                    SUGAR.email2.detailView.populateDetailView(data['uid'], data['mbox'], data['ieId'], setRead, SUGAR.email2.previewLayout);
2088             }
2089     },
2090
2091     /**
2092      * Imports one email into Sugar
2093      */
2094     importEmail : function(ieId, uid, mbox) {
2095         SE.util.clearHiddenFieldValues('emailUIForm');
2096
2097         overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
2098
2099         var vars = "&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mbox;
2100         AjaxObject.target = '';
2101         AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=getImportForm' + vars);
2102     },
2103
2104     /**
2105      * Populates the frameFlex div with the contents of an email
2106      */
2107     populateDetailView : function(uid, mbox, ieId, setRead, destination) {
2108         SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
2109
2110         var mboxStr = new String(mbox);
2111         var compKey = mbox + uid;
2112
2113         if(setRead == true) {
2114                 SE.listView.boldUnreadRows()
2115                 SE.folders.decrementUnreadCount(ieId, mbox, 1);
2116         }
2117
2118         if(destination == SE.innerLayout) {
2119                 /*
2120              * loading email into a tab, peer with ListView
2121              * targetDiv must remain in the global namespace as it is used by AjaxObject
2122              */
2123                 //Check if we already have a tab of the email open
2124                 var tabs = SE.innerLayout.get("tabs");
2125                 for (var t in tabs) {
2126                         if (tabs[t].id && tabs[t].id == uid) {
2127                                 SE.innerLayout.set("activeTab", tabs[t]);
2128                                 return;
2129                         }
2130                 }
2131
2132                 targetDiv = new YAHOO.SUGAR.ClosableTab({
2133                                 label: loadingSprite,
2134                                         scroll : true,
2135                                         content : "",
2136                                         active : true
2137                 }, SE.innerLayout);
2138                 targetDiv.id = uid;
2139                 SE.innerLayout.addTab(targetDiv);
2140
2141             // use cache if available
2142             if(SE.cache[compKey]) {
2143                 SE.detailView.consumeMetaDetail(SE.cache[compKey]);
2144             } else {
2145                 // open email as peer-tab to listView
2146                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailDetail);
2147                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
2148             }
2149         } else {
2150             // loading email into preview pane
2151             document.getElementById('_blank').innerHTML = loadingSprite;
2152
2153             // use cache if available
2154             if(SE.cache[compKey]) {
2155                 SE.detailView.consumeMetaPreview(SE.cache[compKey]);
2156             } else {
2157                 AjaxObject.forceAbort = true;
2158                 // open in preview window
2159                 SE.detailView.requestEmailContents(mboxStr, uid, mbox, ieId, AjaxObject.detailView.callback.emailPreview);
2160                // AjaxObject.startRequest(AjaxObject.detailView.callback.emailPreview, null);
2161             }
2162         }
2163     },
2164
2165     requestEmailContents : function(mboxStr, uid, mbox, ieId, callback)
2166     {
2167         if(mboxStr.substring(0,7) == 'sugar::') {
2168             // display an email from Sugar
2169             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
2170         } else {
2171             // display an email from an email server
2172             document.getElementById('emailUIAction').value = 'getSingleMessage';
2173         }
2174         document.getElementById('mbox').value = mbox;
2175         document.getElementById('ieId').value = ieId;
2176         document.getElementById('uid').value = uid;
2177
2178         YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
2179
2180         AjaxObject.forceAbort = true;
2181         AjaxObject.target = '_blank';
2182         AjaxObject.startRequest(callback, null);
2183     },
2184
2185     /**
2186      * Retrieves multiple emails for DetailView
2187      */
2188     populateDetailViewMultiple : function(uids, mbox, ieId, setRead) {
2189         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
2190         SE.util.clearHiddenFieldValues('emailUIForm');
2191
2192         var mboxStr = new String(mbox);
2193
2194         uids = SE.util.cleanUids(uids);
2195
2196         if(mboxStr.substring(0,7) == 'sugar::') {
2197             // display an email from Sugar
2198             document.getElementById('emailUIAction').value = 'getMultipleMessagesFromSugar';
2199             document.getElementById('uid').value = uids;
2200         } else {
2201             // display an email from an email server
2202             document.getElementById('emailUIAction').value = 'getMultipleMessages';
2203             document.getElementById('mbox').value = mbox;
2204             document.getElementById('ieId').value = ieId;
2205             document.getElementById('uid').value = uids;
2206         }
2207
2208         var formObject = document.getElementById('emailUIForm');
2209         YAHOO.util.Connect.setForm(formObject);
2210
2211         AjaxObject.target = 'frameFlex';
2212         AjaxObject.startRequest(callbackEmailDetailMultiple, null);
2213
2214         if(setRead == true) {
2215             var c = uids.split(",");
2216             SE.folders.decrementUnreadCount(ieId, mbox, c.length);
2217         }
2218     },
2219
2220     /**
2221      * Makes async call to get QuickCreate form
2222      * Renders a modal edit view for a given module
2223      */
2224     quickCreate : function(module, ieId, uid, mailbox) {
2225         var get = "&qc_module=" + module + "&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2226
2227         if(ieId == null || ieId == "null" || mailbox == 'sugar::Emails') {
2228             get += "&sugarEmail=true";
2229         }
2230
2231         AjaxObject.startRequest(callbackQuickCreate, urlStandard + '&emailUIAction=getQuickCreateForm' + get);
2232     },
2233
2234     /**
2235      * Makes async call to save a quick create
2236      * @param bool
2237      */
2238     saveQuickCreate : function(action) {
2239         var qcd = SE.detailView.quickCreateDialog;
2240         if (check_form('form_EmailQCView_' + qcd.qcmodule)) {
2241                 var formObject = document.getElementById('form_EmailQCView_' + qcd.qcmodule);
2242                 var theCallback = callbackQuickCreateSave;
2243                 var accountType = '&sugarEmail=true';
2244                 if (qcd.ieId != 'null' && qcd.mbox != 'sugar::Emails') {
2245                    accountType = '&ieId=' + qcd.ieId;
2246                 }
2247
2248             if (action == 'reply') {
2249                    theCallback = callbackQuickCreateSaveAndReply;
2250                 } else if (action == true) {
2251                     theCallback = callbackQuickCreateSaveAndAddToAddressBook;
2252                 }
2253                 formObject.action.value = 'EmailUIAjax';
2254                 YAHOO.util.Connect.setForm(formObject);
2255                 overlay('Saving', app_strings.LBL_EMAIL_ONE_MOMENT);
2256                 AjaxObject.startRequest(theCallback, "to_pdf=true&emailUIAction=saveQuickCreate&qcmodule=" + qcd.qcmodule + '&uid=' + qcd.uid +
2257                                        accountType + '&mbox=' + qcd.mbox);
2258         }
2259     },
2260
2261     /**
2262      * Code to show/hide long list of email address in DetailView
2263      */
2264     showCroppedEmailList : function(el) {
2265         el.style.display = 'none';
2266         el.previousSibling.style.display = 'inline'
2267     },
2268     showFullEmailList : function(el) {
2269         el.style.display = 'none';
2270         el.nextSibling.style.display = 'inline';
2271     },
2272
2273     /**
2274      * Shows the QuickCreate overlay
2275      * @param string ieId
2276      * @param string uid
2277      * @param string mailbox
2278      */
2279     showQuickCreate : function(ieId, uid, mailbox) {
2280         var panelId = SE.util.getPanelId();
2281         var context = document.getElementById("quickCreateSpan" + panelId);
2282
2283         if (!SE.detailView.cqMenus)
2284                 SE.detailView.cqMenus = {};
2285
2286         if (SE.detailView.cqMenus[context])
2287                 SE.detailView.cqMenus[context].destroy();
2288
2289             var menu = SE.detailView.cqMenus[context] = new YAHOO.widget.Menu("qcMenuDiv" + panelId, {
2290                 lazyload:true,
2291                 context: ["quickCreateSpan" + panelId, "tr","br", ["beforeShow", "windowResize"]]
2292         });
2293
2294             for (var i=0; i < this.qcmodules.length; i++) {
2295             var module = this.qcmodules[i];
2296             menu.addItem({
2297                 text:   app_strings['LBL_EMAIL_QC_' + module.toUpperCase()],
2298                 modulename: module,
2299                 value: module,
2300                 onclick: { fn: function() {
2301                                 SE.detailView.quickCreate(this.value, ieId, uid, mailbox);
2302                         }
2303                 }
2304             });
2305         }
2306
2307                 menu.render(document.body);
2308                 menu.show();
2309     },
2310
2311     /**
2312      * Displays the "View" submenu in the detailView
2313      * @param string ieId
2314      * @param string uid
2315      * @param string mailbox
2316      */
2317     showViewMenu : function(ieId, uid, mailbox) {
2318         var panelId = SE.util.getPanelId();
2319         var context = "btnEmailView" + panelId;
2320         if (!SE.detailView.viewMenus)
2321                 SE.detailView.viewMenus = {};
2322
2323         if (SE.detailView.viewMenus[context])
2324                 SE.detailView.viewMenus[context].destroy();
2325
2326             var menu = SE.detailView.viewMenus[context] = new YAHOO.widget.Menu("menuDiv" + panelId, {
2327                 lazyload:true,
2328                 context: ["btnEmailView" + panelId, "tl","bl", ["beforeShow", "windowResize"]],
2329                 clicktohide: true
2330         });
2331                 menu.addItems(
2332                                 (ieId == 'null' || ieId == null) ?
2333                         //No ieId - Sugar Email
2334                         [{
2335                                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2336                                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);} }
2337             }]
2338                         :
2339                         //IeID exists, on a remote server
2340                         [{
2341                 text: app_strings.LBL_EMAIL_VIEW_HEADERS,
2342                 onclick: { fn: function() {SE.detailView.viewHeaders(ieId, uid, mailbox);}}
2343             },{
2344                 text: app_strings.LBL_EMAIL_VIEW_RAW,
2345                 onclick: { fn: function() {SE.detailView.viewRaw(ieId, uid, mailbox);}}
2346             }]
2347         );
2348                 menu.render(document.body);
2349                 menu.show();
2350
2351
2352         /*
2353         //#23108 jchi@07/17/2008
2354         menu.render('quickCreateSpan'+ panelId);*/
2355         //this.viewMenu = menu;
2356         //this.viewMenu.show(context);
2357     },
2358     /**
2359      * Makes async call to get an email's headers
2360      */
2361     viewHeaders : function(ieId, uid, mailbox) {
2362         var get = "&type=headers&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2363         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2364     },
2365
2366     /**
2367      * Makes async call to get a printable version
2368      */
2369     viewPrintable : function(ieId, uid, mailbox) {
2370         if(mailbox == 'sugar::Emails') {
2371             // display an email from Sugar
2372             var emailUIAction = '&emailUIAction=getSingleMessageFromSugar';
2373         } else {
2374             // display an email from an email server
2375             var emailUIAction = '&emailUIAction=getSingleMessage';
2376         }
2377
2378         var get = "&type=printable&ieId=" + ieId + "&uid=" + uid + "&mbox=" + mailbox;
2379         AjaxObject.startRequest(AjaxObject.detailView.callback.viewPrint, urlStandard + emailUIAction + get);
2380     },
2381
2382     /**
2383      * Makes async call to get an email's raw source
2384      */
2385     viewRaw : function(ieId, uid, mailbox) {
2386         var get = "&type=raw&ieId=" + ieId + "&uid=" + uid + "&mailbox=" + mailbox;
2387         AjaxObject.startRequest(AjaxObject.detailView.callback.viewRaw, urlStandard + "&emailUIAction=displayView" + get);
2388     },
2389
2390     /**
2391      * Display all email addresses in detailview.
2392      */
2393     displayAllAddrs : function(el) {
2394         el.style.display = 'none';
2395         Dom.getNextSibling(el).style.display = 'inline';
2396     }
2397 };
2398 ////    END SE.detailView
2399 ///////////////////////////////////////////////////////////////////////////////
2400
2401
2402
2403 ///////////////////////////////////////////////////////////////////////////////
2404 ////    SE.folders
2405 SE.folders = {
2406     contextMenuFocus : new Object(),
2407
2408     /**
2409      * Generates a standardized identifier that allows reconstruction of I-E ID-folder strings or
2410      * SugarFolder ID - folder strings
2411      */
2412     _createFolderId : function(node) {
2413         var ret = '';
2414
2415         if(!node.data.id)
2416             return ret;
2417
2418         if(node.data.ieId) {
2419             /* we have a local Sugar folder */
2420             if(node.data.ieId == 'folder') {
2421                 ret = "sugar::" + node.data.id; // FYI: folder_id is also stored in mbox field
2422             } else if(node.data.ieId.match(SE.reGUID)) {
2423                 ret = "remote::" + node.data.ieId + "::" + node.data.mbox.substr(node.data.mbox.indexOf("INBOX"), node.data.mbox.length);
2424             }
2425         } else {
2426             ret = node.data.id;
2427         }
2428
2429         return ret;
2430     },
2431
2432     addChildNode : function(parentNode, childNode) {
2433         var is_group = (childNode.properties.is_group == 'true') ? 1 : 0;
2434         var is_dynamic = (childNode.properties.is_dynamic == 'true') ? 1 : 0;
2435         var node = this.buildTreeViewNode(childNode.label, childNode.properties.id, is_group, is_dynamic, childNode.properties.unseen, parentNode, childNode.expanded);
2436
2437         if(childNode.nodes) {
2438             if(childNode.nodes.length > 0) {
2439                 for(j=0; j<childNode.nodes.length; j++) {
2440                     var newChildNode = childNode.nodes[j];
2441                     this.addChildNode(node, newChildNode);
2442                 }
2443             }
2444         }
2445     },
2446
2447     /**
2448      * Builds and returns a new TreeView Node
2449      * @param string name
2450      * @param string id
2451      * @param int is_group
2452      * @return object
2453      */
2454     buildTreeViewNode : function(name, id, is_group, is_dynamic, unseen, parentNode, expanded) {
2455         var node = new YAHOO.widget.TextNode(name, parentNode, true);
2456
2457         //node.href = " SE.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '" + id + "', 'false');";
2458         node.expanded = expanded;
2459         node.data = new Object;
2460         node.data['id'] = id;
2461         node.data['mbox'] = id; // to support DD imports into BRAND NEW folders
2462         node.data['label'] = name;
2463         node.data['ieId'] = 'folder';
2464         node.data['isGroup'] = (is_group == 1) ? 'true' : 'false';
2465         node.data['isDynamic'] = (is_dynamic == 1) ? 'true' : 'false';
2466         node.data['unseen'] = unseen;
2467         return node;
2468     },
2469
2470     /**
2471      * ensures that a new folder has a valid name
2472      */
2473     checkFolderName : function(name) {
2474         if(name == "")
2475             return false;
2476
2477         this.folderAdd(name);
2478     },
2479
2480     /**
2481      * Pings email servers for new email - forces refresh of folder pane
2482      */
2483     checkEmailAccounts : function() {
2484         this.checkEmailAccountsSilent(true);
2485     },
2486
2487     checkEmailAccountsSilent : function(showOverlay) {
2488         if(typeof(SE.folders.checkingMail)) {
2489             clearTimeout(SE.folders.checkingMail);
2490         }
2491
2492         // don't stomp an on-going request
2493         if(AjaxObject.currentRequestObject.conn == null) {
2494             if(showOverlay) {
2495                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW,
2496                       app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br><i>" + app_strings.LBL_EMAIL_CHECKING_DESC + "</i>");
2497             }
2498             AjaxObject.startRequest(AjaxObject.folders.callback.checkMail, urlStandard + '&emailUIAction=checkEmail&all=true');
2499         } else {
2500             // wait 5 secs before trying again.
2501             SE.folders.checkingMail = setTimeout("SE.folders.checkEmailAccountsSilent(false);", 5000);
2502         }
2503     },
2504
2505     /**
2506      * Starts check of all email Accounts using a loading bar for large POP accounts
2507      */
2508     startEmailAccountCheck : function() {
2509         // don't do two checks at the same time
2510        if(!AjaxObject.requestInProgress()) {
2511             overlay(app_strings.LBL_EMAIL_ONE_MOMENT, app_strings.LBL_EMAIL_CHECKING_NEW, 'progress');
2512             SE.accounts.ieIds = SE.folders.getIeIds();
2513             if (SE.accounts.ieIds.length > 0) {
2514                 AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2515                                 '&emailUIAction=checkEmailProgress&ieId=' + SE.accounts.ieIds[0] + "&currentCount=0");
2516             } else {
2517                hideOverlay();
2518             }
2519         } else {
2520             // wait 5 secs before trying again.
2521             SE.folders.checkingMail = setTimeout("SE.folders.startEmailAccountCheck();", 5000);
2522         }
2523     },
2524
2525     /**
2526      * Checks a single Account check based on passed ieId
2527      */
2528      startEmailCheckOneAccount : function(ieId, synch) {
2529             if (synch) {
2530                 synch = true;
2531             } else {
2532                 synch = false;
2533             }
2534             var mbox = "";
2535             var node = SE.clickedFolderNode;
2536             if (node && !synch) {
2537                 mbox = node.data.mbox;
2538             } // if
2539             overlay(app_strings.LBL_EMAIL_CHECKING_NEW, app_strings.LBL_EMAIL_CHECKING_DESC, 'progress');
2540             SE.accounts.ieIds = [ieId];
2541             AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
2542                                 '&emailUIAction=checkEmailProgress&mbox=' + mbox + '&ieId=' + ieId + "&currentCount=0&synch=" + synch);
2543       },
2544
2545
2546     /**
2547      * Empties trash for subscribed accounts
2548      */
2549     emptyTrash : function() {
2550         SE.contextMenus.frameFoldersContextMenu.hide();
2551         overlay(app_strings.LBL_EMAIL_EMPTYING_TRASH, app_strings.LBL_EMAIL_ONE_MOMENT);
2552         AjaxObject.startRequest(callbackEmptyTrash, urlStandard + '&emailUIAction=emptyTrash');
2553     },
2554
2555     /**
2556      * Clears Cache files of the inboundemail account
2557      */
2558     clearCacheFiles : function(ieId) {
2559         SE.contextMenus.frameFoldersContextMenu.hide();
2560         overlay(app_strings.LBL_EMAIL_CLEARING_CACHE_FILES, app_strings.LBL_EMAIL_ONE_MOMENT);
2561         AjaxObject.startRequest(callbackClearCacheFiles, urlStandard + '&ieId=' + ieId + '&emailUIAction=clearInboundAccountCache');
2562     },
2563
2564
2565     /**
2566      * Returns an array of all the active accounts in the folder view
2567      */
2568     getIeIds : function() {
2569          var ieIds = [];
2570          var root = SE.tree.getRoot();
2571          for(i=0; i < root.children.length; i++) {
2572            if ((root.children[i].data.cls == "ieFolder" && root.children[i].children.length > 0) ||
2573                         (root.children[i].data.isGroup != null && root.children[i].data.isGroup == "true" && root.children[i].children.length > 0)) {
2574                ieIds.push(root.children[i].children[0].data.ieId);
2575            }
2576          }
2577          return ieIds;
2578      },
2579
2580     /**
2581      * loads folder lists in Settings->Folders
2582      */
2583     lazyLoadSettings : function() {
2584         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2585         AjaxObject.startRequest(callbackSettingsFolderRefresh, urlStandard + '&emailUIAction=getFoldersForSettings');
2586     },
2587
2588     /**
2589      * After the add new folder is done via folders tab on seetings, this function should get called
2590      * It will refresh the folder list after inserting an entry on the UI to update the new folder list
2591      */
2592     loadSettingFolder : function() {
2593         AjaxObject.timeout = 300000; // 5 min timeout for long checks
2594         AjaxObject.startRequest(callbackLoadSettingFolder, urlStandard + '&emailUIAction=getFoldersForSettings');
2595     },
2596
2597     /**
2598      * Recursively removes nodes from the TreeView of type Sugar (data.ieId = 'folder')
2599      */
2600     removeSugarFolders : function() {
2601         var tree = SE.tree;
2602         var root = tree.getRoot();
2603         var folder = SE.util.findChildNode(root, "ieId", "folder");
2604         while(folder) {
2605             tree.removeNode(folder);
2606             folder = SE.util.findChildNode(root, "ieId", "folder");
2607         }
2608         if (!root.childrenRendered) {
2609                 root.childrenRendered = true;
2610         }
2611     },
2612
2613     rebuildFolders : function(silent) {
2614       if (!silent) overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2615        AjaxObject.startRequest(callbackFolders, urlStandard + '&emailUIAction=getAllFoldersTree');
2616     },
2617
2618
2619
2620     /**
2621      * Updates TreeView with Sugar Folders
2622      */
2623     setSugarFolders : function(delay) {
2624         this.removeSugarFolders();
2625                 //AjaxObject.forceAbort = true;
2626                 AjaxObject.startRequest(callbackRefreshSugarFolders, urlStandard + "&emailUIAction=refreshSugarFolders");
2627     },
2628
2629     /**
2630      * Takes async data object and creates the sugar folders in TreeView
2631      */
2632     setSugarFoldersEnd : function(o) {
2633         var root = SE.tree.getRoot();
2634         addChildNodes(root, {nodes: o});
2635         SE.accounts.renderTree();
2636         //If nothing is loaded in the grid, load "My Inbox"
2637         if (SE.grid.params.ieId == "undefined") {
2638                 SE.listView.populateListFrameSugarFolder({data: o[0]}, o[0].id, false);
2639         }
2640     },
2641
2642     startCheckTimer : function() {
2643         if(SE.userPrefs.emailSettings.emailCheckInterval && SE.userPrefs.emailSettings.emailCheckInterval != -1) {
2644             var ms = SE.userPrefs.emailSettings.emailCheckInterval * 60 * 1000;
2645
2646             if(typeof(SE.folders.checkTimer) != 'undefined') {
2647                 clearTimeout(SE.folders.checkTimer);
2648             }
2649
2650             SE.folders.checkTimer = setTimeout("SE.folders.checkEmailAccountsSilent(false);", ms);
2651             if (!SE.userPrefs.emailSettings.firstAutoCheck)
2652             {
2653                 SE.userPrefs.emailSettings.firstAutoCheck = true;
2654                 SE.folders.checkEmailAccountsSilent(false);
2655             }
2656         }
2657     },
2658
2659     /**
2660      * makes an async call to save user preference and refresh folder view
2661      * @param object SELECT list object
2662      */
2663     setFolderSelection : function() {
2664         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
2665
2666         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
2667         var a_active_accnts = "";
2668         for(i=0;i<a_rs.length;i++)
2669         {
2670                 var t_record = a_rs[i];
2671                 var is_active = t_record.getData('is_active');
2672                 if(is_active)
2673                         a_active_accnts += ("&ieIdShow[]=" + t_record.getData('id'));
2674         }
2675
2676         if(a_active_accnts == "")
2677                 a_active_accnts = "&ieIdShow[]=";
2678
2679         var query = "&emailUIAction=setFolderViewSelection" + a_active_accnts;
2680
2681         AjaxObject.startRequest(callbackFolders, urlStandard + query);
2682     },
2683
2684     /**
2685      * makes async call to save user preference for a given node's open state
2686      * @param object node YUI TextNode object
2687      */
2688     setOpenState : function(node) {
2689         SE.util.clearHiddenFieldValues('emailUIForm');
2690         var nodePath = node.data.id;
2691         var nodeParent = node.parent;
2692
2693         while(nodeParent != null) {
2694             // root node has no ID param
2695             if(nodeParent.data != null) {
2696                 nodePath = nodeParent.data.id + "::" + nodePath;
2697             }
2698
2699             var nodeParent = nodeParent.parent;
2700         }
2701
2702         document.getElementById('emailUIAction').value = 'setFolderOpenState';
2703         document.getElementById('focusFolder').value = nodePath;
2704
2705         if(node.expanded == true) {
2706             document.getElementById('focusFolderOpen').value = 'open';
2707         } else {
2708             document.getElementById('focusFolderOpen').value = 'closed';
2709         }
2710
2711         var formObject = document.getElementById('emailUIForm');
2712         YAHOO.util.Connect.setForm(formObject);
2713
2714         AjaxObject.startRequest(null, null);
2715     },
2716
2717     getNodeFromMboxPath : function(path) {
2718         var tree = YAHOO.widget.TreeView.getTree('frameFolders');
2719         var a = JSON.parse(path);
2720
2721         var node = tree.getRoot();
2722
2723         var i = 0;
2724         while(i < a.length) {
2725             node = this.getChildNodeFromLabel(node, a[i]);
2726             i++;
2727         }
2728
2729         return node;
2730     },
2731
2732     getChildNodeFromLabel : function(node, nodeLabel) {
2733         for(i=0; i<node.children.length; i++) {
2734             if(node.children[i].data.id == nodeLabel) {
2735                 return node.children[i];
2736             }
2737         }
2738     },
2739
2740     /**
2741      * returns the node that presumably under the user's right-click
2742      */
2743     getNodeFromContextMenuFocus : function() {
2744         //// get the target(parent) node
2745         var tree = YAHOO.widget.TreeView.trees.frameFolders;
2746         var index = -1;
2747         var target = SE.contextMenus.frameFoldersContextMenu.contextEventTarget;
2748
2749         // filter local folders
2750         if(target.className == 'localFolder' || target.className == 'groupInbox') {
2751             while(target && (target.className == 'localFolder' || target.className == 'groupInbox')) {
2752                 if(target.id == '') {
2753                     target = target.parentNode;
2754                 } else {
2755                     break;
2756                 }
2757             }
2758         }
2759
2760         var targetNode = document.getElementById(target.id);
2761         re = new RegExp(/ygtv[a-z]*(\d+)/i);
2762
2763         try {
2764             var matches = re.exec(targetNode.id);
2765         } catch(ex) {
2766             return document.getElementById(ygtvlabelel1);
2767         }
2768
2769         if(matches) {
2770             index = matches[1];
2771         } else {
2772             // usually parent node
2773             matches = re.exec(targetNode.parentNode.id);
2774
2775             if(matches) {
2776                 index = matches[1];
2777             }
2778         }
2779
2780         var parentNode = (index == -1) ? tree.getNodeByProperty('id', 'Home') : tree.getNodeByIndex(index);
2781         parentNode.expand();
2782
2783         return parentNode;
2784     },
2785
2786     /**
2787      * Decrements the Unread Email count in folder text
2788      * @param string ieId ID to look for
2789      * @param string mailbox name
2790      * @param count how many to decrement
2791      */
2792     decrementUnreadCount : function(ieId, mbox, count) {
2793
2794         if(mbox == null)
2795             return;
2796
2797         if(mbox.indexOf("sugar::") === 0) {
2798             var node = this.getNodeFromId(ieId);
2799         } else {
2800             var node = this.getNodeFromIeIdAndMailbox(ieId, mbox);
2801         }
2802         if(node) {
2803             var unseen = node.data.unseen;
2804             if(unseen > 0) {
2805                 var check = unseen - count;
2806                 var finalCount = (check >= 0) ? check : 0;
2807                 node.data.unseen = finalCount;
2808             }
2809             SE.accounts.renderTree();
2810         }
2811     },
2812
2813     /**
2814      * gets the TreeView node with a given ID/ieId
2815      * @param string id ID to look for
2816      * @return object Node
2817      */
2818     getNodeFromId : function(id) {
2819         SE.folders.focusNode = null;
2820         SE.util.cascadeNodes(SE.tree.getRoot(), function(ieId) {
2821             if ((this.data.id && this.data.id == ieId) || (this.data.ieId && this.data.ieId == ieId)) {
2822                 SE.folders.focusNode = this;
2823                 return false;
2824             }
2825         }, null, [id]);
2826         return SE.folders.focusNode;
2827     },
2828
2829     /**
2830      * Uses ieId and mailbox to try to find a node in the tree
2831      */
2832     getNodeFromIeIdAndMailbox : function(id, mbox) {
2833                 SE.folders.focusNode = null;
2834         if (mbox == "sugar::Emails") {
2835                 mbox = id;
2836                 id = "folder";
2837         } // if
2838         SE.util.cascadeNodes(SE.tree.getRoot(), function(varsarray) {
2839                 if (varsarray instanceof Array) {
2840             if (this.data.ieId && this.data.ieId == varsarray[0]
2841                     && this.data.mbox == varsarray[1]) {
2842                 SE.folders.focusNode = this;
2843                 return false;
2844             } }
2845                 else {
2846                         if (this.data.ieId && this.data.ieId == varsarray) {
2847                                 SE.folders.focusNode = this;
2848                     return false;
2849                         }
2850                 }
2851         }, null, [id, mbox]);
2852         return SE.folders.focusNode;
2853     },
2854
2855     unhighliteAll : function() {
2856         SE.util.cascadeNodes(SE.tree.getRoot(), function(){this.unhighlight()});
2857     },
2858
2859     /**
2860      * Displays a short form
2861      */
2862     folderAdd : function() {
2863         SE.contextMenus.frameFoldersContextMenu.hide();
2864
2865         var node = SE.clickedFolderNode;
2866
2867         if(node != null && node.data) {
2868             overlay(app_strings.LBL_EMAIL_FOLDERS_ADD_DIALOG_TITLE,
2869                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2870                     'prompt', {fn:SE.folders.folderAddXmlCall, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2871         } else {
2872             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2873         }
2874     },
2875
2876     folderAddRegisterEnter : function() {
2877         this.enterKeyListener = new YAHOO.util.KeyListener(YAHOO.util.Dom.get("sugar-message-prompt"),
2878                                                                                                                         {keys: YAHOO.util.KeyListener.KEY.ENTER},
2879                                                                                                                         this.buttons[1].handler);
2880
2881                 this.enterKeyListener.enable();
2882     },
2883
2884     folderRemoveRegisterEnter : function() {
2885         this.enterKeyListener.disable();
2886     },
2887
2888     folderAddXmlCall : function(name) {
2889         if (trim(name) == "") {
2890                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
2891                 return false;
2892         }
2893         name = escape(name);
2894         var post = '';
2895         var type = 'sugar';
2896
2897         var parentNode = SE.clickedFolderNode;
2898
2899         this.contextMenuFocus = parentNode;
2900
2901         if(parentNode.data.ieId) {
2902             if(parentNode.data.ieId != 'folder' && parentNode.data.ieId.match(SE.reGUID)) {
2903                 type = 'imap';
2904             }
2905         }
2906         if(type == 'imap') {
2907                 // make an IMAP folder
2908             post = "&newFolderName=" + name + "&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2909             AjaxObject.startRequest(callbackFolderRename, urlStandard + '&emailUIAction=saveNewFolder&folderType=imap' + post);
2910         } else if(type == 'sugar') {
2911             // make a Sugar folder
2912             if(SE.folders.isUniqueFolderName(name)) {
2913                 post = "&parentId=" + parentNode.data.id + "&nodeLabel=" + name;
2914                 AjaxObject.startRequest(callbackFolderSave, urlStandard + '&emailUIAction=saveNewFolder&folderType=sugar&' + post);
2915             } else {
2916                 alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
2917                 SE.folders.folderAdd();
2918                 return;
2919             }
2920         } else {
2921             alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2922         }
2923
2924         // hide add-folder diaglogue
2925         SE.e2overlay.hide();
2926     },
2927
2928     /**
2929      * Removes either an IMAP folder or a Sugar Folder
2930      */
2931     folderDelete : function() {
2932         SE.contextMenus.frameFoldersContextMenu.hide();
2933
2934         if(confirm(app_strings.LBL_EMAIL_FOLDERS_DELETE_CONFIRM)) {
2935             var post = '';
2936             var parentNode = SE.clickedFolderNode;
2937
2938             if(parentNode != null && parentNode.data) {
2939                 if(parentNode.data.mbox == 'INBOX' || parentNode.data.id == 'Home') {
2940                     overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2941                     return;
2942                 }
2943
2944                 AjaxObject.target = 'frameFlex';
2945
2946                 if(parentNode.data.ieId != 'folder') {
2947                     // delete an IMAP folder
2948                     post = "&folderType=imap&mbox=" + parentNode.data.mbox + "&ieId=" + parentNode.data.ieId;
2949                 } else {
2950                     // delete a sugar folder
2951                     post = "&folderType=sugar&folder_id=" + parentNode.data.id;
2952                 }
2953                 overlay("Deleting folder", app_strings.LBL_EMAIL_ONE_MOMENT);
2954                 AjaxObject.startRequest(callbackFolderDelete, urlStandard + '&emailUIAction=deleteFolder' + post);
2955             } else {
2956                 alert(app_strings.LBL_EMAIL_ERROR_CANNOT_FIND_NODE);
2957             }
2958         }
2959     },
2960
2961     /**
2962      * Rename folder form
2963      */
2964      //EXT111
2965     folderRename : function() {
2966         SE.contextMenus.frameFoldersContextMenu.hide();
2967         var node = SE.clickedFolderNode;
2968
2969         if(node != null) {
2970             if(node.id == 'Home' || !node.data || node.data.mbox == 'INBOX') {
2971                 overlay(app_strings.LBL_EMAIL_ERROR_GENERAL_TITLE, app_strings.LBL_EMAIL_FOLDERS_CHANGE_HOME, 'alert');
2972                 return;
2973             }
2974
2975                         overlay(app_strings.LBL_EMAIL_FOLDERS_RENAME_DIALOG_TITLE + " - " + node.data.text,
2976                     app_strings.LBL_EMAIL_SETTINGS_NAME,
2977                     'prompt',
2978                     {fn:SE.folders.submitFolderRename, beforeShow: SE.folders.folderAddRegisterEnter, beforeHide: SE.folders.folderRemoveRegisterEnter});
2979         } else {
2980             alert(app_strings.LBL_EMAIL_FOLDERS_NO_VALID_NODE);
2981         }
2982     },
2983
2984     /**
2985      * fills an Object with key-value pairs of available folders
2986      */
2987     getAvailableFoldersObject : function() {
2988         var ret = new Object();
2989         var tree = SE.tree.root;
2990
2991         if(tree.children) {
2992             for(var i=0; i<tree.children.length; i++) {
2993                 ret = this.getFolderFromChild(ret, tree.children[i], '', app_strings.LBL_EMAIL_SPACER_MAIL_SERVER);
2994             }
2995         } else {
2996             ret['none'] = app_strings.LBL_NONE;
2997         }
2998
2999         return ret;
3000     },
3001
3002     /**
3003      * Fills in key-value pairs for dependent dropdowns
3004      * @param object ret Associative array
3005      * @param object node TreeView node in focus
3006      * @param string currentPath Built up path thus far
3007      * @param string spacer Defined in app_strings, visual separator b/t Sugar and Remote folders
3008      */
3009     getFolderFromChild : function(ret, node, currentPath, spacer) {
3010         if(node.data != null && node.depth > 0) {
3011             /* handle visual separtors differentiating b/t mailserver and local */
3012             if(node.data.ieId && node.data.ieId == 'folder') {
3013                 spacer = app_strings.LBL_EMAIL_SPACER_LOCAL_FOLDER;
3014             }
3015
3016             if(!ret.spacer0) {
3017                 ret['spacer0'] = spacer;
3018             } else if(ret.spacer0 != spacer) {
3019                 ret['spacer1'] = spacer
3020             }
3021
3022             var theLabel = node.data.label.replace(/<[^>]+[\w\/]+[^=>]*>/gi, '');
3023             var depthMarker = currentPath;
3024             var retIndex = SE.folders._createFolderId(node);
3025             ret[retIndex] = depthMarker + theLabel;
3026         }
3027
3028         if(node.children != null) {
3029             if(theLabel) {
3030                 currentPath += theLabel + "/";
3031             }
3032
3033             for(var i=0; i<node.children.length; i++) {
3034                 ret = this.getFolderFromChild(ret, node.children[i], currentPath, spacer);
3035             }
3036         }
3037
3038         return ret;
3039     },
3040
3041     /**
3042      * Wrapper to refresh folders tree
3043      */
3044     getFolders : function() {
3045         SE.accounts.rebuildFolderList();
3046     },
3047
3048     /**
3049      * handles events around folder-rename input field changes
3050      * @param object YUI event object
3051      */
3052     handleEnter : function(e) {
3053         switch(e.browserEvent.type) {
3054             case 'click':
3055                 e.preventDefault(); // click in text field
3056             break;
3057
3058             case 'blur':
3059                 SE.folders.submitFolderRename(e);
3060             break;
3061
3062             case 'keypress':
3063                 var kc = e.browserEvent.keyCode;
3064                 switch(kc) {
3065                     case 13: // enter
3066                         e.preventDefault();
3067                         SE.folders.submitFolderRename(e);
3068                     break;
3069
3070                     case 27: // esc
3071                         e.preventDefault(e);
3072                         SE.folders.cancelFolderRename(e);
3073                     break;
3074                 }
3075             break;
3076         }
3077     },
3078     /**
3079     * Called when a node is clicked on in the folder tree
3080     * @param node, The node clicked on
3081     * @param e, The click event
3082     */
3083     handleClick : function(o) {
3084         var node = o.node;
3085         //If the click was on a sugar folder
3086         if (node.data.ieId == "folder") {
3087             SE.listView.populateListFrameSugarFolder(node, node.id, false);
3088         }
3089         else {
3090             SE.listView.populateListFrame(node, node.data.ieId, false);
3091         }
3092        //eval(node.data.click);
3093        //debugger;
3094     },
3095
3096     /**
3097     * Called when a node is right-clicked on in the folder tree
3098     */
3099     handleRightClick : function(e) {
3100         YAHOO.util.Event.preventDefault(e);
3101                 //Get the Tree Node
3102                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Event.getTarget(e));
3103                 var menu = SUGAR.email2.contextMenus.frameFoldersContextMenu;
3104
3105                 //If the click was on a sugar folder
3106         SE.clickedFolderNode = node;
3107         var inbound = (node.data.ieId && node.data.ieId != 'folder');
3108                 var disableNew = (inbound && (typeof(node.data.mbox) == 'undefined'));
3109                 menu.getItem(0).cfg.setProperty("disabled", !inbound);
3110                 menu.getItem(1).cfg.setProperty("disabled", !inbound);
3111                 menu.getItem(2).cfg.setProperty("disabled", disableNew);
3112                 menu.getItem(3).cfg.setProperty("disabled", false);
3113                 menu.getItem(4).cfg.setProperty("disabled", false);
3114                 menu.getItem(5).cfg.setProperty("disabled", false);
3115                 menu.getItem(6).cfg.setProperty("disabled", true);
3116                 //Group folder
3117                 if (inbound && node.data.isGroup != null && node.data.isGroup == "true") {
3118                         menu.getItem(0).cfg.setProperty("disabled", true);
3119                         menu.getItem(1).cfg.setProperty("disabled", true);
3120                         menu.getItem(2).cfg.setProperty("disabled", true);
3121                         menu.getItem(3).cfg.setProperty("disabled", true);
3122                         menu.getItem(4).cfg.setProperty("disabled", true);
3123                 }
3124         if (node.data.protocol != null) {
3125                 menu.getItem(6).cfg.setProperty("disabled", false);
3126         }
3127                 if (node.data.folder_type != null && (node.data.folder_type == "inbound" ||
3128                                 node.data.folder_type == "sent" || node.data.folder_type == "draft")) {
3129                         //Sent or Draft folders
3130                         menu.getItem(3).cfg.setProperty("disabled", true);
3131                         menu.getItem(4).cfg.setProperty("disabled", true);
3132                         menu.getItem(5).cfg.setProperty("disabled", true);
3133                 }
3134
3135                 //For group with auto inbound, disable everything.
3136                 if( (typeof(node.data.is_group) != 'undefined') && node.data.is_group == 'true')
3137                 {
3138                     menu.getItem(0).cfg.setProperty("disabled", true);
3139                 menu.getItem(1).cfg.setProperty("disabled", true);
3140                 menu.getItem(2).cfg.setProperty("disabled", true);
3141                 menu.getItem(3).cfg.setProperty("disabled", true);
3142                 menu.getItem(4).cfg.setProperty("disabled", true);
3143                 menu.getItem(5).cfg.setProperty("disabled", true);
3144                 menu.getItem(6).cfg.setProperty("disabled", true);
3145                 }
3146
3147                 menu.cfg.setProperty("xy", YAHOO.util.Event.getXY(e));
3148                 menu.show();
3149     },
3150
3151     /**
3152     * Called when a row is dropped on a node
3153     */
3154     handleDrop : function(rows, targetFolder) {
3155         var rowData = rows[0].getData();
3156         if (rowData.mbox != targetFolder.data.mbox) {
3157             var srcIeId = rowData.ieId;
3158             var srcFolder = rowData.mbox;
3159             var destIeId = targetFolder.data.ieId;
3160             var destFolder = targetFolder.data.mbox;
3161             var uids = [];
3162             for(var i=0; i<rows.length; i++) {
3163                 uids[i] = rows[i].getData().uid;
3164             }
3165             SE.listView.moveEmails(srcIeId, srcFolder, destIeId, destFolder, uids, rows);
3166         }
3167     },
3168
3169     /**
3170     * Called when something is dragged over a Folder Node
3171     */
3172     dragOver : function(dragObject) {
3173        return true;
3174     },
3175
3176     /**
3177      * Determines if a folder name is unique to the folder tree
3178      * @param string name
3179      */
3180     isUniqueFolderName : function(name) {
3181         uniqueFolder = true;
3182         var root = SE.tree.getRoot();
3183         SE.util.cascadeNodes(SE.tree.getRoot(), function(name) {
3184             if (this.attributes && this.attributes.ieId == "folder") {
3185                 if (this.attributes.text == name) {
3186                     uniqueFolder = false;
3187                     return false;
3188                 }
3189             }
3190         }, null, [name]);
3191         return uniqueFolder;
3192     },
3193
3194     /**
3195      * Makes async call to rename folder in focus
3196      * @param object e Event Object
3197      */
3198     submitFolderRename : function(newName) {
3199         if (trim(newName) == "") {
3200                 alert(mod_strings.LBL_ENTER_FOLDER_NAME);
3201                 return false;
3202         }
3203                 newName = escape(newName);
3204         var node = SE.clickedFolderNode;
3205         var origName = node.data.text
3206         //Ignore no change
3207         if (newName == origName) {
3208             return true;
3209         }
3210         if(SE.folders.isUniqueFolderName(newName)) {
3211             overlay(app_strings.LBL_EMAIL_MENU_RENAMING_FOLDER, app_strings.LBL_EMAIL_ONE_MOMENT);
3212             if (node.data.ieId == "folder") {
3213                 //Sugar Folder
3214                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&folderId=" + node.data.id + "&newFolderName=" + newName);
3215             }
3216             else {
3217                 //IMAP folder or POP mailbox
3218                 var nodePath = node.data.mbox.substring(0, node.data.mbox.lastIndexOf(".") + 1);
3219                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=renameFolder&ieId="
3220                     + node.data.ieId + "&oldFolderName=" + node.data.mbox + "&newFolderName=" + nodePath + newName);
3221             }
3222             return true;
3223         } else {
3224             alert(app_strings.LBL_EMAIL_ERROR_DUPE_FOLDER_NAME);
3225             return false;
3226         }
3227     },
3228
3229     moveFolder : function(folderId, parentFolderId) {
3230         if (folderId != parentFolderId)
3231         {
3232                 AjaxObject.startRequest(callbackFolderRename, urlStandard + "&emailUIAction=moveFolder&folderId="
3233                     + folderId + "&newParentId=" + parentFolderId);
3234         }
3235     },
3236
3237     /**
3238      * makes async call to do a full synchronization of all accounts
3239      */
3240     synchronizeAccounts : function() {
3241         if(confirm(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC_WARN)) {
3242             overlayModal(app_strings.LBL_EMAIL_SETTINGS_FULL_SYNC, app_strings.LBL_EMAIL_ONE_MOMENT + "<br>&nbsp;<br>" + app_strings.LBL_EMAIL_COFFEE_BREAK);
3243             AjaxObject.startRequest(callbackFullSync, urlStandard + '&emailUIAction=synchronizeEmail');
3244         }
3245     },
3246
3247     /**
3248      * Updates user's folder subscriptsion (Sugar only)
3249      * @param object SELECT DOM object in focus
3250      * @param string type of Folder selection
3251      */
3252     updateSubscriptions : function() {
3253         overlay(app_strings.LBL_EMAIL_REBUILDING_FOLDERS, app_strings.LBL_EMAIL_ONE_MOMENT);
3254
3255         var active = "";
3256
3257         select = document.getElementById('userFolders');
3258
3259         for(i=0; i<select.options.length; i++) {
3260             var opt = select.options[i];
3261              if(opt.selected && opt.value != "") {
3262                  if(active != "") {
3263                      active += "::";
3264                  }
3265                  active += opt.value;
3266              }
3267         }
3268
3269         //Add the group folder ids.
3270         var group_folders = SUGAR.email2.folders.retrieveGroupFolderSubscriptions();
3271         for(i=0; i<group_folders.length; i++)
3272         {
3273             active += ("::" + group_folders[i]);
3274         }
3275
3276         AjaxObject.startRequest(callbackFolderSubscriptions, urlStandard + '&emailUIAction=updateSubscriptions&subscriptions=' + active);
3277     },
3278     /**
3279      * Updates user's group folder subscriptsion (Sugar only)
3280      * @param ieID The group folder to add to the tree view
3281      */
3282     retrieveGroupFolderSubscriptions : function() {
3283
3284         var a_rs = SE.accounts.inboundAccountsSettingsTable.getRecordSet().getRecords();
3285         var activeGroupFolders = "";
3286         var activeGroupIds = [];
3287         for(i=0;i<a_rs.length;i++)
3288         {
3289                 var t_record = a_rs[i];
3290                 var is_active = t_record.getData('is_active');
3291                 var isGroupFolder = t_record.getData('has_groupfolder');
3292                 var ieID = t_record.getData('id');
3293                 if( isGroupFolder )
3294                 {
3295                     if(is_active)
3296                       activeGroupIds.push(ieID);
3297                 }
3298         }
3299
3300         return activeGroupIds;
3301     }
3302
3303 };
3304
3305 SE.folders.checkEmail2 = function() {
3306     AjaxObject.startRequest(callbackCheckEmail2, urlStandard + "&emailUIAction=checkEmail2");
3307 }
3308 ////    END FOLDERS OBJECT
3309 ///////////////////////////////////////////////////////////////////////////////
3310
3311
3312 ///////////////////////////////////////////////////////////////////////////////
3313 ////    SE.keys
3314 /**
3315  * Keypress Event capture and processing
3316  */
3317 SE.keys = {
3318     overall : function(e) {
3319         switch(e.charCode) {
3320             case 119: // "w"
3321                 if(e.ctrlKey || e.altKey) {
3322                     var focusRegion = SE.innerLayout.regions.center;
3323                     if(focusRegion.activePanel.closable == true) {
3324                         focusRegion.remove(focusRegion.activePanel);
3325                     }
3326                 }
3327             break;
3328         }
3329     }
3330 };
3331 ////    END SE.keys
3332 ///////////////////////////////////////////////////////////////////////////////
3333
3334
3335 ///////////////////////////////////////////////////////////////////////////////
3336 ////    SE.listView
3337 /**
3338  * ListView object methods and attributes
3339  */
3340 SE.listView = {
3341     currentRowId : -1,
3342
3343     /**
3344      * Fills the ListView pane with detected messages.
3345      */
3346     populateListFrame : function(node, ieId, forceRefresh) {
3347         SE.innerLayout.selectTab(0);
3348                 YAHOO.util.Connect.abort(AjaxObject.currentRequestObject, null, false);
3349
3350         Dom.get('_blank').innerHTML = "";
3351         SE.grid.params['emailUIAction'] = 'getMessageList';
3352         SE.grid.params['mbox'] = node.data.mbox;
3353         SE.grid.params['ieId'] = ieId;
3354         forcePreview = true; // loads the preview pane with first item in grid
3355         SE.listView.refreshGrid();
3356     },
3357
3358     /**
3359      * Like populateListFrame(), but specifically for SugarFolders since the API is radically different
3360      */
3361     populateListFrameSugarFolder : function(node, folderId, forceRefresh) {
3362         SE.innerLayout.selectTab(0);
3363         Dom.get('_blank').innerHTML = "";
3364         SE.grid.params['emailUIAction'] = 'getMessageListSugarFolders';
3365         SE.grid.params['ieId'] = node.data.id;
3366         SE.grid.params['mbox'] = node.data.origText ? node.data.origText : node.data.text;
3367         SE.listView.refreshGrid();
3368     },
3369
3370     /**Mac
3371      * Sets sort order as user preference
3372      * @param
3373      */
3374     saveListViewSortOrder : function(sortBy, focusFolderPassed, ieIdPassed, ieNamePassed) {
3375         ieId = ieIdPassed;
3376         ieName = ieNamePassed;
3377         focusFolder = focusFolderPassed;
3378
3379         SE.util.clearHiddenFieldValues('emailUIForm');
3380         var previousSort = document.getElementById('sortBy').value;
3381
3382         document.getElementById('sortBy').value = sortBy;
3383         document.getElementById('emailUIAction').value = 'saveListViewSortOrder';
3384         document.getElementById('focusFolder').value = focusFolder;
3385         document.getElementById('ieId').value = ieId;
3386
3387         if(sortBy == previousSort) {
3388             document.getElementById('reverse').value = '1';
3389         }
3390
3391         var formObject = document.getElementById('emailUIForm');
3392         YAHOO.util.Connect.setForm(formObject);
3393
3394         AjaxObject.startRequest(callbackListViewSortOrderChange, null);
3395     },
3396
3397
3398     /**
3399      * Enables click/arrow select of grid items which then populate the preview pane.
3400      */
3401     selectFirstRow : function() {
3402         SE.grid.selModel.selectFirstRow();
3403     },
3404
3405     selectLastRow : function() {
3406         SE.grid.selModel.selectRow(SE.grid.dataSource.data.getCount() - 1);
3407     },
3408
3409     setEmailListStyles : function() {
3410         SE.listView.boldUnreadRows();
3411         return;
3412         var ds = SE.grid.getStore();
3413         if (SE.grid.getSelections().length == 0) {
3414             document.getElementById('_blank').innerHTML = '';
3415         }
3416
3417         var acctMbox = '';
3418         if(typeof(ds.baseParams.mbox) != 'undefined') {
3419             acctMbox = (ds.baseParams.acct) ? ds.baseParams.acct + " " + ds.baseParams.mbox : ds.baseParams.mbox;
3420             var cm = SE.grid.getColumnModel();
3421             if (ds.baseParams.mbox == mod_strings.LBL_LIST_FORM_SENT_TITLE) {
3422                 cm.setColumnHeader(4, mod_strings.LBL_LIST_DATE_SENT);
3423                 //SE.grid.render();
3424             } else if (cm.config[4].header != app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER){
3425                 cm.setColumnHeader(4, app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER);
3426                 //SE.grid.render();
3427             }
3428         }
3429         var total = (typeof(ds.totalLength) != "undefined") ? " (" + ds.totalLength +" " + app_strings.LBL_EMAIL_MESSAGES +") " : "";
3430         SE.listViewLayout.setTitle(acctMbox + total);// + toggleRead + manualFit);
3431
3432
3433         // 4/20/2007 added to hide overlay after search
3434         //hideOverlay();
3435         if (ds.reader.xmlData.getElementsByTagName('UnreadCount').length > 0){
3436             var unread = ds.reader.xmlData.getElementsByTagName('UnreadCount')[0].childNodes[0].data;
3437             var node = SE.folders.getNodeFromIeIdAndMailbox(ds.baseParams.ieId, ds.baseParams.mbox);
3438             if (node) node.data.unseen = unread;
3439         }
3440         SE.accounts.renderTree();
3441
3442
3443         // bug 15035 perhaps a heavy handed solution to stopping the loading spinner.
3444         if(forcePreview && ds.totalCount > 0) {
3445             SE.detailView.getEmailPreview();
3446             forcePreview = false;
3447         }
3448     },
3449
3450     /**
3451      * Removes a row if found via its UID
3452      */
3453     removeRowByUid : function(uid) {
3454         uid = new String(uid);
3455         uids = uid.split(',');
3456         var dataTableRecords = SE.grid.getRecordSet().getRecords(0, SE.grid.getRecordSet().getLength());
3457
3458         for(j=0; j<uids.length; j++) {
3459             var theUid = uids[j];
3460             for (k = 0 ; k < SE.grid.getRecordSet().getLength() ; k++) {
3461                 if (SE.grid.getRecordSet().getRecords()[k].getData().uid == theUid) {
3462                         SE.grid.deleteRow(SE.grid.getRecordSet().getRecords()[k]);
3463                 }
3464             } // for
3465         }
3466     },
3467
3468     displaySelectedEmails : function(rows) {
3469         var dm = SE.grid.getDataModel();
3470         var uids = '';
3471
3472         for(i=0; i<rows.length; i++) {
3473             var rowIndex = rows[i].rowIndex;
3474             var metadata = dm.data[rowIndex];
3475
3476             if(uids != "") {
3477                 uids += ",";
3478             }
3479             uids += metadata[5];
3480
3481             // unbold unseen email
3482             this.unboldRow(rowIndex);
3483         }
3484
3485         SE.detailView.populateDetailViewMultiple(uids, metadata[6], metadata[7], metadata[8], false);
3486     },
3487
3488     /**
3489      * exception handler for data load failures
3490      */
3491     loadException : function(dataModel, ex, response) {
3492         //debugger;
3493     },
3494
3495     /**
3496      * Moves email(s) from a folder to another, from IMAP/POP3 to Sugar and vice-versa
3497      * @param string sourceIeId Email's source I-E id
3498      * @param string sourceFolder Email's current folder
3499      * @param destinationIeId Destination I-E id
3500      * @param destinationFolder Destination folder in format [root::IE::INBOX::etc]
3501      *
3502      * @param array emailUids Array of email's UIDs
3503      */
3504     moveEmails : function(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, selectedRows) {
3505         if(destinationIeId != 'folder' && sourceIeId != destinationIeId) {
3506             overlay(app_strings.LBL_EMAIL_ERROR_MOVE_TITLE, app_strings.LBL_EMAIL_ERROR_MOVE);
3507         } else {
3508             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
3509             // remove rows from visibility
3510             for(row in selectedRows) {
3511                 //SE.grid.getStore().remove(row);
3512             }
3513
3514             var baseUrl =    '&sourceIeId=' + sourceIeId +
3515                             '&sourceFolder=' + sourceFolder +
3516                             '&destinationIeId=' + destinationIeId +
3517                             '&destinationFolder=' + destinationFolder;
3518             var uids = '';
3519
3520             for(i=0; i<emailUids.length; i++) {
3521                 if(uids != '') {
3522                     uids += app_strings.LBL_EMAIL_DELIMITER;
3523                 }
3524                 uids += emailUids[i];
3525             }
3526             if (destinationIeId == 'folder' && sourceFolder != 'sugar::Emails') {
3527                 AjaxObject.startRequest(callbackImportOneEmail, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3528             } else {
3529                 AjaxObject.startRequest(callbackMoveEmails, urlStandard + '&emailUIAction=moveEmails&emailUids=' + uids + baseUrl);
3530             }
3531         }
3532     },
3533
3534     /**
3535      * Unbolds text in the grid view to denote read status
3536      */
3537     markRead : function(index, record) {
3538         // unbold unseen email
3539         var row = SE.grid.getRecord(record);
3540         row.getData().seen = 1;
3541         SE.grid.getTrEl(record).style.fontWeight = "normal";
3542     },
3543
3544     /**
3545      * grid row output, bolding unread emails
3546      */
3547     boldUnreadRows : function() {
3548         // bold unread emails
3549         var trEl = SE.grid.getFirstTrEl();
3550         while(trEl != null) {
3551                 if(SE.grid.getRecord(trEl).getData().seen == "0")
3552                         trEl.style.fontWeight = "bold";
3553                 else
3554                         trEl.style.fontWeight = "";
3555                 trEl = SE.grid.getNextTrEl(trEl);
3556         }
3557     },
3558
3559     /**
3560      * Show preview for an email if 1 and only 1 is selected
3561      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3562      */
3563     handleRowSelect : function(e) {
3564         if(e.selectedRows.length == 1) {
3565             SE.detailView.getEmailPreview();
3566         }
3567     },
3568
3569     handleDrop : function(e, dd, targetId, e2) {
3570         switch(targetId) {
3571             case 'htmleditordiv':
3572                 var rows = SE.grid.getSelectedRows();
3573                 if(rows.length > 0) {
3574                     SE.listView.displaySelectedEmails(rows);
3575                 }
3576             break;
3577
3578             default:
3579                 var targetElId = new String(targetId);
3580                 var targetIndex = targetElId.replace('ygtvlabelel',"");
3581                 var targetNode = SE.tree.getNodeByIndex(targetIndex);
3582                 var dm = SE.grid.getDataModel();
3583                 var emailUids = new Array();
3584                 var destinationIeId = targetNode.data.ieId;
3585                 var destinationFolder = SE.util.generateMboxPath(targetNode.data.mbox);
3586
3587
3588                 var rows = SE.grid.getSelectedRows();
3589                 // iterate through dragged rows
3590                 for(i=0; i<rows.length; i++) {
3591                     //var rowIndex = e.selModel.selectedRows[i].rowIndex;
3592                     var rowIndex = rows[i].rowIndex;
3593                     var dataModelRow = dm.data[rowIndex];
3594                     var sourceIeId = dataModelRow[7];
3595                     var sourceFolder = dataModelRow[6];
3596                     emailUids[i] = dataModelRow[5];
3597                 }
3598
3599                 // event wrapped call - need FQ
3600                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
3601                 SE.listView.moveEmails(sourceIeId, sourceFolder, destinationIeId, destinationFolder, emailUids, e.selModel.selectedRows);
3602             break;
3603         }
3604     },
3605
3606     /**
3607      * Hack-around to get double-click and single clicks to work on the grid
3608      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3609      */
3610     handleClick : function(o) {
3611         SUGAR.email2.grid.clearTextSelection();
3612
3613         var el = SUGAR.email2.grid.getSelectedRows();
3614
3615         //Load an email preview only if a single record is selected.  For multiple selections do nothing.
3616         if ( el.length == 1)
3617         {
3618            var rowId = el[0];
3619            SUGAR.email2.listView.currentRow = SUGAR.email2.grid.getRecord(rowId);
3620            SUGAR.email2.listView.currentRowIndex = rowId;
3621            clearTimeout(SUGAR.email2.detailView.previewTimer);
3622            SUGAR.email2.detailView.previewTimer = setTimeout("SUGAR.email2.detailView.getEmailPreview();", 500);
3623         }
3624     },
3625
3626     /**
3627      * Custom handler for double-click/enter
3628      * ---- all references must be fully qual'd since this gets wrapped by the YUI event handler
3629      */
3630     getEmail : function(e) {
3631         var rows = SE.grid.getSelectedRows();
3632         var row = SE.grid.getRecord(rows[0]).getData();
3633
3634         clearTimeout(SE.detailView.previewTimer);
3635         document.getElementById("_blank").innerHTML = "";
3636
3637         if(row.type != "draft") {
3638             SE.detailView.populateDetailView(row.uid, row.mbox, row.ieId, 'true', SE.innerLayout);
3639         } else {
3640             // circumventing yui-ext tab generation, let callback handler build new view
3641             SE.util.clearHiddenFieldValues('emailUIForm');
3642             //function(uid, mbox, ieId, setRead, destination) {
3643             document.getElementById('emailUIAction').value = 'getSingleMessageFromSugar';
3644             document.getElementById('uid').value = row.uid; // uid;
3645             document.getElementById('mbox').value = row.mbox; // mbox;
3646             document.getElementById('ieId').value = row.ieId; // ieId;
3647
3648             YAHOO.util.Connect.setForm(document.getElementById('emailUIForm'));
3649             AjaxObject.target = '_blank';
3650             AjaxObject.startRequest(AjaxObject.detailView.callback.emailDetail, null);
3651         }
3652     },
3653
3654     /**
3655      * Retrieves a row if found via its UID
3656      * @param string
3657      * @return int
3658      */
3659     getRowIndexByUid : function(uid) {
3660         uid = new String(uid);
3661         uids = uid.split(',');
3662
3663         for(j=0; j<uids.length; j++) {
3664             var theUid = uids[j];
3665
3666             for(i=0; i<SE.grid.getStore().data.length; i++) {
3667                 if(SE.grid.getStore().data[i].id == theUid) {
3668                     return i;
3669                 }
3670             }
3671         }
3672     },
3673
3674     /**
3675      * Returns the UID's of the seleted rows
3676      *
3677      */
3678      getUidsFromSelection : function() {
3679          var rows = SE.grid.getSelectedRows();
3680          var uids = [];
3681          /* iterate through available rows JIC a row is deleted - use first available */
3682          for(var i=0; i<rows.length; i++) {
3683                  uids[i] = SE.grid.getRecord(rows[i]).getData().uid;
3684          }
3685          return uids;
3686      },
3687
3688     refreshGrid : function() {
3689         SE.grid.getDataSource().sendRequest(
3690             SUGAR.util.paramsToUrl(SE.grid.params),
3691                 SE.grid.onDataReturnInitializeTable,
3692                 SE.grid
3693         );
3694     }
3695
3696 };
3697 ////    END SE.listView
3698 ///////////////////////////////////////////////////////////////////////////////
3699
3700 ///////////////////////////////////////////////////////////////////////////////
3701 ////    SEARCH
3702 SE.search = {
3703     /**
3704      * sends search criteria
3705      * @param reference element search field
3706      */
3707     search : function(el) {
3708         var searchCriteria = new String(el.value);
3709
3710         if(searchCriteria == '') {
3711             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3712             return false;
3713         }
3714
3715         var safeCriteria = escape(searchCriteria);
3716
3717         var accountListSearch = document.getElementById('accountListSearch');
3718         //overlay(app_strings.LBL_EMAIL_SEARCHING,app_strings.LBL_EMAIL_ONE_MOMENT);
3719
3720         SE.grid.getStore().baseParams['emailUIAction'] = 'search';
3721         SE.grid.getStore().baseParams['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3722         SE.grid.getStore().baseParams['subject'] = safeCriteria;
3723         SE.grid.getStore().baseParams['ieId'] = accountListSearch.options[accountListSearch.selectedIndex].value;
3724         SE.grid.getStore().load({params:{start:0, limit:SE.userPrefs.emailSettings.showNumInList}});
3725
3726     },
3727
3728     /**
3729      * sends advanced search criteria
3730      */
3731     searchAdvanced : function() {
3732         var formObject = document.getElementById('advancedSearchForm');
3733         var search = false;
3734
3735         //Set assigned user id to blank if name is not present.
3736         if (formObject.elements['assigned_user_name'].value == "")
3737             formObject.elements['assigned_user_id'].value = "";
3738
3739         for(i=0; i<formObject.elements.length; i++) {
3740             if(formObject.elements[i].type != 'button' && formObject.elements[i].value != "") {
3741                 search = true;
3742             }
3743             if(formObject.elements[i].type == 'text') {
3744                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3745             }
3746             if(formObject.elements[i].type == 'hidden') {
3747                 SE.grid.params[formObject.elements[i].name] = formObject.elements[i].value;
3748             }
3749              if(formObject.elements[i].type == 'select-one') {
3750                 var el = formObject.elements[i];
3751                 var v = el.options[el.selectedIndex].value;
3752
3753                 if(v != "")
3754                     SE.grid.params[el.name] = v;
3755                 else
3756                 {
3757                     //Clear previous search results if necessary
3758                     if(typeof( SE.grid.params[el.name]) != 'undefined')
3759                         delete SE.grid.params[el.name]
3760                 }
3761              }
3762         }
3763
3764         if (search)
3765         {
3766             if(! this.validateSearchFormInput() )
3767                 return;
3768
3769                 SE.grid.params['emailUIAction'] = 'searchAdvanced';
3770                 SE.grid.params['mbox'] = app_strings.LBL_EMAIL_SEARCH_RESULTS_TITLE;
3771                 var accountListSearch = document.getElementById('accountListSearch');
3772                 SE.listView.refreshGrid();
3773         } else {
3774             alert(app_strings.LBL_EMAIL_ERROR_EMPTY);
3775         }
3776     },
3777
3778     /**
3779     *  Validates the search form inputs to ensure all parameters are valid
3780     *  @return bool
3781     */
3782     validateSearchFormInput: function()
3783     {
3784         addToValidate('advancedSearchForm', 'dateTo', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_UNTIL);
3785         addToValidate('advancedSearchForm', 'dateFrom', 'date', false, app_strings.LBL_EMAIL_SEARCH_DATE_FROM);
3786         var dateCheck = check_form('advancedSearchForm');
3787
3788         //If the parent type is selected ensure the user selected a parent_id.
3789         if( SE.composeLayout.isParentTypeAndNameValid('_search') && dateCheck)
3790             return true;
3791         else
3792             return false;
3793     },
3794     /**
3795     *   Toggles the advanced options, either hidding or showing the selection.
3796     */
3797     toggleAdvancedOptions: function()
3798     {
3799         var el = YAHOO.util.Dom.getElementsByClassName('toggleClass','tr', 'advancedSearchTable');
3800
3801         for(var i=0;i<el.length;i++)
3802         {
3803             if(Dom.hasClass(el[i],"toggleClass yui-hidden" ))
3804                 Dom.replaceClass(el[i],"toggleClass yui-hidden", "toggleClass visible-search-option" )
3805             else
3806                 Dom.replaceClass(el[i],"toggleClass visible-search-option","toggleClass yui-hidden" )
3807         }
3808     },
3809     /**
3810      * clears adv search form fields
3811      */
3812     searchClearAdvanced : function() {
3813         var form = document.getElementById('advancedSearchForm');
3814
3815         for(i=0; i<form.elements.length; i++) {
3816             if(form.elements[i].type != 'button') {
3817                 form.elements[i].value = '';
3818             }
3819         }
3820     }
3821 };
3822 ////    END SE.search
3823 //////////////////////////////////////////////////////////////////////////////
3824
3825
3826 //////////////////////////////////////////////////////////////////////////////
3827 ////    SE.settings
3828 SE.settings = {
3829     /******************************************************************************
3830      * USER SIGNATURES calls stolen from Users module
3831      *****************************************************************************/
3832     createSignature : function(record, the_user_id) {
3833         var URL = "index.php?module=Users&action=PopupSignature&sugar_body_only=true";
3834         if(record != "") {
3835             URL += "&record="+record;
3836         }
3837         if(the_user_id != "") {
3838             URL += "&the_user_id="+the_user_id;
3839         }
3840         var windowName = 'email_signature';
3841         var windowFeatures = 'width=800,height=600,resizable=1,scrollbars=1';
3842
3843         var win = window.open(URL, windowName, windowFeatures);
3844         if(win && win.focus) {
3845             // put the focus on the popup if the browser supports the focus() method
3846             win.focus();
3847         }
3848     },
3849
3850     deleteSignature : function() {
3851         if(confirm(app_strings.LBL_EMAIL_CONFIRM_DELETE_SIGNATURE)) {
3852             overlay(app_strings.LBL_EMAIL_IE_DELETE_SIGNATURE, app_strings.LBL_EMAIL_ONE_MOMENT);
3853                 var singature_id = document.getElementById('signature_id').value;
3854                 AjaxObject.startRequest(callbackDeleteSignature, urlStandard + '&emailUIAction=deleteSignature&id=' + singature_id);
3855         } // if
3856     },
3857
3858     saveOptionsGeneral :  function(displayMessage) {
3859         var formObject = document.getElementById('formEmailSettingsGeneral');
3860         if (!SUGAR.collection.prototype.validateTemSet('formEmailSettingsGeneral', 'team_name')) {
3861                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
3862                 return false;
3863         } // if
3864         YAHOO.util.Connect.setForm(formObject);
3865         SE.composeLayout.emailTemplates = null;
3866
3867         AjaxObject.target = 'frameFlex';
3868         AjaxObject.startRequest(callbackSettings, urlStandard + '&emailUIAction=saveSettingsGeneral');
3869
3870         if(displayMessage)
3871             alert(app_strings.LBL_EMAIL_SETTINGS_SAVED);
3872
3873         SE.settings.settingsDialog.hide();
3874     },
3875
3876     /**
3877      * Shows settings container screen
3878      */
3879     showSettings : function() {
3880         if(!SE.settings.settingsDialog) {
3881                 var dlg = SE.settings.settingsDialog = new YAHOO.widget.Dialog("settingsDialog", {
3882                 modal:true,
3883                 visible:false,
3884                 fixedcenter:true,
3885                 draggable: false,
3886                 width:"800px",
3887                                 constraintoviewport: true
3888             });
3889                         dlg.showEvent.subscribe( function (){
3890                                 var el = this.element;
3891                                 var viewH = YAHOO.util.Dom.getViewportHeight();
3892                 if (this.header && el && viewH - 50 < el.clientHeight) {
3893                     var body = this.header.nextElementSibling;
3894                                         body.style.overflow = "auto";
3895                     body.style.height = (viewH - 50) + "px";
3896                 }
3897             }, dlg);
3898                 dlg.setHeader(app_strings.LBL_EMAIL_SETTINGS);
3899                 dlg.setBody('<div id="settingsTabDiv"/>');
3900                 dlg.beforeRenderEvent.subscribe(function() {
3901                         var dd = new YAHOO.util.DDProxy(dlg.element);
3902                         dd.setHandleElId(dlg.header);
3903                         dd.on('endDragEvent', function() {
3904                                 dlg.show();
3905                         });
3906                 }, dlg, true);
3907                 dlg.render();
3908
3909                 var tp = SE.settings.settingsTabs = new YAHOO.widget.TabView("settingsTabDiv");
3910                         var tabContent = Dom.get("tab_general");
3911                 tp.addTab(new YAHOO.widget.Tab({
3912                                 label: app_strings.LBL_EMAIL_SETTINGS_GENERAL,
3913                                 scroll : true,
3914                                 content :  tabContent.innerHTML,
3915                                 id : "generalSettings",
3916                                 active : true
3917                         }));
3918                 tabContent.parentNode.removeChild(tabContent);
3919                 tabContent = Dom.get("tab_accounts");
3920                 var accountTab = new YAHOO.widget.Tab({
3921                                 label: app_strings.LBL_EMAIL_SETTINGS_ACCOUNTS,
3922                                 scroll : true,
3923                                 content : tabContent.innerHTML,
3924                                 id : "accountSettings"
3925                         });
3926                 tp.addTab(accountTab);
3927                 tabContent.parentNode.removeChild(tabContent);
3928
3929                         tp.appendTo(dlg.body);
3930         }
3931
3932         SE.settings.settingsDialog.show();
3933         SE.folders.lazyLoadSettings();
3934         SE.accounts.lazyLoad();
3935     },
3936
3937
3938     lazyLoadRules : function() {
3939         if(false/*!SE.settings.rules*/) {
3940             AjaxObject.startRequest(callbackLoadRules, urlStandard + "&emailUIAction=loadRulesForSettings");
3941         }
3942
3943     }
3944 };
3945 ////    END SE.settings
3946 ///////////////////////////////////////////////////////////////////////////////
3947 })();
3948
3949 /******************************************************************************
3950  * UTILITIES
3951  *****************************************************************************/
3952 function removeHiddenNodes(nodes, grid) {
3953     var el;
3954         for(var i = nodes.length - 1; i > -1; i--) {
3955         el = grid ? grid.getTrEl(nodes[i]) : nodes[i];
3956         if (YAHOO.util.Dom.hasClass(el, 'rowStylenone')) {
3957                 nodes.splice(i,1);
3958        }
3959     }
3960 }
3961
3962 function strpad(val) {
3963     return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
3964 };
3965
3966 function refreshTodos() {
3967     SUGAR.email2.util.clearHiddenFieldValues('emailUIForm');
3968     AjaxObject.target = 'todo';
3969     AjaxObject.startRequest(callback, urlStandard + '&emailUIAction=refreshTodos');
3970 };
3971
3972 /******************************************************************************
3973  * MUST STAY IN GLOBAL NAMESPACE
3974  *****************************************************************************/
3975 function refresh_signature_list(signature_id, signature_name) {
3976     var field=document.getElementById('signature_id');
3977     var bfound=0;
3978     for (var i=0; i < field.options.length; i++) {
3979             if (field.options[i].value == signature_id) {
3980                 if (field.options[i].selected==false) {
3981                     field.options[i].selected=true;
3982                 }
3983                 bfound=1;
3984             }
3985     }
3986     //add item to selection list.
3987     if (bfound == 0) {
3988         var newElement=document.createElement('option');
3989         newElement.text=signature_name;
3990         newElement.value=signature_id;
3991         field.options.add(newElement);
3992         newElement.selected=true;
3993     }
3994
3995     //enable the edit button.
3996     var field1=document.getElementById('edit_sig');
3997     field1.style.visibility="inherit";
3998     var deleteButt = document.getElementById('delete_sig');
3999     deleteButt.style.visibility="inherit";
4000 };
4001
4002 function setDefaultSigId(id) {
4003     var checkbox = document.getElementById("signature_default");
4004     var default_sig = document.getElementById("signatureDefault");
4005
4006     if(checkbox.checked) {
4007         default_sig.value = id;
4008     } else {
4009         default_sig.value = "";
4010     }
4011 };
4012
4013 function setSigEditButtonVisibility() {
4014     var field = document.getElementById('signature_id');
4015     var editButt = document.getElementById('edit_sig');
4016     var deleteButt = document.getElementById('delete_sig');
4017     if(field.value != '') {
4018         editButt.style.visibility = "inherit";
4019         deleteButt.style.visibility = "inherit";
4020     } else {
4021         editButt.style.visibility = "hidden";
4022         deleteButt.style.visibility = "hidden";
4023     }
4024 }// End of File modules/Emails/javascript/EmailUI.js
4025                                 
4026 /*********************************************************************************
4027  * SugarCRM is a customer relationship management program developed by
4028  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4029  * 
4030  * This program is free software; you can redistribute it and/or modify it under
4031  * the terms of the GNU Affero General Public License version 3 as published by the
4032  * Free Software Foundation with the addition of the following permission added
4033  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
4034  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
4035  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
4036  * 
4037  * This program is distributed in the hope that it will be useful, but WITHOUT
4038  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4039  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
4040  * details.
4041  * 
4042  * You should have received a copy of the GNU Affero General Public License along with
4043  * this program; if not, see http://www.gnu.org/licenses or write to the Free
4044  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4045  * 02110-1301 USA.
4046  * 
4047  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
4048  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
4049  * 
4050  * The interactive user interfaces in modified source and object code versions
4051  * of this program must display Appropriate Legal Notices, as required under
4052  * Section 5 of the GNU Affero General Public License version 3.
4053  * 
4054  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
4055  * these Appropriate Legal Notices must retain the display of the "Powered by
4056  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
4057  * technical reasons, the Appropriate Legal Notices must display the words
4058  * "Powered by SugarCRM".
4059  ********************************************************************************/
4060
4061  (function() {
4062         var sw = YAHOO.SUGAR,
4063                 Event = YAHOO.util.Event,
4064                 Connect = YAHOO.util.Connect,
4065             Dom = YAHOO.util.Dom
4066             SE = SUGAR.email2;
4067
4068 ///////////////////////////////////////////////////////////////////////////////
4069 ////    ADDRESS BOOK
4070 SE.addressBook = {
4071     _contactCache : new Array(), // cache of contacts
4072     _dd : new Array(), // filtered list, same format as _contactCache
4073     _ddLists : new Array(), // list of Lists
4074     _dd_mlUsed : new Array(), // contacts in mailing list edit view column1
4075     _dd_mlAvailable : new Array(), // contacts in mailing list edit view column2
4076     clickBubble : true, // hack to get around onclick event bubbling
4077         relatedBeanId : '',
4078         relatedBeanType : '',
4079         idx : 0,
4080
4081     itemSpacing : 'white-space:nowrap; padding:2px;',
4082     reGUID : SE.reGUID,
4083
4084
4085
4086     /**
4087     *  YUI bug fix 2527707.  Causes nested datatable's in <tables> to cause 404 errors whens earching.
4088     */
4089     initFixForDatatableSort: function () {
4090         //Workaround for YUI bug 2527707: http://yuilibrary.com/projects/yui2/ticket/913efafad48ce433199f3e72e4847b18, should be removed when YUI 2.8+ is used
4091         YAHOO.widget.DataTable.prototype.getColumn = function(column) {
4092             var oColumn = this._oColumnSet.getColumn(column);
4093
4094             if(!oColumn) {
4095                 // Validate TD element
4096                 var elCell = column.nodeName.toLowerCase() != "th" ? this.getTdEl(column) : false;
4097                 if(elCell) {
4098                     oColumn = this._oColumnSet.getColumn(elCell.cellIndex);
4099                 }
4100                 // Validate TH element
4101                 else {
4102                     elCell = this.getThEl(column);
4103                     if(elCell) {
4104                         // Find by TH el ID
4105                         var allColumns = this._oColumnSet.flat;
4106                         for(var i=0, len=allColumns.length; i<len; i++) {
4107                             if(allColumns[i].getThEl().id === elCell.id) {
4108                                 oColumn = allColumns[i];
4109                             }
4110                         }
4111                     }
4112                 }
4113             }
4114
4115             return oColumn;
4116         };
4117     },
4118
4119     cancelEdit : function() {
4120         if(this.editContactDialog)
4121             this.editContactDialog.hide();
4122         if(this.editMailingListDialog)
4123             this.editMailingListDialog.hide();
4124     },
4125
4126     /**
4127      * Clears filter form
4128      */
4129     clear : function() {
4130         var t = document.getElementById('contactsFilter');
4131         t.value = '';
4132         this.filter(t);
4133     },
4134
4135     /**
4136      * handle context-menu Compose-to call
4137      * @param string type 'contacts' or 'lists'
4138      */
4139     composeTo : function(type, waited) {
4140         var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id")
4141         if (activePanel.substring(0, 10) != "composeTab") {
4142             SE.composeLayout.c0_composeNewEmail();
4143             setTimeout("SE.addressBook.composeTo('" + type + "', true);");
4144                 SE.contextMenus.contactsContextMenu.hide();
4145             return;
4146         }
4147         var idx = activePanel.substring(10);
4148         var rows = [ ];
4149         var id = '';
4150         // determine if we have a selection to work with
4151         if(type == 'contacts') {
4152             var ids = SE.contactView.getSelectedRows();
4153             for (var i in ids) {
4154                 rows[i] = SE.contactView.getRecord(ids[i]);
4155             }
4156             removeHiddenNodes(rows, SE.contactView);
4157         }
4158                 else { return; }
4159
4160         if(rows.length > 0) {
4161             SE.composeLayout.handleDrop(
4162                 (type == 'contacts') ? SE.contactView : SE.emailListsView,
4163                 null, rows, 'addressTO' + idx );
4164         } else {
4165             alert(app_strings.LBL_EMAIL_MENU_MAKE_SELECTION);
4166         }
4167     },
4168
4169     editContact : function() {
4170         SE.contextMenus.contactsContextMenu.hide();
4171         var element = SE.contactView.getSelectedNodes()[0];
4172         var elementId = "";
4173         if (element.className.indexOf('address-contact') > -1) {
4174             elementId = element.id;
4175         } else if (element.className.indexOf('address-exp-contact') > -1) {
4176             elementId = element.id.substring(2);
4177         }
4178     },
4179
4180
4181     /**
4182      * Filters contact entries based on user input
4183      */
4184     filter : function(inputEl) {
4185         var ret = new Object();
4186         var re = new RegExp(inputEl.value, "gi");
4187
4188         for(var i in this._contactCache) {
4189             if(this._contactCache[i].name.match(re)) {
4190                 ret[i] = this._contactCache[i];
4191             }
4192         }
4193
4194         this.buildContactList(ret);
4195     },
4196
4197     fullForm : function(id, module) {
4198         document.location = "index.php?return_module=Emails&return_action=index&module=" + module + "&action=EditView&record=" + id;
4199     },
4200
4201     /**
4202      * returns a formatted email address from the addressBook cache
4203      */
4204     getFormattedAddress : function(id) {
4205         var o = this._contactCache[id];
4206         var primaryEmail = '';
4207
4208         for(var i=0; i<o.email.length; i++) {
4209             var currentEmail = o.email[i].email_address;
4210
4211             if(o.email[i].primary_address == 1) {
4212                 primaryEmail = o.email[i].email_address;
4213             }
4214         }
4215
4216         var finalEmail = (primaryEmail == "") ? currentEmail : primaryEmail;
4217         var name = new String(o.name);
4218         var finalName = name.replace(/(<([^>]+)>)/ig, "").replace(/&#039;/gi,'\'');
4219         var ret = finalName + " <" + finalEmail.replace(/&#039;/gi,'\'') + ">";
4220
4221         return ret;
4222     },
4223
4224     /**
4225      * Sets up async call to query for matching contacts, users, etc.
4226      */
4227     searchContacts : function() {
4228         var fn = document.getElementById('input_searchField').value;
4229         var pe = document.getElementById('input_searchPerson').value;
4230
4231         var rb = document.getElementById('hasRelatedBean').checked;
4232         if (rb) {
4233                         var idx = this.idx;
4234                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4235                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4236                 this.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4237                 this.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4238         } else {
4239                 this.addressBookDataModel.params['related_bean_id'] = '';
4240         }
4241
4242         this.addressBookDataModel.params['search_field'] = fn;
4243         this.addressBookDataModel.params['person'] = pe;
4244         this.addressBookDataModel.params['emailUIAction'] = 'getAddressSearchResults';
4245         this.grid._oDataSource = this.addressBookDataModel;
4246         this.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(this.addressBookDataModel.params),  this.grid.onDataReturnInitializeTable, this.grid);
4247     },
4248
4249     /**
4250      * Clear Search Crieteria For Addressbook
4251      */
4252     clearAddressBookSearch : function() {
4253         document.getElementById('input_searchField').value = "";
4254         document.getElementById('input_searchPerson').selectedIndex = 0;
4255     },
4256
4257     /**
4258      * Opens modal select window to add contacts to addressbook
4259      */
4260     selectContactsDialogue : function(destId) {
4261         if(!this.contactsDialogue) {
4262                 var dlg = this.contactsDialogue = new YAHOO.widget.Dialog("contactsDialogue", {
4263                 modal:true,
4264                 visible:false,
4265                 draggable: false,
4266                 constraintoviewport: true,
4267                 width   : 980,
4268                 buttons : [{text: app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD, isDefault: true, handler: this.populateEmailAddressFieldsFromResultTable},
4269                            {text: app_strings.LBL_EMAIL_ADDRESS_BOOK_CLEAR, isDefault: true, handler: this.clearAllEmailAddressFieldsFromResultTable} ]
4270             });
4271                 dlg.setHeader(app_strings.LBL_EMAIL_ADDRESS_BOOK_SELECT_TITLE);
4272
4273                 var body = SUGAR.util.getAndRemove("contactsDialogueHTML");
4274                 dlg.setBody(body.innerHTML);
4275                 dlg.renderEvent.subscribe(function() {
4276                 var iev = YAHOO.util.Dom.get("contactsDialogueBody");
4277                 if (iev && !SUGAR.isIE) {
4278                         this.body.style.width = "950px";
4279                 }
4280             }, dlg);
4281
4282
4283                 dlg.beforeRenderEvent.subscribe(function() {
4284                         var dd = new YAHOO.util.DDProxy(dlg.element);
4285                         dd.setHandleElId(dlg.header);
4286                         dd.on('endDragEvent', function() {
4287                                 dlg.show();
4288                         });
4289                 }, dlg, true);
4290                 dlg.render();
4291
4292                 var tp = new YAHOO.widget.TabView("contactsSearchTabs");
4293
4294                 var tabContent = SUGAR.util.getAndRemove("searchForm");
4295                 tp.addTab(new YAHOO.widget.Tab({
4296                                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_TITLE,
4297                                 scroll : true,
4298                                 content : tabContent.innerHTML,
4299                                 id : "addressSearchTab",
4300                                 active : true
4301                         }));
4302
4303                 var addListenerFields = ['input_searchPerson','input_searchField' ]
4304                 YAHOO.util.Event.addListener(addListenerFields,"keydown", function(e){
4305                         if (e.keyCode == 13) {
4306                                 YAHOO.util.Event.stopEvent(e);
4307                                 SUGAR.email2.addressBook.searchContacts();
4308                         }
4309                 });
4310
4311                 this.contactsDialogue.render();
4312                 dlg.center();
4313         }
4314         //Quick Compose does not have an innerLayout component and will always be referenced with ix 0.
4315         if (typeof(SUGAR.email2.innerLayout) == 'undefined')
4316             var idx = 0;
4317         else
4318         {
4319             var activePanel = SUGAR.email2.innerLayout.get("activeTab").get("id");
4320             var idx = activePanel.substring(10);
4321         }
4322         SE.addressBook.idx = idx;
4323
4324                 var relatedBeanId;
4325         if ((hasRelatedBeanId = document.getElementById('data_parent_id' + idx).value) != '') {
4326                 document.getElementById('relatedBeanColumn').style.display = '';
4327                 var relatedBeanName = document.getElementById('data_parent_name' + idx).value;
4328                         var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
4329                         relatedBeanId = document.getElementById('data_parent_id' + idx).value;
4330                         document.getElementById('relatedBeanInfo').innerHTML = ' ' + relatedBeanType + ' <b>' + relatedBeanName + '</b>';
4331                         SE.addressBook.relatedBeanType = relatedBeanType;
4332             } else {
4333                 document.getElementById('relatedBeanColumn').style.display = 'none';
4334                 document.getElementById('hasRelatedBean').checked = false;
4335             }
4336
4337             if (!SE.addressBook.grid)
4338             {
4339                 if (hasRelatedBeanId) {
4340                         document.getElementById('hasRelatedBean').checked = true;
4341                 }
4342                 AddressSearchGridInit();
4343                         SE.addressBook.relatedBeanId = relatedBeanId;
4344             }
4345             else
4346             {
4347                 if (typeof(relatedBeanId) != 'undefined' && relatedBeanId != SE.addressBook.relatedBeanId)
4348                 {
4349                         SE.addressBook.relatedBeanId = relatedBeanId;
4350                         document.getElementById('hasRelatedBean').checked = true;
4351                 }
4352                 if (document.getElementById('hasRelatedBean').checked == true)
4353                 {
4354                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = relatedBeanId;
4355                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = relatedBeanType;
4356                 } else {
4357                         SE.addressBook.addressBookDataModel.params['related_bean_id'] = '';
4358                         SE.addressBook.addressBookDataModel.params['related_bean_type'] = '';
4359                 }
4360                 SE.addressBook.addressBookDataModel.params['search_field'] = document.getElementById('input_searchField').value;;
4361                         SE.addressBook.addressBookDataModel.params['person'] = document.getElementById('input_searchPerson').value;
4362                 SE.addressBook.grid.getDataSource().sendRequest(SUGAR.util.paramsToUrl(SE.addressBook.addressBookDataModel.params),  SE.addressBook.grid.onDataReturnInitializeTable, SE.addressBook.grid);
4363             }
4364
4365             //Remove any lingering rows in the result set table if the module was closed.
4366             SE.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4367             //Repopulate
4368             SE.addressBook.populateResulstTableEmailAddresses();
4369
4370         this.contactsDialogue.show();
4371     },
4372     /**
4373     *  Clear all email addresses from result table.
4374     *
4375     */
4376     clearAllEmailAddressFieldsFromResultTable: function () {
4377         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4378         //Unhighlight any rows currently selected if the emails were cleared.
4379         SUGAR.email2.addressBook.grid.toggleSelectAll(false);
4380         SUGAR.email2.addressBook.grid.reSelectRowsOnRender();
4381     },
4382     /**
4383     *  Take all email address listed in the compose tab To|Cc|Bcc fields and re-populates the
4384     *  results table.  This function is called when the address book is displayed.
4385     */
4386     populateResulstTableEmailAddresses: function () {
4387
4388         var idx = SE.addressBook.idx;
4389         var emailFields = ['to','cc','bcc'];
4390
4391         for(var k=0;k<emailFields.length;k++)
4392         {
4393             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4394             var allEmails = document.getElementById(elKey).value;
4395             if(allEmails == '')
4396                 continue;
4397
4398             var formatedEmails = SE.composeLayout._getEmailArrayFromString(allEmails);
4399
4400                 for (var i=0; i<formatedEmails.length; i++)
4401                 {
4402                     var t_name = formatedEmails[i].name;
4403                     var t_emailAddr = formatedEmails[i].email_address;
4404                     var displayEmail = t_name + ' <' + t_emailAddr + '>';
4405                     if(t_name == '')
4406                         t_name = displayEmail = t_emailAddr;
4407
4408                     var addressType = SE.addressBook.translateAddresType(emailFields[k],true);
4409                 SUGAR.email2.addressBook.gridResults.addRow({'type':addressType,'name':t_name,'email_address': t_emailAddr,
4410                     'display_email_address': displayEmail,'bean_id': -1,'idx' : SE.addressBook.idx});
4411                 }
4412         }
4413     },
4414
4415     /**
4416     * Checks all entries in the result table against a particular email address, returning true
4417     * if the email address is found, false otherwise.
4418     */
4419     doesEmailAdddressExistInResultTable: function(emailAddress)
4420     {
4421         if(trim(emailAddress) == '')
4422             return false;
4423
4424         var emailAddressFound = false;
4425         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4426         for (var i=0; i < contacts.length; i++)
4427         {
4428             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4429             //If we are adding to cc or bcc fields, make them visible.
4430             if(data.email_address == emailAddress)
4431             {
4432                 emailAddressFound = true;
4433                 break;
4434             }
4435         }
4436
4437         return emailAddressFound;
4438     },
4439     /**
4440     *  Takes all email addresses that the users wishes to add from the address book and populates the To
4441     *  fields on the compose tab.
4442     */
4443     populateEmailAddressFieldsFromResultTable: function()
4444     {
4445         //Clear the fields first, all email addresses are stored in the address book
4446         var idx = SE.addressBook.idx;
4447         var emailFields = ['to','cc','bcc'];
4448         for(var k=0;k<emailFields.length;k++)
4449         {
4450             var elKey = 'address' + emailFields[k].toUpperCase() + idx;
4451             document.getElementById(elKey).value = "";
4452         }
4453
4454         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4455         for (var i=0; i < contacts.length; i++)
4456         {
4457             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4458
4459             var addressTypeKey = SE.addressBook.translateAddresType(data.type,false);
4460             //If we are adding to cc or bcc fields, make them visible.
4461             if(addressTypeKey =='cc' || addressTypeKey =='bcc')
4462                 SE.composeLayout.showHiddenAddress(addressTypeKey,data.idx);
4463             //Construct the target id
4464             var target_id = 'address' + addressTypeKey.toUpperCase() + data.idx
4465
4466             var target = document.getElementById(target_id);
4467             target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data.display_email_address);
4468         }
4469
4470         //Delete all rows from the result set table
4471         SUGAR.email2.addressBook.gridResults.deleteRows(0, SUGAR.email2.addressBook.gridResults.getRecordSet().getLength());
4472
4473         //Hide the dialogue
4474         SE.addressBook.contactsDialogue.hide()
4475     },
4476     /**
4477     *  Insert contacts into the result table.
4478     */
4479     insertContactToResultTable : function(event,address_type) {
4480
4481         var contactsDialogue = SE.addressBook.contactsDialogue;
4482         var contacts = SE.addressBook.grid.getSelectedRows();
4483
4484         var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
4485         for (var i = 0; i < rows.length; i++)
4486         {
4487                         if (typeof(rows[i]) != "undefined" && rows[i].getData().checked )
4488                         {
4489                             var recId = SE.addressBook.grid.getRecord(rows[i]).getId();
4490                 SE.addressBook.insertContactRowToResultTable(recId,address_type);
4491                 SUGAR.email2.addressBook.grid.selectRow(rows[i]);
4492                 rows[i].setData("selected",true);
4493                         }
4494         }
4495         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
4496         for (var i = 0; i < checkBoxes.length; i++) {
4497             checkBoxes[i].checked = false;
4498         }
4499     },
4500     /**
4501     *
4502     */
4503     insertContactRowToResultTable : function(rowId, addressType) {
4504         var data = SE.addressBook.grid.getRecord(rowId).getData();
4505         if(SE.addressBook.doesGridResultsEntryExist(data.email) )
4506                 return;
4507         var name = data.name.replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4508         var ea = name + ' <' + data.email.replace(/&#039;/gi,'\'') + '>';
4509         if(addressType == null)
4510             addressType = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,''); //Default to To when using the plus icon.
4511         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});
4512     },
4513     /**
4514     * Remove a row from the gridsResult table.
4515     */
4516     removeRowFromGridResults : function(rowId,emailAddress)
4517     {
4518         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4519         for (var i=0; i < contacts.length; i++)
4520         {
4521             var rec = SE.addressBook.gridResults.getRecord(contacts[i]);
4522             var data = rec.getData();
4523             if(data.email_address == emailAddress)
4524             {
4525                 SUGAR.email2.addressBook.gridResults.deleteRow(rec.getId());
4526                 break;
4527             }
4528         }
4529
4530        SUGAR.email2.addressBook.toggleSearchRowIcon(rowId,true);
4531     },
4532     /**
4533     * Translates between the addressType To|Cc|Bcc labels/keys.
4534     */
4535     translateAddresType: function(addressType,fromKey)
4536     {
4537         var displayTo = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'');
4538         var displayCc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,'');
4539         var displayBcc = app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'');
4540         var mappingObject = {};
4541
4542         if(fromKey)
4543             mappingObject = {'to':displayTo, 'cc':displayCc, 'bcc':displayBcc};
4544         else
4545         {
4546             mappingObject[displayTo] = 'to'; //Cant use object literal with variable variable.
4547             mappingObject[displayCc] = 'cc';
4548             mappingObject[displayBcc] = 'bcc';
4549         }
4550
4551         return typeof(mappingObject[addressType]) != 'undefined' ? mappingObject[addressType] : '';
4552
4553     },
4554     /**
4555     *
4556     */
4557     toggleSearchRowIcon : function(rowId,show)
4558     {
4559         if(show)
4560         {
4561             var idToShow = rowId + '_add_img';
4562             var idToHide = rowId + '_rm_img';
4563         }
4564         else
4565         {
4566             var idToShow = rowId + '_rm_img';
4567             var idToHide = rowId + '_add_img';
4568         }
4569
4570
4571         Dom.addClass(idToHide, "yui-hidden");
4572         Dom.removeClass(idToShow, "yui-hidden");
4573     },
4574     /**
4575     * Determine if an entry has already been added to the grid results table to prevent duplicates.
4576     */
4577     doesGridResultsEntryExist: function(emailAddrs)
4578     {
4579
4580         var contactExists = false;
4581         var contacts = SE.addressBook.gridResults.getRecordSet().getRecords();
4582         for (var i=0; i < contacts.length; i++)
4583         {
4584             var data = SE.addressBook.gridResults.getRecord(contacts[i]).getData();
4585             if(data.email_address == emailAddrs)
4586             {
4587                 contactExists = true;
4588                 break;
4589             }
4590         }
4591         return contactExists;
4592     },
4593
4594     /**
4595      * adds an email address to a string, but first checks if it exists
4596      * @param string concat The string we are appending email addresses to
4597      * @param string addr Email address to add
4598      * @return string
4599      */
4600     smartAddEmailAddressToComposeField : function(concat, addr) {
4601         var re = new RegExp(addr);
4602
4603         if(!concat.match(re)) {
4604             if(concat != "") {
4605                 concat += "; " + addr;
4606             } else {
4607                 concat = addr;
4608             }
4609         }
4610
4611         return concat;
4612     }
4613 };
4614 ////    END ADDRESS BOOK
4615 ///////////////////////////////////////////////////////////////////////////////
4616
4617
4618
4619 ///////////////////////////////////////////////////////////////////////////////
4620 ////    AUTOCOMPLETE
4621 /**
4622  * Auto-complete object
4623  */
4624 SE.autoComplete = {
4625     config : {
4626         delimChar : [";", ","],
4627         useShadow :    false,
4628         useIFrame : false,
4629         typeAhead : true,
4630         prehighlightClassName : "yui-ac-prehighlight",
4631         queryDelay : 0
4632     },
4633     instances : new Array(),
4634
4635     /**
4636      * Parses an addressBook entry looking for primary address.  If not found, it will return the last found address.
4637      * @param object Contact from AddressBook
4638      * @return string
4639      */
4640     getPrimaryAddress : function(contact) {
4641         var address = app_strings.LBL_EMAIL_ADDRESS_BOOK_NOT_FOUND;
4642
4643         for(var eIndex in contact.email) {
4644             address = contact.email[eIndex].email_address;
4645             if(contact.email[eIndex].primary_address == 1) {
4646                 return contact.email[eIndex].email_address;
4647             }
4648         }
4649         return address;
4650     },
4651
4652
4653     /**
4654      * initializes autocomplete widgets for a given compose view
4655      * @param int idx
4656      */
4657     init : function(idx) {
4658         var ds = new YAHOO.widget.DS_JSArray(this.returnDataSource(SE.addressBook._contactCache), {
4659             "queryMatchContains" : false,
4660             "queryMatchSubset" : true
4661         });
4662
4663         this.instances[idx] = {
4664             to : null,
4665             cc : null,
4666             bcc : null
4667         };
4668
4669
4670         // instantiate the autoComplete widgets
4671         this.instances[idx]['to'] = new YAHOO.widget.AutoComplete('addressTO'+idx, "addressToAC"+idx, ds, this.config);
4672         this.instances[idx]['cc'] = new YAHOO.widget.AutoComplete('addressCC'+idx, "addressCcAC"+idx, ds, this.config);
4673         this.instances[idx]['bcc'] = new YAHOO.widget.AutoComplete('addressBCC'+idx, "addressBccAC"+idx, ds, this.config);
4674
4675         // enable hiding of interfering textareas
4676         this.instances[idx]['to'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4677         this.instances[idx]['cc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4678         this.instances[idx]['bcc'].containerExpandEvent.subscribe(SE.autoComplete.toggleTextareaHide);
4679
4680         // enable reshowing of hidden textareas
4681         this.instances[idx]['to'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4682         this.instances[idx]['cc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4683         this.instances[idx]['bcc'].containerCollapseEvent.subscribe(SE.autoComplete.toggleTextareaShow);
4684
4685         // enable refreshes of contact lists
4686         this.instances[idx]['to'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4687         this.instances[idx]['cc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4688         this.instances[idx]['bcc'].textboxFocusEvent.subscribe(SE.autoComplete.refreshDataSource);
4689     },
4690
4691     refreshDataSource : function(sType, aArgs) {
4692         var textBoxId = aArgs[0].getInputEl().id; // "addressTo0"
4693         var idx;
4694         var refresh = SE.autoComplete.returnDataSource(SE.addressBook._contactCache);
4695
4696         if(textBoxId.indexOf("addressTO") > -1 || textBoxId.indexOf("addressCC") > -1) {
4697             idx = textBoxId.substr(9);
4698         } else {
4699             idx = textBoxId.substr(10);
4700         }
4701
4702         SE.autoComplete.instances[idx]['to'].dataSource.data = refresh;
4703         SE.autoComplete.instances[idx]['cc'].dataSource.data = refresh;
4704         SE.autoComplete.instances[idx]['bcc'].dataSource.data = refresh;
4705     },
4706
4707     /**
4708      * Parses AddressBook entries to return an appropriate DataSource array for YUI.autoComplete
4709      */
4710     returnDataSource : function(contacts) {
4711         var ret = new Array();
4712         for(var id in contacts) {
4713             if (contacts[id].name) {
4714                     var primary = this.getPrimaryAddress(contacts[id]);
4715
4716                     ret[ret.length] = contacts[id].name.replace(/<[\/]*b>/gi, '') + " <" + primary + ">";
4717                     //ret[ret.length] = contacts[id].name + " <" + primary + ">";
4718
4719                     for(var emailIndex in contacts[id].email) {
4720                         ret[ret.length] = contacts[id].email[emailIndex].email_address;
4721                     }
4722             }
4723         }
4724
4725         return ret;
4726     },
4727
4728     /**
4729      * Hides address textareas to prevent autocomplete dropdown from being obscured
4730      */
4731     toggleTextareaHide : function(sType, aArgs) {
4732         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4733         var type = "";
4734         var idx = -1;
4735
4736         if(textBoxId.indexOf("addressTO") > -1) {
4737             type = "to";
4738         } else if(textBoxId.indexOf("addressCC") > -1) {
4739             type = "cc";
4740         }
4741         idx = textBoxId.substr(9);
4742
4743         // follow through if not BCC
4744         if(type != "") {
4745             var cc = document.getElementById("addressCC" + idx);
4746             var bcc = document.getElementById("addressBCC" + idx);
4747
4748             switch(type) {
4749                 case "to":
4750                     cc.style.visibility = 'hidden';
4751                 case "cc":
4752                     bcc.style.visibility = 'hidden';
4753                 break;
4754             }
4755         }
4756     },
4757
4758     /**
4759      * Redisplays the textareas after an address is commited
4760      */
4761     toggleTextareaShow : function(sType, aArgs) {
4762         var textBoxId = aArgs[0]._oTextbox.id; // "addressTo0"
4763         var type = "";
4764         var idx = -1;
4765
4766         if(textBoxId.indexOf("addressTO") > -1) {
4767             type = "to";
4768         } else if(textBoxId.indexOf("addressCC") > -1) {
4769             type = "cc";
4770         }
4771         idx = textBoxId.substr(9);
4772
4773         // follow through if not BCC
4774         if(type != "") {
4775             document.getElementById("addressCC" + idx).style.visibility = 'visible';
4776             document.getElementById("addressBCC" + idx).style.visibility = 'visible';
4777         }
4778     }
4779 };
4780
4781 ////    END AUTOCOMPLETE
4782 ///////////////////////////////////////////////////////////////////////////////
4783
4784 ///////////////////////////////////////////////////////////////////////////////
4785 ////    COMPOSE & SEND
4786 /**
4787  * expands the options sidebar
4788  */
4789 SE.composeLayout = {
4790     currentInstanceId : 0,
4791     ccHidden : true,
4792     bccHidden : true,
4793     outboundAccountErrors : null,
4794     loadedTinyInstances : {}, //Tracks which tinyMCE editors have initalized with html content.
4795
4796     showAddressDetails : function(e) {
4797         var linkElement = document.getElementById("More"+e.id);
4798         var spanElement = document.getElementById("Detail"+e.id);
4799         var emailAddressList = e.value;
4800         if(e.value.length > 96)
4801         {
4802                 var resultArray = SE.composeLayout._getEmailArrayFromString(emailAddressList);
4803             var displayArray = [];
4804                 for (var i=0; i<resultArray.length; i++)
4805                 {
4806                     var t_name = resultArray[i].name;
4807                     var t_emailAddr = resultArray[i].email_address;
4808                     if(t_name == '')
4809                        displayArray.push('<br/>&lt;' + t_emailAddr + '&gt;');
4810                     else
4811                        displayArray.push(t_name + '<br/>&lt;' + t_emailAddr + '&gt;');
4812                 }
4813
4814             var result = displayArray.join('<br/>');
4815                 // Display
4816             linkElement.style.display = "inline";
4817             linkElement.style.height="10px";
4818             linkElement.style.overflow="visible";
4819             spanElement.innerHTML = result;
4820         }
4821         else
4822                 linkElement.style.display = "none";
4823
4824         },
4825
4826    /**
4827     *  Given a string of email address, return an array containing the name portion (if available)
4828     *  and email portion.
4829     */
4830     _getEmailArrayFromString : function (emailAddressList){
4831
4832         var reg = /@.*?;/g;
4833         while ((results = reg.exec(emailAddressList)) != null)
4834         {
4835             orignial = results[0];
4836             parsedResult = results[0].replace(';', ':::::');
4837             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4838         }
4839
4840         reg = /@.*?,/g;
4841         while ((results = reg.exec(emailAddressList)) != null)
4842         {
4843             orignial = results[0];
4844             parsedResult = results[0].replace(',', ':::::');
4845             emailAddressList = emailAddressList.replace (orignial, parsedResult);
4846         }
4847         //Administrator <johndoe@som.com>  ;1@somwhe.com;2@somwherecomplex.com,3@somwherecomplex.com;4@somwherecomplex.com,5@somwherecomplex.com,
4848         var emailArr = emailAddressList.split(":::::");
4849         var resultsArray = [];
4850         var newArr = [];
4851         for (var i=0; i<emailArr.length; i++)
4852         {
4853             var rposition = emailArr[i].indexOf('<');
4854             var lposition = emailArr[i].indexOf('>');
4855
4856             if(trim(emailArr[i]) != '')
4857             {
4858                 if(rposition != -1 && lposition != -1)
4859                 {
4860                     var t_name = emailArr[i].substr(0, rposition-1);
4861                     var t_emailAddr = emailArr[i].substr(rposition+1, (lposition-1 - rposition) );
4862                     resultsArray.push({'name':t_name, 'email_address': t_emailAddr});
4863                 }
4864                 else
4865                 {
4866                     resultsArray.push({'name':'', 'email_address': emailArr[i]});
4867                 }
4868             }
4869         }
4870         return resultsArray;
4871     },
4872     ///////////////////////////////////////////////////////////////////////////
4873     ////    COMPOSE FLOW
4874     /**
4875      * Prepare bucket DIV and yui-ext tab panels
4876      */
4877     _0_yui : function() {
4878         var idx = this.currentInstanceId;
4879
4880         var composeTab = new YAHOO.SUGAR.ClosableTab({
4881                         label: mod_strings.LNK_NEW_SEND_EMAIL,
4882                                 scroll : true,
4883                                 content : "<div id='htmleditordiv" + idx + "'/>",
4884                                 id : "composeTab" + idx,
4885                                 closeMsg: app_strings.LBL_EMAIL_CONFIRM_CLOSE,
4886                                 active : true
4887         }, SE.innerLayout);
4888         SE.innerLayout.addTab(composeTab);
4889
4890         // get template engine with template
4891         if (!SE.composeLayout.composeTemplate) {
4892                 SE.composeLayout.composeTemplate = new YAHOO.SUGAR.Template(SE.templates['compose']);
4893         }
4894
4895         // create Tab inner layout
4896         var composePanel =  this.getComposeLayout();
4897         composePanel.getUnitByPosition("right").collapse();
4898         composePanel.autoSize();
4899
4900     },
4901         /**
4902      * Generate the quick compose layout
4903          * @method getQuickComposeLayout
4904          * @param {Pannel} parentPanel Parent pannel
4905          * @param {Object} o Options
4906          * @return {} none
4907          **/
4908     getQuickComposeLayout : function (parentPanel,o) {
4909          var idx = SE.composeLayout.currentInstanceId;
4910
4911          //Before rendering the parent pannel we need to initalize the grid layout
4912          parentPanel.beforeRenderEvent.subscribe(function() {
4913
4914                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4915                         SE.composeLayout._createComposeLayout(idx);
4916                         SE.composeLayout[idx].set('height', 350);
4917                         SE.composeLayout[idx].render();
4918            });
4919         });
4920
4921          //Wait until the Compose Layout has rendered, then add the
4922          //options tab and perform the tiny initialization.
4923          parentPanel.renderEvent.subscribe(function() {
4924
4925                 YAHOO.util.Event.onAvailable('htmleditordiv' + idx, function() {
4926                 SE.composeLayout._initComposeOptionTabs(idx);
4927                 SE.composeLayout[idx].getUnitByPosition("right").collapse();
4928                 //Initialize tinyMCE
4929                 if (!SUGAR.util.isTouchScreen())
4930                     SE.composeLayout._1_tiny();
4931                 //Init templates and address book
4932                 SE.composeLayout._2_final();
4933
4934             SE.composeLayout.quickCreateComposePackage(o);
4935
4936                 });
4937          });
4938
4939             //Check if we have the div override for the shortcut bar
4940         if(typeof o.menu_id != 'undefined') {
4941                    parentPanel.render(o.menu_id);
4942             } else {
4943                    parentPanel.render(document.body);
4944             }
4945
4946         return SE.composeLayout[idx];
4947     },
4948     /**
4949      * Fill in all fields into the quick compose layout.
4950          * @method quickCreateComposePackage
4951          * @param {Object} o Options
4952          * @return {} none
4953          **/
4954     quickCreateComposePackage: function(o)
4955     {
4956         //If we have a compose package fill in defaults.
4957         if (typeof(o.composePackage) != 'undefined')
4958         {
4959             composePackage = o.composePackage; //Set the compose data object
4960             //Hijack this method called by composePackage as it's not need for quick creates.
4961             SE.composeLayout.c0_composeNewEmail = function(){};
4962             SE.composeLayout.composePackage(); //Fill in defaults.
4963         }
4964     },
4965     getComposeLayout : function() {
4966         var idx = SE.composeLayout.currentInstanceId;
4967
4968         this._createComposeLayout(idx);
4969         SE.composeLayout[idx].render();
4970         this._initComposeOptionTabs(idx);
4971
4972         return SE.composeLayout[idx];
4973         },
4974
4975         /**
4976         *       Create the layout manager for the compose window.
4977         */
4978         _createComposeLayout : function(idx)
4979         {
4980                 SE.composeLayout[idx] = new YAHOO.widget.Layout('htmleditordiv' + idx, {
4981                 parent: SE.complexLayout,
4982                 border:true,
4983             hideOnLayout: true,
4984             height: 400,
4985                         units: [{
4986                                         position: "center",
4987                         animate: false,
4988                         scroll: false,
4989                         split:true,
4990                         body:
4991                                 SE.composeLayout.composeTemplate.exec({
4992                                 'app_strings':app_strings,
4993                                 'mod_strings':mod_strings,
4994                                 'theme': theme,
4995                                 'linkbeans_options' : linkBeans,
4996                                 'idx' : SE.composeLayout.currentInstanceId
4997                                 })
4998                     },{
4999                         position: "right",
5000                                     scroll:true,
5001                                     collapse: true,
5002                                     collapsed: true,
5003                                     resize: true,
5004                                     border:true,
5005                                     animate: false,
5006                                     width:'230',
5007                                     body: "<div class='composeRightTabs' id='composeRightTabs" + idx + "'/>",
5008                                     titlebar: true,
5009                                     split: true,
5010                                     header: app_strings.LBL_EMAIL_OPTIONS
5011                     }]
5012                 });
5013         },
5014
5015         /**
5016         *  Create compose tab which will populate the 'right' container in the compose window.
5017         */
5018         _initComposeOptionTabs : function(idx)
5019         {
5020                 var cTabs = new YAHOO.widget.TabView("composeRightTabs" + idx);
5021                 var tab = new YAHOO.widget.Tab({
5022                                 label: app_strings.LBL_EMAIL_ATTACHMENT,
5023                                 scroll : true,
5024                                 content : SUGAR.util.getAndRemove("divAttachments" + idx).innerHTML,
5025                                 id : "divAttachments" + idx,
5026                                 active : true
5027                         });
5028
5029                 tab.layout = SE.composeLayout[idx];
5030
5031            tab.on("activeChange", function(o){
5032                         if (o.newValue) {
5033                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_ATTACHMENT);
5034                         }
5035                 });
5036
5037                 cTabs.addTab(tab);
5038
5039                 tab = new YAHOO.widget.Tab({
5040                                 label: app_strings.LBL_EMAIL_OPTIONS,
5041                                 scroll : true,
5042                                 content : SUGAR.util.getAndRemove("divOptions" + idx).innerHTML,
5043                                 id : "divOptions" + idx,
5044                                 active : false
5045                         });
5046
5047                 tab.layout = SE.composeLayout[idx];
5048                 tab.on("activeChange", function(o){
5049                         if (o.newValue) {
5050                                 this.layout.getUnitByPosition("right").set("header", app_strings.LBL_EMAIL_OPTIONS);
5051                         }
5052                 });
5053                 cTabs.addTab(tab);
5054
5055                 SE.composeLayout[idx].autoSize = function() {
5056                         var pEl = this.get("element").parentNode.parentNode.parentNode;
5057                         this.set("height", pEl.clientHeight-30);
5058                         this.render();
5059                 }
5060
5061                 SE.composeLayout[idx].rightTabs = cTabs;
5062     },
5063     isParentTypeValid : function(idx) {
5064                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5065                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5066                 if (trim(parentTypeValue) == ""){
5067                         alert(mod_strings.LBL_ERROR_SELECT_MODULE);
5068                         return false;
5069                 } // if
5070                 return true;
5071     },
5072
5073     isParentTypeAndNameValid : function(idx) {
5074                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5075                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5076                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5077                 if ((trim(parentTypeValue) != "" && trim(parentNameValue) == "") ||
5078                         (trim(parentTypeValue) != "" && trim(parentNameValue) != "" && parentIdValue == "")){
5079                                 alert(mod_strings.LBL_ERROR_SELECT_MODULE_SELECT);
5080                         return false;
5081                 } // if
5082                 return true;
5083     },
5084
5085     callopenpopupForEmail2 : function(idx,options) {
5086
5087         var formName = 'emailCompose' + idx;
5088
5089         if(typeof(options) != 'undefined' && typeof(options.form_name) != 'undefined')
5090             formName = options.form_name;
5091
5092                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5093                 var parentNameValue = document.getElementById('data_parent_name' + idx).value;
5094                 if (!SE.composeLayout.isParentTypeValid(idx)) {
5095                         return;
5096                 } // if
5097                 open_popup(document.getElementById('data_parent_type' + idx).value,600,400,'&tree=ProductsProd',true,false,
5098                 {
5099                         call_back_function:"SE.composeLayout.popupAddEmail",
5100                         form_name:formName,
5101                         field_to_name_array:{
5102                                 id:'data_parent_id' + idx,
5103                                 name:'data_parent_name' + idx,
5104                                 email1:'email1'}
5105                 });
5106         },
5107
5108         popupAddEmail : function(o)
5109         {
5110                 var nameKey = "data_parent_name" + SE.composeLayout.currentInstanceId;
5111                 var data = o.name_to_value_array;
5112                 if (typeof (data[nameKey]) != "undefined" && data[nameKey] != ""
5113                         && typeof (data["email1"]) != "undefined" && data["email1"] != "" && data["email1"] != "undefined")
5114         {
5115                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
5116                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, data[nameKey] + "<" + data.email1 + ">");
5117         }
5118                 set_return(o);
5119         },
5120     /**
5121      * Prepare TinyMCE
5122      */
5123     _1_tiny : function() {
5124         var idx = SE.composeLayout.currentInstanceId;
5125         var elId = SE.tinyInstances.currentHtmleditor = 'htmleditor' + idx;
5126         SE.tinyInstances[elId] = { };
5127         SE.tinyInstances[elId].ready = false;
5128         var t = tinyMCE.getInstanceById(elId);
5129
5130         if(typeof(t) == 'undefined')  {
5131             tinyMCE.execCommand('mceAddControl', false, elId);
5132             YAHOO.util.Event.onAvailable(elId + "_parent", function() {
5133                 SE.composeLayout.resizeEditor(idx);
5134                 setTimeout("SUGAR.email2.composeLayout.setSignature('" + idx + "')", 1000);
5135             }, this);
5136         }
5137     },
5138
5139     resizeEditor : function(idx)
5140     {
5141         var cof = Dom.get('composeOverFrame' + idx);
5142         var head = Dom.get('composeHeaderTable' + idx);
5143         var targetHeight = cof.clientHeight - head.clientHeight;
5144         var instance =  tinyMCE.get(SE.tinyInstances.currentHtmleditor);
5145
5146         var parentEl = Dom.get(instance.editorId + '_parent');
5147         var toolbar = Dom.getElementsByClassName("mceFirst", "tr", parentEl)[0];
5148         var contentEl  = instance.contentAreaContainer;
5149         var iFrame = contentEl.firstChild;
5150         var tinMceToolbarOffset = 18;
5151         iFrame.style.height = (targetHeight - toolbar.offsetHeight - tinMceToolbarOffset)  + "px";
5152     },
5153
5154     /**
5155      * Initializes d&d, auto-complete, email templates
5156      */
5157     _2_final : function() {
5158         var idx = SE.composeLayout.currentInstanceId;
5159
5160         if(this.emailTemplates) {
5161             this.setComposeOptions(idx);
5162         } else {
5163             //populate email template cache
5164             AjaxObject.target = '';
5165             AjaxObject.startRequest(callbackComposeCache, urlStandard + "&emailUIAction=fillComposeCache");
5166         }
5167
5168         // handle drop targets for addressBook
5169        var to =  new YAHOO.util.DDTarget('addressTO' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5170        var cc =  new YAHOO.util.DDTarget('addressCC' +idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5171        var bcc = new YAHOO.util.DDTarget('addressBCC'+idx, 'addressBookDD', {notifyDrop:this.handleDrop});
5172        to.notifyDrop = cc.notifyDrop = bcc.notifyDrop = this.handleDrop;
5173
5174         // auto-complete setup
5175         SE.autoComplete.init(idx);
5176
5177         // set focus on to:
5178         document.getElementById("addressTO" + idx).focus();
5179     },
5180
5181         /**
5182      * hide tinyMCE tool bar if send email as plaintext is checked
5183      */
5184     renderTinyMCEToolBar : function (idx, hide) {
5185         if (hide) {
5186                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = 'none';
5187         } else {
5188                 document.getElementById('htmleditor' + idx + '_toolbar1').style.display = '';
5189         }
5190     },
5191
5192     c1_composeEmail : function(isReplyForward, retry) {
5193         if (!retry) {
5194             this._0_yui();
5195         }
5196         if (typeof(tinyMCE) == 'undefined' || typeof(tinyMCE.settings) == 'undefined'){
5197             setTimeout("SE.composeLayout.c1_composeEmail(" + isReplyForward + ", true);", 500);
5198         } else {
5199                 this._1_tiny();
5200                 this._2_final();
5201
5202                 if(isReplyForward) {
5203                     this.replyForwardEmailStage2();
5204                 }
5205         }
5206     },
5207
5208     /**
5209      * takes draft info and prepopulates
5210      */
5211     c0_composeDraft : function() {
5212         this.getNewInstanceId();
5213         inCompose = true;
5214         document.getElementById('_blank').innerHTML = '';
5215         var idx = SE.composeLayout.currentInstanceId;
5216                 SE.composeLayout.draftObject = new Object();
5217                 SE.composeLayout.draftObject.id = idx;
5218                 SE.composeLayout.draftObject.isDraft = true;
5219         SE.composeLayout.currentInstanceId = idx;
5220         SE.tinyInstances.currentHtmleditor = 'htmleditor' + SE.composeLayout.currentInstanceId;
5221         SE.tinyInstances[SE.tinyInstances.currentHtmleditor] = new Object();
5222         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = false;
5223
5224         SE.composeLayout._0_yui();
5225         SE.composeLayout._1_tiny();
5226
5227         // final touches
5228         SE.composeLayout._2_final();
5229
5230         /* Draft-specific final processing. Need a delay to allow Tiny to render before calling setText() */
5231         setTimeout("AjaxObject.handleReplyForwardForDraft(SE.o);", 1000);
5232     },
5233
5234     /**
5235      * Strip & Prep editor hidden fields
5236      */
5237     c0_composeNewEmail : function() {
5238         this.getNewInstanceId();
5239         this.c1_composeEmail(false);
5240     },
5241
5242     /**
5243      * Sends async request to get the compose view.
5244      * Requests come from "reply" or "forwards"
5245      */
5246     c0_replyForwardEmail : function(ieId, uid, mbox, type) {
5247         SE.composeLayout.replyForwardObj = new Object();
5248         SE.composeLayout.replyForwardObj.ieId = ieId;
5249         SE.composeLayout.replyForwardObj.uid = uid;
5250         SE.composeLayout.replyForwardObj.mbox = mbox;
5251         SE.composeLayout.replyForwardObj.type = type;
5252
5253         if(mbox == 'sugar::Emails') {
5254             SE.composeLayout.replyForwardObj.sugarEmail = true;
5255         }
5256
5257         SE.composeLayout.getNewInstanceId();
5258         SE.composeLayout.c1_composeEmail(true);
5259     },
5260     ////    END COMPOSE FLOW
5261     ///////////////////////////////////////////////////////////////////////////
5262
5263     /**
5264      * Called when a contact, email, or mailinglist is dropped
5265      * into one of the compose fields.
5266      */
5267     handleDrop : function (source, event, data, target) {
5268         var nodes;
5269         if (!target) {
5270             target = event.getTarget();
5271             if (data.single) {
5272                 data.nodes = [data.nodes];
5273             }
5274             nodes = data.nodes;
5275         } else {
5276             target = document.getElementById(target);
5277             nodes = data;
5278         }
5279
5280         if (target.id.indexOf('address') > -1) {
5281             // dropped onto email to/cc/bcc field
5282             for(var i in nodes) {
5283                 var node = nodes[i].getData();
5284                 var email = "";
5285                 if (node[1].indexOf('contact') > -1) {
5286                     email = SE.addressBook.getFormattedAddress(node[0]);
5287                 } else if (node[1].indexOf('address-email') > -1){
5288                     email = node[3].replace(/&nbsp;/gi, '');
5289                     email = email.replace('&lt;', '<').replace('&gt;', '>');
5290                     var tr = source.getTrEl(nodes[i]);
5291                     while (tr && !Dom.hasClass(tr, "address-contact")) {
5292                         tr = source.getPreviousTrEl(tr);
5293                     }
5294                     var CID = source.getRecord(tr).getData()[0];
5295                     var o = SE.addressBook._contactCache[CID];
5296                     var name = new String(o.name);
5297                     var finalName = name.replace(/(<([^>]+)>)/ig, "");
5298                     email = finalName + email;
5299                 }
5300                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, email);
5301             }
5302         }
5303     },
5304
5305
5306     /*/////////////////////////////////////////////////////////////////////////////
5307     ///    EMAIL TEMPLATE CODE
5308      */
5309     applyEmailTemplate : function (idx, id) {
5310
5311         //bug #20680
5312         var box_title = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_TITLE;
5313                 var box_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_SHOW_MSG;
5314                 var box_none_msg = mod_strings.LBL_EMAILTEMPLATE_MESSAGE_CLEAR_MSG;
5315
5316                 // id is selected index of email template drop-down
5317                 if(id == '' || id == "0") {
5318                         YAHOO.SUGAR.MessageBox.show({
5319                    title:box_title,
5320                    msg: box_none_msg,
5321                    type: 'confirm',
5322                    fn: function(btn){
5323                                 if(btn=='no'){return;};
5324                                 SUGAR.email2.composeLayout.processNoneResult(idx, id);},
5325                    modal:true,
5326                    scope:this
5327                });
5328                return;
5329                 }
5330
5331                 YAHOO.SUGAR.MessageBox.show({
5332            title:box_title,
5333            msg: box_msg,
5334            type: 'confirm',
5335            fn: function(btn){
5336                         if(btn=='no'){return;};
5337                         SUGAR.email2.composeLayout.processResult(idx, id);},
5338            modal:true,
5339            scope:this
5340        });
5341     },
5342
5343     processNoneResult : function(idx, id) {
5344         var tiny = SE.util.getTiny('htmleditor' + idx);
5345         var tinyHTML = tiny.getContent();
5346         var openTag = '<div><span><span>';
5347         var htmllow = tinyHTML.toLowerCase();
5348         var start = htmllow.indexOf(openTag);
5349                 if (start > -1) {
5350                 tinyHTML = tinyHTML.substr(start);
5351                 tiny.setContent(tinyHTML);
5352                 } else {
5353                 tiny.setContent('');
5354                 }
5355     },
5356
5357         processResult : function(idx , id){
5358         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', this.appendEmailTemplateJSON);
5359
5360         // get attachments if any
5361         AjaxObject.target = '';
5362         AjaxObject.startRequest(callbackLoadAttachments, urlStandard + "&emailUIAction=getTemplateAttachments&parent_id=" + id);
5363     },
5364
5365     appendEmailTemplateJSON : function() {
5366         var idx = SE.composeLayout.currentInstanceId; // post increment
5367
5368         // query based on template, contact_id0,related_to
5369         //jchi 09/10/2008 refix #7743
5370         if(json_objects['email_template_object']['fields']['subject'] != '' ) { // cn: bug 7743, don't stomp populated Subject Line
5371             document.getElementById('emailSubject' + idx).value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
5372         }
5373
5374         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,'"');
5375
5376         // cn: bug 14361 - text-only templates don't fill compose screen
5377         if(text == '') {
5378             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/>");
5379         }
5380
5381         var tiny = SE.util.getTiny('htmleditor' + idx);
5382         var tinyHTML = tiny.getContent();
5383         var openTag = '<div><span><span>';
5384         var closeTag = '</span></span></div>';
5385         var htmllow = tinyHTML.toLowerCase();
5386         var start = htmllow.indexOf(openTag);
5387                 if (start > -1) {
5388                 var htmlPart2 = tinyHTML.substr(start);
5389                 tinyHTML = text + htmlPart2;
5390                 tiny.setContent(tinyHTML);
5391                 } else {
5392                 tiny.setContent(text);
5393                 }
5394     },
5395
5396     /**
5397      * Writes out the signature in the email editor
5398      */
5399     setSignature : function(idx) {
5400         if (!tinyMCE)
5401             return false;
5402         var hide = document.getElementById('setEditor' + idx).checked;
5403         SE.composeLayout.renderTinyMCEToolBar(idx,hide);
5404         //wait for signatures to load before trying to set them
5405         if (!SE.composeLayout.signatures) {
5406             setTimeout("SE.composeLayout.setSignature(" + idx + ");", 1000);
5407                         return;
5408         }
5409
5410         if(idx) {
5411             var sel = document.getElementById('signatures' + idx);
5412         } else {
5413             var sel = document.getElementById('signature_id');
5414             idx = SE.tinyInstances.currentHtmleditor;
5415         }
5416
5417         //Ensure that the tinyMCE html has been rendered.
5418         if(typeof(SE.composeLayout.loadedTinyInstances[idx]) != 'undefined' && SE.composeLayout.loadedTinyInstances[idx] == false) {
5419             setTimeout("SE.composeLayout.setSignature(" + idx + ");",1000);
5420                     return;
5421                 }
5422
5423         var signature = '';
5424
5425         try {
5426             signature = sel.options[sel.selectedIndex].value;
5427         } catch(e) {
5428
5429         }
5430
5431         var openTag = '<div><span><span>';
5432         var closeTag = '</span></span></div>';
5433         var t = SE.util.getTiny('htmleditor' + idx);
5434         //IE 6 Hack
5435         if(typeof(t) != 'undefined')
5436         {
5437             t.contentDocument = t.contentWindow.document;
5438             var html = t.getContent();
5439         }
5440         else
5441             var html = '';
5442
5443         var htmllow = html.toLowerCase();
5444         var start = htmllow.indexOf(openTag);
5445         var end = htmllow.indexOf(closeTag) + closeTag.length;
5446
5447         // selected "none" - remove signature from email
5448         if(signature == '') {
5449             if (start > -1) {
5450                 var htmlPart1 = html.substr(0, start);
5451                 var htmlPart2 = html.substr(end, html.length);
5452
5453                 html = htmlPart1 + htmlPart2;
5454                 t.setContent(html);
5455             }
5456             SE.signatures.lastAttemptedLoad = '';
5457             return false;
5458         }
5459
5460         if(!SE.signatures.lastAttemptedLoad) // lazy load place holder
5461             SE.signatures.lastAttemptedLoad = '';
5462
5463         SE.signatures.lastAttemptedLoad = signature;
5464
5465         if(typeof(SE.signatures[signature]) == 'undefined') {
5466             //lazy load
5467             SE.signatures.lastAttemptedLoad = ''; // reset this flag for recursion
5468             SE.signatures.targetInstance = (idx) ? idx : "";
5469             AjaxObject.target = '';
5470             AjaxObject.startRequest(callbackLoadSignature, urlStandard + "&emailUIAction=getSignature&id="+signature);
5471         } else {
5472             var newSignature = this.prepareSignature(SE.signatures[signature]);
5473
5474             // clear out old signature
5475             if(SE.signatures.lastAttemptedLoad && start > -1) {
5476                 var htmlPart1 = html.substr(0, start);
5477                 var htmlPart2 = html.substr(end, html.length);
5478
5479                 html = htmlPart1 + htmlPart2;
5480             }
5481
5482             // [pre|ap]pend
5483                         start = html.indexOf('<div><hr></div>');
5484             if(SE.userPrefs.signatures.signature_prepend == 'true' && start > -1) {
5485                                 var htmlPart1 = html.substr(0, start);
5486                                 var htmlPart2 = html.substr(start, html.length);
5487                 var newHtml = htmlPart1 + openTag + newSignature + closeTag + htmlPart2;
5488             } else if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
5489                 var newHtml = '<br/>' + openTag + newSignature + closeTag + html;
5490             } else {
5491                 var newHtml = html + openTag + newSignature + closeTag;
5492             }
5493             //tinyMCE.setContent(newHtml);
5494             t.setContent(newHtml);
5495         }
5496     },
5497
5498     prepareSignature : function(str) {
5499         var signature = new String(str);
5500
5501         signature = signature.replace(/&lt;/gi, '<');
5502         signature = signature.replace(/&gt;/gi, '>');
5503
5504         return signature;
5505     },
5506
5507
5508     showAttachmentPanel : function(idx) {
5509         var east = SE.composeLayout[idx].getUnitByPosition("right");
5510         var tabs = SE.composeLayout[idx].rightTabs;
5511         east.expand();
5512         tabs.set("activeTab", tabs.getTab(0));
5513     },
5514
5515     /**
5516      * expands sidebar and displays options panel
5517      */
5518     showOptionsPanel : function(idx) {
5519         var east = SE.composeLayout[idx].getUnitByPosition("right");
5520         var tabs = SE.composeLayout[idx].rightTabs;
5521         east.expand();
5522         tabs.set("activeTab", tabs.getTab(1));
5523     },
5524
5525     /**
5526      * Selects the Contacts tab
5527      */
5528     showContactsPanel : function() {
5529         SE.complexLayout.regions.west.showPanel("contactsTab");
5530     },
5531
5532     /**
5533      * Generates fields for Select Document
5534      */
5535     addDocumentField : function(idx) {
5536         var basket = document.getElementById('addedDocuments' + idx);
5537         if(basket) {
5538             var index = (basket.childNodes.length / 7) - 1;
5539             if(index < 0)
5540                 index = 0;
5541         } else {
5542             index = 0;
5543         }
5544
5545         var test = document.getElementById('documentId' + idx + index);
5546
5547         while(test != null) {
5548             index++;
5549             test = document.getElementById('documentId' + idx + index);
5550         }
5551
5552         var documentCup = document.createElement("div");
5553         documentCup.id = 'documentCup' + idx + index;
5554         documentCup.innerHTML = "<input type='hidden' name='document" + idx + index + "' id='document" + idx + index + "' />" +
5555                 // document id field
5556                 "<input type='hidden' name='documentId" + idx + index + "' id='documentId" + idx + index + "' />" +
5557                 // document name field
5558                 "<input value='' size='15' disabled='true' type='text' name='documentName" + idx + index + "' id='documentName" + idx + index + "' />" +
5559                 // select button
5560                 "<button class='button firstChild' type='button' name='documentSelect" + idx + index + "' id='documentSelect" + idx + index + "'" +
5561                     "onclick='SE.composeLayout.selectDocument(\"" + index + "\");' value='" + app_strings.LBL_EMAIL_SELECT + "'>" +
5562                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-select.png' ></button>" +
5563                 // remove button
5564                 "<button class='button lastChild' type='button' name='documentRemove" + idx + index + "' id='documentRemove" + idx + index + "'" +
5565                     "onclick='SE.composeLayout.deleteDocumentField(\"documentCup" + idx + index + "\");' value='" + app_strings.LBL_EMAIL_REMOVE + "'>" +
5566                  "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=id-ff-clear.png' ></button>" +
5567                 "<br/>";
5568
5569         basket.appendChild(documentCup);
5570         //basket.innerHTML += out;
5571         return index;
5572     },
5573
5574     /**
5575      * Makes async call to save a draft of the email
5576      * @param int Instance index
5577      */
5578     saveDraft : function(tinyInstance) {
5579         this.sendEmail(tinyInstance, true);
5580     },
5581
5582     selectDocument : function(target) {
5583         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
5584         windowName = 'selectDocument';
5585         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
5586
5587         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
5588         if(window.focus) {
5589             // put the focus on the popup if the browser supports the focus() method
5590             win.focus();
5591         }
5592     },
5593
5594     /**
5595      * Modal popup for file attachment dialogue
5596      */
5597     addFileField : function() {
5598         if(!SE.addFileDialog){ // lazy initialize the dialog and only create it once
5599             SE.addFileDialog = new YAHOO.widget.Dialog("addFileDialog", {
5600                 modal:true,
5601                 visible:false,
5602                 fixedcenter:true,
5603                 constraintoviewport: true,
5604                 scroll: true,
5605                 keylisteners : new YAHOO.util.KeyListener(document, { keys:27 }, {
5606                         fn:function(){SE.addFileDialog.hide();}
5607                 })
5608             });
5609             SE.addFileDialog.setHeader(app_strings.LBL_EMAIL_ATTACHMENTS);
5610             SE.addFileDialog.render();
5611            // SE.addFileDialog.addKeyListener(27, , SE.addFileDialog);
5612         }
5613         Dom.removeClass("addFileDialog", "yui-hidden");
5614
5615         SE.addFileDialog.show();
5616     },
5617
5618     /**
5619      * Async upload of file to temp dir
5620      */
5621     uploadAttachment : function() {
5622         if(document.getElementById('email_attachment').value != "") {
5623             var formObject = document.getElementById('uploadAttachment');
5624             YAHOO.util.Connect.setForm(formObject, true, true);
5625             AjaxObject.target = '';
5626             AjaxObject.startRequest(callbackUploadAttachment, null);
5627         } else {
5628             alert(app_strings.LBL_EMAIL_ERROR_NO_FILE);
5629         }
5630     },
5631
5632     /**
5633      * Adds a SugarDocument to an outbound email.  Action occurs in a popup window displaying a ListView from the Documents module
5634      * @param string target in focus compose layout
5635      */
5636     setDocument : function(idx, target, documentId, documentName, docRevId) {
5637         // fields are named/id'd [fieldName][instanceId][index]
5638         var addedDocs = document.getElementById("addedDocuments" + idx);
5639         var docId = document.getElementById('documentId' + idx + target);
5640         var docName = document.getElementById('documentName' + idx + target);
5641         var docRevisionId = document.getElementById('document' + idx + target);
5642         docId.value = documentId;
5643         docName.value = documentName;
5644         docRevisionId.value = docRevId;
5645     },
5646
5647     /**
5648      * Removes the bucket div containing the document input fields
5649      */
5650     deleteDocumentField : function(documentCup) {
5651         var f0 = document.getElementById(documentCup);
5652         f0.parentNode.removeChild(f0);
5653     },
5654
5655     /**
5656      * Removes a Template Attachment field
5657      * @param int
5658      * @param int
5659      */
5660     deleteTemplateAttachmentField : function(idx, index) {
5661         // create not-in-array values for removal filtering
5662         var r = document.getElementById("templateAttachmentsRemove" + idx).value;
5663
5664         if(r != "") {
5665             r += "::";
5666         }
5667
5668         r += document.getElementById('templateAttachmentId' + idx + index).value;
5669         document.getElementById("templateAttachmentsRemove" + idx).value = r;
5670
5671         var target = 'templateAttachmentCup' + idx + index;
5672         d =  document.getElementById(target);
5673         d.parentNode.removeChild(d);
5674     },
5675
5676     /**
5677      * Async removal of uploaded temp file
5678      * @param string index Should be a concatenation of idx and index
5679      * @param string
5680      */
5681     deleteUploadAttachment : function(index, file) {
5682         var d = document.getElementById('email_attachment_bucket' + index);
5683         d.parentNode.removeChild(d);
5684
5685         // make async call to delete cached file
5686         AjaxObject.target = '';
5687         AjaxObject.startRequest(null, urlStandard + "&emailUIAction=removeUploadedAttachment&file="+file);
5688     },
5689
5690     /**
5691      * Attaches files coming from Email Templates
5692      */
5693     addTemplateAttachmentField : function(idx) {
5694         // expose title
5695         document.getElementById('templateAttachmentsTitle' + idx).style.display = 'block';
5696
5697         var basket = document.getElementById('addedTemplateAttachments' + idx);
5698
5699         if(basket) {
5700             var index = basket.childNodes.length;
5701             if(index < 0)
5702                 index = 0;
5703         } else {
5704             index = 0;
5705         }
5706
5707         var out = "<div id='templateAttachmentCup" + idx + index + "'>" +
5708                                 // remove button
5709                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
5710                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteTemplateAttachmentField(\"" +
5711                                         idx + "\",\"" + index + "\");'/>" +
5712                                 // file icon
5713                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " + "align='absmiddle' />" +
5714                                 // templateAttachment field
5715                                 "<input type='hidden' value='" + "' name='templateAttachment" + idx + index + "' id='templateAttachment" + idx + index + "' />" +
5716                                 // docId field
5717                                 "<input type='hidden' value='" + "' name='templateAttachmentId" + idx + index + "' id='templateAttachmentId" + idx + index + "' />" +
5718                                 // file name
5719                                 "<span id='templateAttachmentName"  + idx + index + "'" + ">&nbsp;</span>" +
5720                                 "<br id='br" + index + "></br>" +
5721                                 "<br id='brdoc" + index + "></br>" +
5722                         "</div>";
5723                 basket.innerHTML = basket.innerHTML + out;
5724
5725         return index;
5726     },
5727
5728     /**
5729      * Sends one email via async call
5730      * @param int idx Editor instance ID
5731      * @param bool isDraft
5732      */
5733     sendEmail : function(idx, isDraft) {
5734
5735         //If the outbound account has an error message associate with it, alert the user and refuse to continue.
5736         var obAccountID = document.getElementById('addressFrom' + idx).value;
5737
5738         if( typeof(SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID]) != 'undefined' )
5739         {
5740             overlay(app_strings.LBL_EMAIL_ERROR_DESC, SUGAR.email2.composeLayout.outboundAccountErrors[obAccountID], 'alert');
5741             return false;
5742         }
5743
5744
5745         var form = document.getElementById('emailCompose' + idx);
5746         var composeOptionsFormName = "composeOptionsForm" + idx;
5747         var t = SE.util.getTiny(SE.tinyInstances.currentHtmleditor);
5748         var html = t.getContent();
5749         var subj = document.getElementById('emailSubject' + idx).value;
5750         var to = trim(document.getElementById('addressTO' + idx).value);
5751         var cc = trim(document.getElementById('addressCC' + idx).value);
5752         var bcc = trim(document.getElementById('addressBCC' + idx).value);
5753         var email_id = document.getElementById('email_id' + idx).value;
5754         var composeType = document.getElementById('composeType').value;
5755         var parent_type = document.getElementById("parent_type").value;
5756         var parent_id = document.getElementById("parent_id").value;
5757
5758         var el_uid = document.getElementById("uid");
5759         var uid = (el_uid == null) ? '' : el_uid.value;
5760
5761         var el_ieId = document.getElementById("ieId");
5762         var ieId = (el_ieId == null) ? '' : el_ieId.value;
5763
5764         var el_mbox = document.getElementById("mbox");
5765         var mbox = (el_mbox == null) ? '' : el_mbox.value;
5766
5767         if (!isValidEmail(to) || !isValidEmail(cc) || !isValidEmail(bcc)) {
5768                         alert(app_strings.LBL_EMAIL_COMPOSE_INVALID_ADDRESS);
5769                 return false;
5770         }
5771
5772         if (!SE.composeLayout.isParentTypeAndNameValid(idx)) {
5773                 return;
5774         } // if
5775                 var parentTypeValue = document.getElementById('data_parent_type' + idx).value;
5776                 var parentIdValue = document.getElementById('data_parent_id' + idx).value;
5777         parent_id = parentIdValue;
5778         parent_type = parentTypeValue;
5779
5780         var in_draft = (document.getElementById('type' + idx).value == 'draft') ? true : false;
5781         // baseline viability check
5782
5783         if(to == "" && cc == '' && bcc == '' && !isDraft) {
5784             alert(app_strings.LBL_EMAIL_COMPOSE_ERR_NO_RECIPIENTS);
5785             return false;
5786         } else if(subj == '' && !isDraft) {
5787             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT)) {
5788                 return false;
5789             } else {
5790                 subj = app_strings.LBL_EMAIL_COMPOSE_NO_SUBJECT_LITERAL;
5791             }
5792         } else if(html == '' && !isDraft) {
5793             if(!confirm(app_strings.LBL_EMAIL_COMPOSE_NO_BODY)) {
5794                 return false;
5795             }
5796         }
5797
5798         SE.util.clearHiddenFieldValues('emailCompose' + idx);
5799                 document.getElementById('data_parent_id' + idx).value = parentIdValue;
5800                 var title = (isDraft) ? app_strings.LBL_EMAIL_SAVE_DRAFT : app_strings.LBL_EMAIL_SENDING_EMAIL;
5801         overlay(title, app_strings.LBL_EMAIL_ONE_MOMENT);
5802         html = html.replace(/&lt;/ig, "sugarLessThan");
5803         html = html.replace(/&gt;/ig, "sugarGreaterThan");
5804
5805         form.sendDescription.value = html;
5806         form.sendSubject.value = subj;
5807         form.sendTo.value = to;
5808         form.sendCc.value = cc;
5809         form.sendBcc.value = bcc;
5810         form.email_id.value = email_id;
5811         form.composeType.value = composeType;
5812         form.composeLayoutId.value = 'composeLayout' + idx;
5813         form.setEditor.value = (document.getElementById('setEditor' + idx).checked == false) ? 1 : 0;
5814         form.saveToSugar.value = 1;
5815         form.fromAccount.value = document.getElementById('addressFrom' + idx).value;
5816         form.parent_type.value = parent_type;
5817         form.parent_id.value = parent_id;
5818         form.uid.value = uid;
5819         form.ieId.value = ieId;
5820         form.mbox.value = mbox;
5821
5822         // email attachments
5823         var addedFiles = document.getElementById('addedFiles' + idx);
5824         if(addedFiles) {
5825             for(i=0; i<addedFiles.childNodes.length; i++) {
5826                 var bucket = addedFiles.childNodes[i];
5827
5828                 for(j=0; j<bucket.childNodes.length; j++) {
5829                     var node = bucket.childNodes[j];
5830                     var nName = new String(node.name);
5831
5832                     if(node.type == 'hidden' && nName.match(/email_attachment/)) {
5833                         if(form.attachments.value != '') {
5834                             form.attachments.value += "::";
5835                         }
5836                         form.attachments.value += node.value;
5837                     }
5838                 }
5839             }
5840         }
5841
5842         // sugar documents
5843         var addedDocs = document.getElementById('addedDocuments' + idx);
5844         if(addedDocs) {
5845             for(i=0; i<addedDocs.childNodes.length; i++) {
5846                 var cNode = addedDocs.childNodes[i];
5847                 for(j=0; j<cNode.childNodes.length; j++) {
5848                     var node = cNode.childNodes[j];
5849                     var nName = new String(node.name);
5850                     if(node.type == 'hidden' && nName.match(/documentId/)) {
5851                         if(form.documents.value != '') {
5852                             form.documents.value += "::";
5853                         }
5854                         form.documents.value += node.value;
5855                     }
5856                 }
5857             }
5858         }
5859
5860         // template attachments
5861         var addedTemplateAttachments = document.getElementById('addedTemplateAttachments' + idx);
5862         if(addedTemplateAttachments) {
5863             for(i=0; i<addedTemplateAttachments.childNodes.length; i++) {
5864                 var cNode = addedTemplateAttachments.childNodes[i];
5865                 for(j=0; j<cNode.childNodes.length; j++) {
5866                     var node = cNode.childNodes[j];
5867                     var nName = new String(node.name);
5868                     if(node.type == 'hidden' && nName.match(/templateAttachmentId/)) {
5869                         if(form.templateAttachments.value != "") {
5870                             form.templateAttachments.value += "::";
5871                         }
5872                         form.templateAttachments.value += node.value;
5873                     }
5874                 }
5875             }
5876         }
5877
5878         // remove attachments
5879         form.templateAttachmentsRemove.value = document.getElementById("templateAttachmentsRemove" + idx).value;
5880
5881         YAHOO.util.Connect.setForm(form);
5882
5883         AjaxObject.target = 'frameFlex';
5884
5885         // sending a draft email
5886         if(!isDraft && in_draft) {
5887             // remove row
5888             SE.listView.removeRowByUid(email_id);
5889         }
5890
5891         var sendCallback = (isDraft) ? AjaxObject.composeLayout.callback.saveDraft : callbackSendEmail;
5892         var emailUiAction = (isDraft) ? "&emailUIAction=sendEmail&saveDraft=true" : "&emailUIAction=sendEmail";
5893
5894         AjaxObject.startRequest(sendCallback, urlStandard + emailUiAction);
5895     },
5896
5897     /**
5898      * Handles clicking the email address link from a given view
5899      */
5900     composePackage : function() {
5901         if(composePackage != null) {
5902             SE.composeLayout.c0_composeNewEmail();
5903
5904
5905             if(composePackage.to_email_addrs) {
5906                 document.getElementById("addressTO" + SE.composeLayout.currentInstanceId).value = composePackage.to_email_addrs;
5907             } // if
5908             if (composePackage.subject != null && composePackage.subject.length > 0) {
5909                 document.getElementById("emailSubject" + SE.composeLayout.currentInstanceId).value = composePackage.subject;
5910             }
5911
5912             //If no parent fields are set in the composePackage, ensure they are cleared.
5913             var parentFields = ['parent_type','parent_name','parent_id'];
5914             for(var i=0;i<parentFields.length;i++)
5915             {
5916                 if ( typeof(composePackage[parentFields[i]]) == 'undefined' )
5917                     composePackage[parentFields[i]] = "";
5918             }
5919
5920             document.getElementById("parent_type").value = composePackage.parent_type;
5921             document.getElementById('data_parent_type' + SE.composeLayout.currentInstanceId).value = composePackage.parent_type;
5922             document.getElementById("parent_id").value = composePackage.parent_id;
5923             document.getElementById('data_parent_id' + SE.composeLayout.currentInstanceId).value = composePackage.parent_id;
5924             document.getElementById('data_parent_name' + SE.composeLayout.currentInstanceId).value = composePackage.parent_name;
5925
5926             if(composePackage.email_id != null && composePackage.email_id.length > 0) {
5927                 document.getElementById("email_id" + SE.composeLayout.currentInstanceId).value = composePackage.email_id;
5928             } // if
5929             if (composePackage.body != null && composePackage.body.length > 0) {
5930                         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5931                         SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = false;
5932                         setTimeout("SE.composeLayout.setContentOnThisTiny();", 3000);
5933             } // if
5934             if (composePackage.attachments != null) {
5935                                 SE.composeLayout.loadAttachments(composePackage.attachments);
5936             } // if
5937
5938             if (composePackage.fromAccounts != null && composePackage.fromAccounts.status) {
5939                                 var addressFrom = document.getElementById('addressFrom' + SE.composeLayout.currentInstanceId);
5940                         SE.util.emptySelectOptions(addressFrom);
5941                         var fromAccountOpts = composePackage.fromAccounts.data;
5942                         for(i=0; i<fromAccountOpts.length; i++) {
5943                               var key = fromAccountOpts[i].value;
5944                               var display = fromAccountOpts[i].text;
5945                               var opt = new Option(display, key);
5946                               if (fromAccountOpts[i].selected) {
5947                                 opt.selected = true;
5948                               }
5949                               addressFrom.options.add(opt);
5950                         }
5951
5952             } // if
5953         } // if
5954     },
5955
5956     setContentOnThisTiny : function() {
5957         var tiny = SE.util.getTiny('htmleditor' + SE.composeLayout.currentInstanceId);
5958         var tinyHTML = tiny.getContent();
5959         composePackage.body = decodeURI(encodeURI(composePackage.body));
5960         // cn: bug 14361 - text-only templates don't fill compose screen
5961         if(composePackage.body == '') {
5962             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,'"');
5963         } // if
5964         //Flag determines if we should clear the tiny contents or just append
5965         if (typeof(composePackage.clearBody) != 'undefined' && composePackage.clearBody)
5966             SE.composeLayout.tinyHTML = '';
5967         else
5968             SE.composeLayout.tinyHTML = tinyHTML + composePackage.body;
5969
5970          tiny.setContent(SE.composeLayout.tinyHTML);
5971          //Indicate that the contents has been loaded successfully.
5972          SE.composeLayout.loadedTinyInstances[SE.composeLayout.currentInstanceId] = true;
5973     },
5974     /**
5975      * Confirms closure of a compose screen if "x" is clicked
5976      */
5977     confirmClose : function(panel) {
5978         if(confirm(app_strings.LBL_EMAIL_CONFIRM_CLOSE)) {
5979             SE.composeLayout.closeCompose(panel.id);
5980             return true;
5981         } else {
5982             return false;
5983         }
5984     },
5985
5986     /**
5987      * forces close of a compose screen
5988      */
5989     forceCloseCompose : function(id) {
5990         SE.composeLayout.closeCompose(id);
5991
5992         // handle flow back to originating view
5993         if(composePackage) {
5994             // check if it's a module we need to return to
5995             if(composePackage.return_module && composePackage.return_action && composePackage.return_id) {
5996                 if(confirm(app_strings.LBL_EMAIL_RETURN_TO_VIEW)) {
5997                     var url = "index.php?module=" + composePackage.return_module + "&action=" + composePackage.return_action + "&record=" + composePackage.return_id;
5998                     window.location = url;
5999                 }
6000             }
6001         }
6002     },
6003
6004     /**
6005      * closes the editor that just sent email
6006      * @param string id ID of composeLayout tab
6007      */
6008     closeCompose : function(id) {
6009         // destroy tinyMCE instance
6010         var idx = id.substr(13, id.length);
6011         var instanceId = "htmleditor" + idx;
6012         tinyMCE.execCommand('mceRemoveControl', false, instanceId);
6013
6014         // nullify DOM and namespace values.
6015         inCompose = false;
6016         SE.composeLayout[idx] = null;
6017         SE.tinyInstances[instanceId] = null;
6018         var tabsArray = SE.innerLayout.get("tabs");
6019         for (i = 0 ; i < tabsArray.length ; i++) {
6020                 if (tabsArray[i].get("id") == ('composeTab' + idx)) {
6021                         tabsArray[i].close();
6022                         break;
6023                 }
6024         }
6025         //SE.innerLayout.getTab(idx).close();
6026     },
6027
6028     /**
6029     *  Enable the quick search for the compose relate field or search tab
6030     */
6031     enableQuickSearchRelate: function(idx,overides){
6032
6033         if(typeof overides != 'undefined')
6034         {
6035             var newModuleID = overides['moduleSelectField']; //data_parent_type_search
6036             var newModule = document.getElementById(newModuleID).value;
6037             var formName = overides['formName'];
6038             var fieldName = overides['fieldName'];
6039             var fieldId = overides['fieldId'];
6040             var fullName = formName + "_" + fieldName;
6041             var postBlurFunction = null;
6042         }
6043         else
6044         {
6045             var newModule = document.getElementById('data_parent_type'+idx).value;
6046             var formName = 'emailCompose'+idx;
6047             var fieldName = 'data_parent_name'+idx;
6048             var fieldId = 'data_parent_id'+idx;
6049             var fullName = formName + "_" + fieldName;
6050             var postBlurFunction = "SE.composeLayout.qsAddAddress";
6051         }
6052
6053         if(typeof sqs_objects == 'undefined')
6054             window['sqs_objects'] = new Array;
6055
6056         window['sqs_objects'][fullName] = {
6057             form:formName,
6058                         method:"query",
6059                         modules:[newModule],
6060                         group:"or",
6061             field_list:["name","id", "email1"],populate_list:[fieldName,fieldId],required_list:[fieldId],
6062             conditions:[{name:"name",op:"like_custom",end:"%",value:""}],
6063                         post_onblur_function: postBlurFunction,
6064             order:"name","limit":"30","no_match_text":"No Match"};
6065
6066
6067         if(typeof QSProcessedFieldsArray != 'undefined')
6068                 QSProcessedFieldsArray[fullName] = false;
6069         if (typeof(QSFieldsArray) != 'undefined' && typeof(QSFieldsArray[fullName]) != 'undefined') {
6070                 QSFieldsArray[fullName].destroy();
6071                 delete QSFieldsArray[fullName];
6072         }
6073         if (Dom.get(fullName + "_results")) {
6074                 Dom.get(fullName + "_results").parentNode.removeChild(Dom.get(fullName + "_results"));
6075         }
6076
6077         enableQS(false);
6078     },
6079
6080         qsAddAddress : function(o) {
6081         if (o.name != "" && o.email1 != "")
6082         {
6083                 var target = Dom.get("addressTO" + SE.composeLayout.currentInstanceId);
6084                 target.value = SE.addressBook.smartAddEmailAddressToComposeField(target.value, o.name + "<" + o.email1 + ">");
6085         }
6086     },
6087     /**
6088      * Returns a new instance ID, 0-index
6089      */
6090     getNewInstanceId : function() {
6091         this.currentInstanceId = this.currentInstanceId + 1;
6092         return this.currentInstanceId;
6093     },
6094
6095     /**
6096      * 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.
6097      */
6098     loadAttachments : function(result) {
6099         var idx = SE.composeLayout.currentInstanceId;
6100
6101         if(typeof(result) == 'object') {
6102                 //jchi #20680. Clean the former template attachments;
6103                 var basket = document.getElementById('addedTemplateAttachments' + idx);
6104                         if(basket.innerHTML != ''){
6105                                 confirm(mod_strings.LBL_CHECK_ATTACHMENTS, mod_strings.LBL_HAS_ATTACHMENTS, function(btn){
6106                                         if (btn != 'yes'){
6107                                                 basket.innerHTML = '';
6108                                         }
6109                                 });
6110                         }
6111             for(i in result) {
6112                 if(typeof result[i] == 'object') {
6113                     var index = SE.composeLayout.addTemplateAttachmentField(idx);
6114                     var bean = result[i];
6115                     document.getElementById('templateAttachmentId' + idx + index).value = bean['id'];
6116                     document.getElementById('templateAttachmentName' + idx + index).innerHTML += bean['filename'];
6117                 }
6118             }
6119         }
6120     },
6121
6122     /**
6123      * fills drop-down values for email templates and signatures
6124      */
6125     setComposeOptions : function(idx) {
6126         // send from accounts
6127         var addressFrom = document.getElementById('addressFrom' + idx);
6128
6129         if (addressFrom.options.length <= 0) {
6130                 SE.util.emptySelectOptions(addressFrom);
6131                 var fromAccountOpts = SE.composeLayout.fromAccounts;
6132                 for (id = 0 ; id < fromAccountOpts.length ; id++) {
6133                       var key = fromAccountOpts[id].value;
6134                       var display = fromAccountOpts[id].text;
6135                       var is_default = false;
6136                       if(key == SUGAR.default_inbound_accnt_id)
6137                         is_default = true;
6138                       var opt = new Option(display, key);
6139                       addressFrom.options.add(opt);
6140                       addressFrom.options[id].selected = is_default; //Safari bug new Option(x,y,true) does not work.
6141                 }
6142         }
6143
6144         // email templates
6145         var et = document.getElementById('email_template' + idx);
6146         SE.util.emptySelectOptions(et);
6147
6148         for(var key in this.emailTemplates) { // iterate through assoc array
6149             var display = this.emailTemplates[key];
6150             var opt = new Option(display, key);
6151             et.options.add(opt);
6152         }
6153
6154         // signatures
6155         var sigs = document.getElementById('signatures' + idx);
6156         SE.util.emptySelectOptions(sigs);
6157
6158         for(var key in this.signatures) { // iterate through assoc array
6159             var display = this.signatures[key];
6160             var opt = new Option(display, key);
6161
6162             if(key == SE.userPrefs.signatures.signature_default) {
6163                 opt.selected = true;
6164             }
6165
6166             sigs.options.add(opt);
6167         }
6168
6169         // html/plain email?
6170         var htmlEmail = document.getElementById('setEditor' + idx);
6171         if(SE.userPrefs.emailSettings.sendPlainText == 1) {
6172             htmlEmail.checked = true;
6173         } else {
6174                 htmlEmail.checked = false;
6175         }
6176
6177         SE.tinyInstances[SE.tinyInstances.currentHtmleditor].ready = true;
6178     },
6179
6180     /**
6181      * After compose screen is rendered, async call to get email body from Sugar
6182      */
6183     replyForwardEmailStage2 : function() {
6184         SE.util.clearHiddenFieldValues('emailUIForm');
6185         overlay(app_strings.LBL_EMAIL_RETRIEVING_MESSAGE, app_strings.LBL_EMAIL_ONE_MOMENT);
6186
6187         var ieId = SE.composeLayout.replyForwardObj.ieId;
6188         var uid = SE.composeLayout.replyForwardObj.uid;
6189         var mbox = SE.composeLayout.replyForwardObj.mbox;
6190         var type = SE.composeLayout.replyForwardObj.type;
6191         var idx = SE.composeLayout.currentInstanceId;
6192
6193         var sugarEmail = (SE.composeLayout.replyForwardObj.sugarEmail) ? '&sugarEmail=true' : "";
6194
6195         document.getElementById('emailSubject' + idx).value = type;
6196         document.getElementById('emailUIAction').value = 'composeEmail';
6197         document.getElementById('composeType').value = type;
6198         document.getElementById('ieId').value = ieId;
6199         document.getElementById('uid').value = uid;
6200         document.getElementById('mbox').value = mbox;
6201                 document.getElementById('setEditor' + idx).checked = SE.userPrefs.emailSettings.sendPlainText == 1 ? true : false;
6202         var formObject = document.getElementById('emailUIForm');
6203         YAHOO.util.Connect.setForm(formObject);
6204
6205         var sendType = type;
6206         AjaxObject.startRequest(callbackReplyForward, urlStandard + "&composeType=" + type + sugarEmail);
6207     },
6208
6209     /**
6210     *  Show the hidden cc or bcc fields
6211     */
6212     showHiddenAddress: function(addrType,idx){
6213
6214         Dom.removeClass(addrType+"_tr"+idx, "yui-hidden");
6215         Dom.addClass(addrType+"_span"+idx, "yui-hidden");
6216                 Dom.addClass("bcc_cc_sep"+idx, "yui-hidden");
6217                 this[addrType+'Hidden'+idx] = false;
6218
6219                 //After bcc or cc is added, move options below last addr field
6220                 Dom.insertAfter("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6221
6222                 //If both cc and bcc hidden, remove the empty row containing text.
6223                 if( ( typeof(this['ccHidden'+idx]) != 'undefined' && typeof(this['bccHidden'+idx]) != 'undefined')
6224                            && ( this['ccHidden'+idx]  == false && this['bccHidden'+idx] == false) )
6225                         Dom.addClass("add_addr_options_tr"+idx, "yui-hidden");
6226
6227                 SE.composeLayout.resizeEditor(idx);
6228     },
6229     /**
6230     *  Hide the cc and bcc fields if they were shown.
6231     */
6232     hideHiddenAddresses: function(idx){
6233
6234         var addrTypes = ['cc','bcc'];
6235         for(var i = 0;i<addrTypes.length;i++)
6236         {
6237             Dom.addClass(addrTypes[i] + "_tr"+idx, "yui-hidden");
6238             Dom.removeClass(addrTypes[i] + "_span"+idx, "yui-hidden");
6239             this[addrTypes[i] + 'Hidden'+idx] = true
6240         }
6241
6242         Dom.removeClass("bcc_cc_sep"+idx, "yui-hidden");
6243         Dom.removeClass("add_addr_options_tr"+idx, "yui-hidden");
6244         Dom.insertBefore("add_addr_options_tr"+idx, 'bcc_tr'+idx);
6245     }
6246 };
6247
6248 ////    END SE.composeLayout
6249 ///////////////////////////////////////////////////////////////////////////////
6250 ///////////////////////////////////////////////////////////////////////////////
6251 ////    SE.util
6252 SE.util = {
6253     /**
6254      * Cleans serialized UID lists of duplicates
6255      * @param string
6256      * @return string
6257      */
6258     cleanUids : function(str) {
6259         var seen = new Object();
6260         var clean = "";
6261         var arr = new String(str).split(",");
6262
6263         for(var i=0; i<arr.length; i++) {
6264             if(seen[arr[i]]) {
6265                 continue;
6266             }
6267
6268             clean += (clean != "") ? "," : "";
6269             clean += arr[i];
6270             seen[arr[i]] = true;
6271         }
6272
6273         return clean;
6274     },
6275
6276     /**
6277      * Clears hidden field values
6278      * @param string id ID of form element to clear
6279      */
6280     clearHiddenFieldValues : function(id) {
6281         var form = document.getElementById(id);
6282
6283         for(i=0; i<form.elements.length; i++) {
6284             if(form.elements[i].type == 'hidden') {
6285                 var e = form.elements[i];
6286                 if(e.name != 'action' && e.name != 'module' && e.name != 'to_pdf') {
6287                     e.value = '';
6288                 }
6289             }
6290         }
6291     },
6292
6293     /**
6294      * Reduces a SELECT drop-down to 0 items to prepare for new ones
6295      */
6296     emptySelectOptions : function(el) {
6297         if(el) {
6298             for(i=el.childNodes.length - 1; i >= 0; i--) {
6299                 if(el.childNodes[i]) {
6300                     el.removeChild(el.childNodes[i]);
6301                 }
6302             }
6303         }
6304     },
6305
6306     /**
6307      * Returns the MBOX path in the manner php_imap expects:
6308      * ie: INBOX.DEBUG.test
6309      * @param string str Current serialized value, Home.personal.test.INBOX.DEBUG.test
6310      */
6311     generateMboxPath : function(str) {
6312         var ex = str.split("::");
6313
6314         /* we have a serialized MBOX path */
6315         if(ex.length > 1) {
6316             var start = false;
6317             var ret = '';
6318             for(var i=0; i<ex.length; i++) {
6319                 if(ex[i] == 'INBOX') {
6320                     start = true;
6321                 }
6322
6323                 if(start == true) {
6324                     if(ret != "") {
6325                         ret += ".";
6326                     }
6327                     ret += ex[i];
6328                 }
6329             }
6330         } else {
6331             /* we have a Sugar folder GUID - do nothing */
6332             return str;
6333         }
6334
6335         return ret;
6336     },
6337
6338     /**
6339      * returns a SUGAR GUID by navigating the DOM tree a few moves backwards
6340      * @param HTMLElement el
6341      * @return string GUID of found element or empty on failure
6342      */
6343     getGuidFromElement : function(el) {
6344         var GUID = '';
6345         var iterations = 4;
6346         var passedEl = el;
6347
6348         // upwards
6349         for(var i=0; i<iterations; i++) {
6350             if(el) {
6351                 if(el.id.match(SE.reGUID)) {
6352                     return el.id;
6353                 } else {
6354                     el = el.parentNode;
6355                 }
6356             }
6357         }
6358
6359         return GUID;
6360     },
6361
6362     /**
6363      * Returns the ID value for the current in-focus, active panel (in the innerLayout, not complexLayout)
6364      * @return string
6365      */
6366     getPanelId : function() {
6367         return SE.innerLayout.get("activeTab").id ? SE.innerLayout.get("activeTab").id : "Preview";
6368     },
6369
6370     /**
6371      * wrapper to handle weirdness with IE
6372      * @param string instanceId
6373      * @return tinyMCE Controller object
6374      */
6375     getTiny : function(instanceId) {
6376         if(instanceId == '') {
6377             return null;
6378         }
6379
6380         var t = tinyMCE.getInstanceById(instanceId);
6381
6382         if(this.isIe()) {
6383             this.sleep(200);
6384             YAHOO.util.Event.onContentReady(instanceId, function(t) { return t; });
6385         }
6386         return t;
6387     },
6388
6389     /**
6390      * Simple check for MSIE browser
6391      * @return bool
6392      */
6393     isIe : function() {
6394         var nav = new String(navigator.appVersion);
6395         if(nav.match(/MSIE/)) {
6396             return true;
6397         }
6398         return false;
6399     },
6400
6401     /**
6402      * Recursively removes an element from the DOM
6403      * @param HTMLElement
6404      */
6405     removeElementRecursive : function(el) {
6406         this.emptySelectOptions(el);
6407     },
6408
6409     /**
6410      * Fakes a sleep
6411      * @param int
6412      */
6413     sleep : function(secs) {
6414         setTimeout("void(0);", secs);
6415     },
6416
6417     /**
6418      * Converts a <select> element to an Ext.form.combobox
6419      */
6420      convertSelect : function(select) {
6421        alert('in convertSelect');
6422        if (typeof(select) == "string") {
6423            select = document.getElementById(select);
6424        }
6425      },
6426
6427      findChildNode : function (parent, property, value) {
6428          for (i in parent.children) {
6429                  var child = parent.children[i];
6430                  if (child.data[property] && child.data[property] == value || child[property] && child[property] == value)
6431                          return child;
6432                  var searchChild = SE.util.findChildNode(child, property, value);
6433                  if (searchChild)
6434                          return searchChild;
6435          }
6436          return false;
6437      },
6438
6439      cascadeNodes : function (parent, fn, scope, args) {
6440          for (i in parent.children) {
6441                  var child = parent.children[i];
6442                  var s = scope ? scope : child;
6443                  var a = args ? args : child;
6444                  fn.call(s, a);
6445                  SE.util.cascadeNodes(child, fn, scope, args);
6446          }
6447      }
6448 };
6449
6450
6451 ////    END UTIL
6452 ///////////////////////////////////////////////////////////////////////////////
6453
6454
6455 })();//End namespace// End of File modules/Emails/javascript/EmailUICompose.js
6456                                 
6457 /*********************************************************************************
6458  * SugarCRM is a customer relationship management program developed by
6459  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6460  * 
6461  * This program is free software; you can redistribute it and/or modify it under
6462  * the terms of the GNU Affero General Public License version 3 as published by the
6463  * Free Software Foundation with the addition of the following permission added
6464  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
6465  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
6466  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
6467  * 
6468  * This program is distributed in the hope that it will be useful, but WITHOUT
6469  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
6470  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
6471  * details.
6472  * 
6473  * You should have received a copy of the GNU Affero General Public License along with
6474  * this program; if not, see http://www.gnu.org/licenses or write to the Free
6475  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
6476  * 02110-1301 USA.
6477  * 
6478  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
6479  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
6480  * 
6481  * The interactive user interfaces in modified source and object code versions
6482  * of this program must display Appropriate Legal Notices, as required under
6483  * Section 5 of the GNU Affero General Public License version 3.
6484  * 
6485  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
6486  * these Appropriate Legal Notices must retain the display of the "Powered by
6487  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
6488  * technical reasons, the Appropriate Legal Notices must display the words
6489  * "Powered by SugarCRM".
6490  ********************************************************************************/
6491
6492
6493 if (typeof console == "undefined")
6494         console = { log: function(o) {alert(o)} };
6495
6496 var AjaxObject = {
6497         ret : '',
6498         currentRequestObject : null,
6499         //timeout : 30000, // 30 second timeout default
6500         timeout : 9999999999, // 30 second timeout default
6501         forceAbort : false,
6502         trail : new Array(),
6503
6504         /**
6505          */
6506         _reset : function() {
6507                 this.timeout = 30000;
6508                 this.forceAbort = false;
6509         },
6510
6511         folderRenameCleanup : function() {
6512                 SUGAR.email2.folders.setSugarFolders();
6513         },
6514
6515         fullSyncCleanup : function(o) {
6516                 this.folders.checkMailCleanup(o);
6517                 SUGAR.email2.settings.settingsDialog.hide();
6518         },
6519
6520         /**
6521          */
6522         composeCache : function(o) {
6523                 var idx = SUGAR.email2.composeLayout.currentInstanceId; // post instance increment
6524                 // get email templates and user signatures
6525                 var ret = JSON.parse(o.responseText);
6526
6527                 SUGAR.email2.composeLayout.emailTemplates = ret.emailTemplates;
6528                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6529                 SUGAR.email2.composeLayout.fromAccounts = ret.fromAccounts;
6530
6531                 SUGAR.email2.composeLayout.setComposeOptions(idx);
6532
6533                 //Set the error array so we can notify the user when they try to hit send if any errors
6534                 //are present.  We will also notify them now (after hitting compose button).
6535                 SUGAR.email2.composeLayout.outboundAccountErrors = ret.errorArray;
6536
6537
6538                 //if error element is returning an array, then check the length to make sure we have error messages
6539                 if (typeof(ret.errorArray)=='object' && ret.errorArray instanceof Array && ret.errorArray.length > 0){
6540                         //add error messages for display
6541                         for(i in ret.errorArray)
6542                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6543                 }else if (typeof(ret.errorArray)=='object' && ret.errorArray!=null && ret.errorArray!='' ) {
6544                         //if error element is returning an object, and the object value is not empty or null, then display error message
6545                         for(i in ret.errorArray)
6546                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorArray[i], 'alert');
6547                 }
6548
6549                 //YUI bug with IE6 - Wont restore visibility property for nested select elements.
6550                 if(SUGAR.isIE) {
6551                         var overlayPanel = YAHOO.SUGAR.MessageBox.panel;
6552                         if(overlayPanel) {
6553                           overlayPanel.subscribe('hide',function() { YAHOO.util.Dom.setStyle('addressFrom' + idx,'visibility','');});
6554                         }
6555                 }
6556         },
6557
6558
6559         handleDeleteSignature : function(o) {
6560                 hideOverlay();
6561                 var ret = JSON.parse(o.responseText);
6562                 SUGAR.email2.composeLayout.signatures = ret.signatures;
6563         var field = document.getElementById('signature_id');
6564                 SUGAR.email2.util.emptySelectOptions(field);
6565
6566                 for(var i in ret.signatures) { // iterate through assoc array
6567                         var opt = new Option(ret.signatures[i], i);
6568                         field.options.add(opt);
6569                 }
6570                 setSigEditButtonVisibility();
6571         },
6572
6573         /**
6574          */
6575         handleDeleteReturn : function(o) {
6576                 // force refresh ListView
6577                 hideOverlay();
6578                 if(document.getElementById('focusEmailMbox')) {
6579                         YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(document.getElementById('focusEmailMbox').innerHTML);
6580                 }
6581
6582                 // need to display success message before calling next async call?
6583                 document.getElementById(this.target).innerHTML = o.responseText;
6584         },
6585
6586         /**
6587          */
6588     handleFailure : function(o) {
6589                 // Failure handler
6590                 overlay('Exception occurred...', o.statusText, 'alert');
6591         },
6592
6593         handleReplyForward : function(o) {
6594                 var a = JSON.parse(o.responseText);
6595                 globalA = a;
6596                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6597
6598                 document.getElementById('email_id' + idx).value = a.uid;
6599                 document.getElementById('emailSubject' + idx).value = a.name;
6600                 document.getElementById('addressTO' + idx).value = a.from;
6601                 document.getElementById('uid' + idx).value = a.uid;
6602                 if(a.cc) {
6603                         document.getElementById('addressCC' + idx).value = a.cc;
6604                         SE.composeLayout.showHiddenAddress('cc', idx);
6605                 }
6606
6607                 if(a.type) {
6608                         document.getElementById('type' + idx).value = a.type;
6609                 }
6610
6611                 // apply attachment values
6612                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6613
6614                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6615         },
6616
6617         handleReplyForwardForDraft : function(o) {
6618                 var a = JSON.parse(o.responseText);
6619                 globalA = a;
6620                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6621
6622                 document.getElementById('email_id' + idx).value = a.uid;
6623                 document.getElementById('emailSubject' + idx).value = a.name;
6624                 document.getElementById('addressTO' + idx).value = a.to;
6625
6626                 if(a.cc) {
6627                         document.getElementById('addressCC' + idx).value = a.cc;
6628                         SUGAR.email2.composeLayout.showHiddenAddress('cc',idx);
6629                 }
6630
6631                 if(a.bcc) {
6632                         document.getElementById('addressBCC' + idx).value = a.bcc;
6633                         SUGAR.email2.composeLayout.showHiddenAddress('bcc',idx);
6634                 }
6635
6636
6637                 if(a.type) {
6638                         document.getElementById('type' + idx).value = a.type;
6639                 }
6640
6641
6642                 // apply attachment values
6643                 SUGAR.email2.composeLayout.loadAttachments(a.attachments);
6644
6645                 setTimeout("callbackReplyForward.finish(globalA);", 500);
6646         },
6647
6648         /**
6649          */
6650         handleSuccess : function(o) {
6651                 document.getElementById(this.target).innerHTML = o.responseText;
6652                 hideOverlay();
6653         },
6654
6655         /**
6656          */
6657         ieDeleteSuccess : function(o) {
6658                 hideOverlay();
6659
6660                 var ret = JSON.parse(o.responseText);
6661
6662                 SUGAR.email2.accounts.refreshInboundAccountTable();
6663                 alert(app_strings.LBL_EMAIL_IE_DELETE_SUCCESSFUL);
6664                 SUGAR.email2.accounts.rebuildFolderList();
6665
6666         },
6667
6668         /**
6669          */
6670         ieSaveSuccess : function(o) {
6671                 document.getElementById('saveButton').disabled = false;
6672                 var a = JSON.parse(o.responseText);
6673                 if (a) {
6674                         if(a.error) {
6675                                 overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_CHECK_IE_SETTINGS, 'alert');
6676                                 SUGAR.email2.accounts.ieAccountError(SUGAR.email2.accounts.errorStyle);
6677                         } else {
6678                                 resp = JSON.parse(o.responseText);
6679                                 SUGAR.email2.accounts.refreshInboundAccountTable();
6680                                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6681                                 SUGAR.email2.folders.startEmailCheckOneAccount(resp.id, true);
6682                                 SUGAR.email2.accounts.inboundAccountEditDialog.hide();
6683                         }
6684                 } else {
6685                      hideOverlay();
6686                      overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_SAVE_ACCOUNT, 'alert');
6687                 }
6688
6689         },
6690
6691         /**
6692          */
6693         loadAttachments : function(o) {
6694                 var result = JSON.parse(o.responseText);
6695
6696                 SUGAR.email2.composeLayout.loadAttachments(result);
6697         },
6698
6699         /**
6700          */
6701         loadSignature : function(o) {
6702                 var ret = JSON.parse(o.responseText);
6703                 SUGAR.email2.signatures[ret.id] = ret.signature_html;
6704                 SUGAR.email2.composeLayout.setSignature(SUGAR.email2.signatures.targetInstance);
6705         },
6706
6707         /**
6708          * Follow up to mark email read|unread|flagged
6709          */
6710         markEmailCleanup : function(o) {
6711                 var ret = JSON.parse(o.responseText);
6712                 if (!ret['status']) {
6713                 hideOverlay();
6714                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret['message'], 'alert');
6715                 } else {
6716                         SUGAR.email2.contextMenus.markEmailCleanup();
6717                 } // else
6718         },
6719
6720         /**
6721          */
6722         rebuildShowFolders : function(o) {
6723                 var t = JSON.parse(o.responseText);
6724                 var show = document.getElementById('ieAccountListShow');
6725
6726                 SUGAR.email2.util.emptySelectOptions(show);
6727
6728                 for(i=0; i<t.length; i++) { // iterate through assoc array
6729                         var opt = new Option(t[i].text, t[i].value, t[i].selected);
6730                         opt.selected = t[i].selected;
6731                         show.options.add(opt);
6732                 }
6733
6734                 SUGAR.email2.accounts.renderTree();
6735         },
6736         /**
6737          */
6738         saveListViewSortOrderPart2 : function() {
6739                 // create the JSON string the func expects
6740                 focusFolderPath = '[ "Home", "' + ieName + '"';
6741
6742                 var f = new String(focusFolder);
6743                 var fEx = f.split('.');
6744
6745                 for(i=0; i<fEx.length; i++) {
6746                         focusFolderPath += ', "' + fEx[i] +'"'
6747                 }
6748
6749                 focusFolderPath += ']';
6750
6751                 YAHOO.namespace('frameFolders').selectednode = SUGAR.email2.folders.getNodeFromMboxPath(focusFolderPath);
6752                 SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, ieId, 'true');
6753         },
6754
6755         /**
6756          *
6757          */
6758         sendEmailCleanUp : function(o) {
6759                 hideOverlay();
6760                 var ret = JSON.parse(o.responseText);
6761                 if (ret) {
6762                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
6763                   //SUGAR.email2.addressBook.showContactMatches(ret.possibleMatches);
6764                 } else if (o.responseText) {
6765                   overlay(mod_strings.LBL_SEND_EMAIL_FAIL_TITLE, o.responseText, 'alert');
6766                 }
6767
6768                 if (typeof(SE.grid) != 'undefined')
6769                         SE.listView.refreshGrid();
6770                 //Disabled while address book is disabled
6771
6772                 //If this call back was initiated by quick compose from a Detail View page, refresh the
6773                 //history subpanel.  If it was initiated by quickcreate from shortcut bar, then
6774                 //close the shortcut bar menu
6775                 if ( (typeof(action_sugar_grp1) != 'undefined')) {
6776                         if(action_sugar_grp1 == 'DetailView') {
6777                                 showSubPanel('history',null,true);
6778                         } else if(action_sugar_grp1 == 'quickcreate') {
6779                                 closeEmailOverlay();
6780                         }
6781                 }
6782
6783         },
6784
6785         ieSendSuccess : function(o) {
6786                 hideOverlay();
6787                 overlay(app_strings.LBL_EMAIL_TEST_OUTBOUND_SETTINGS_SENT, app_strings.LBL_EMAIL_TEST_NOTIFICATION_SENT, 'plain');
6788         },
6789
6790         /**
6791          */
6792         settingsFolderRefresh : function(o) {
6793                 //SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
6794                 var ret = JSON.parse(o.responseText);
6795                 var user = document.getElementById('userFolders');
6796
6797                 SUGAR.email2.util.emptySelectOptions(user);
6798
6799                 for(i=0; i<ret.userFolders.length; i++) {
6800                         var display = ret.userFolders[i].name;
6801                         var value = ret.userFolders[i].id;
6802                         var selected = (ret.userFolders[i].selected != "") ? true : false;
6803                         var opt = new Option(display, value, selected);
6804                         opt.selected = selected;
6805                         user.options.add(opt);
6806                 }
6807         },
6808
6809         /**
6810          */
6811         startRequest : function(callback, args, forceAbort) {
6812                 if(this.currentRequestObject != null) {
6813                         if(this.forceAbort == true) {
6814                                 YAHOO.util.Connect.abort(this.currentRequestObject, null, false);
6815                         }
6816                 }
6817                 this.currentRequestObject = YAHOO.util.Connect.asyncRequest('POST', "./index.php", callback, args);
6818                 this._reset();
6819         },
6820
6821         requestInProgress : function() {
6822                 return (YAHOO.util.Connect.isCallInProgress(this.currentRequestObject));
6823         },
6824
6825         /**
6826          */
6827         updateFolderSubscriptions : function() {
6828                 SUGAR.email2.folders.lazyLoadSettings(); // refresh view in Settings overlay
6829                 SUGAR.email2.folders.setSugarFolders(1000);// refresh view in TreeView
6830                 hideOverlay();
6831         },
6832
6833         /**
6834          */
6835         updateFrameFolder : function() {
6836                 SUGAR.email2.folders.checkEmailAccounts();
6837         },
6838
6839         /**
6840          */
6841         updateUserPrefs : function(o) {
6842                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
6843                 SUGAR.email2.folders.startCheckTimer(); // starts the auto-check interval
6844         },
6845
6846         /**
6847          */
6848         uploadAttachmentSuccessful : function(o) {
6849                 // clear out field
6850                 document.getElementById('email_attachment').value = '';
6851
6852                 var ret = JSON.parse(o.responseText);
6853                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
6854                 var overall = document.getElementById('addedFiles' + idx);
6855                 var index = overall.childNodes.length;
6856                 var out =
6857                         "<div id='email_attachment_bucket" + idx + index + "'>" +
6858                                 // remove button
6859                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=minus.gif' " +
6860                                         "style='cursor:pointer' align='absmiddle' onclick='SUGAR.email2.composeLayout.deleteUploadAttachment(\"" +
6861                                         idx + index + "\",\"" + ret.guid + ret.name + "\");'/>" +
6862                                 // file icon
6863                                 "<img src='index.php?entryPoint=getImage&themeName=" + SUGAR.themes.theme_name + "&imageName=attachment.gif' " +
6864                                         "id='email_attachmentImage'" + idx + index + "align='absmiddle' />" +
6865                                 // hidden id field
6866                                 "<input type='hidden' value='" + ret.guid + ret.name + "' name='email_attachment" + index + "' id='email_attachment" + idx + index + "' />" +
6867                                 // file name
6868                                 ((ret.nameForDisplay != null) ? ret.nameForDisplay + "&nbsp;" : ret.name + "&nbsp;") +
6869                                 "<br/>" +
6870                         "</div>";
6871                 overall.innerHTML += out;
6872                 if(SUGAR.email2.util.isIe()) {
6873                         document.getElementById('addedFiles' + idx).innerHTML = document.getElementById('addedFiles' + idx).innerHTML;
6874                 }
6875
6876                 // hide popup
6877                 SUGAR.email2.addFileDialog.hide();
6878                 // focus attachments
6879                 SUGAR.email2.composeLayout.showAttachmentPanel(idx);
6880         }
6881 };
6882
6883
6884 ///////////////////////////////////////////////////////////////////////////
6885 ////    PER MODULE CALLBACK OBJECTS
6886 AjaxObject.accounts = {
6887         saveOutboundCleanup : function(o) {
6888                 SUGAR.email2.accounts.refreshOuboundAccountTable();
6889                 SUGAR.email2.accounts.outboundDialog.hide();
6890                 var id = o.responseText;
6891                 SUGAR.email2.accounts.newAddedOutboundId = id;
6892                 },
6893         saveDefaultOutboundCleanup: function(o){
6894
6895         },
6896         callbackEditOutbound : {
6897                 success : function(o)
6898                 {
6899                         var ret = JSON.parse(o.responseText);
6900                         // show overlay
6901                         SUGAR.email2.accounts.showAddSmtp();
6902
6903                         // fill values
6904                         document.getElementById("mail_id").value = ret.id;
6905                         document.getElementById("type").value = ret.type;
6906                         document.getElementById("mail_sendtype").value = ret.mail_sendtype;
6907                         document.getElementById("mail_name").value = ret.name;
6908                         document.getElementById("mail_smtpserver").value = ret.mail_smtpserver;
6909                         document.getElementById("outboundEmailForm").mail_smtptype.value = ret.mail_smtptype;
6910                         document.getElementById("mail_smtpport").value = ret.mail_smtpport;
6911                         document.getElementById("mail_smtpuser").value = ret.mail_smtpuser;
6912                         document.getElementById("mail_smtpauth_req").checked = (ret.mail_smtpauth_req == 1) ? true : false;
6913                         SUGAR.email2.accounts.smtp_authenticate_field_display();
6914                         document.getElementById("mail_smtpssl").options[ret.mail_smtpssl].selected = true;
6915
6916             if(ret.type == 'system-override') {
6917                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(true);
6918                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,true);
6919             }
6920             else {
6921                              SUGAR.email2.accounts.toggleOutboundAccountDisabledFields(false);
6922                              SUGAR.email2.accounts.changeEmailScreenDisplay(ret.mail_smtptype,false);
6923             }
6924             SUGAR.util.setEmailPasswordDisplay('mail_smtppass', ret.has_password);
6925
6926                 },
6927                 failure : AjaxObject.handleFailure,
6928                 timeout : AjaxObject.timeout,
6929                 scope   : AjaxObject
6930         },
6931         callbackDeleteOutbound : {
6932                 success : function(o) {
6933                     var ret = JSON.parse(o.responseText);
6934                     if(ret.is_error)
6935                     {
6936                         if(confirm(ret.error_message))
6937                 {
6938                     overlay(app_strings.LBL_EMAIL_IE_DELETE, app_strings.LBL_EMAIL_ONE_MOMENT);
6939                     AjaxObject.startRequest(AjaxObject.accounts.callbackDeleteOutbound, urlStandard + "&emailUIAction=deleteOutbound&confirm=true&outbound_email=" + ret.outbound_email);
6940                 }
6941                 else
6942                     hideOverlay();
6943                     }
6944                     else
6945                     {
6946                              hideOverlay();
6947                              SUGAR.email2.accounts.refreshOuboundAccountTable();
6948                     }
6949                 },
6950
6951                 failure : AjaxObject.handleFailure,
6952                 timeout : AjaxObject.timeout,
6953                 scope   : AjaxObject
6954         },
6955
6956         callbackCheckMailProgress : {
6957            success : function(o) {
6958                if (typeof(SUGAR.email2.accounts.totalMsgCount) == "undefined") {
6959                    SUGAR.email2.accounts.totalMsgCount = -1;
6960                }
6961
6962                //Check for server timeout / errors
6963                var ret = JSON.parse(o.responseText);
6964                var done = false;
6965
6966                if (typeof(o.responseText) == 'undefined' || o.responseText == "" || ret == false) {
6967                    hideOverlay();
6968                    overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
6969                    SUGAR.email2.accounts.totalMsgCount = -1;
6970                //SUGAR.email2.folders.rebuildFolders();
6971                done = true;
6972                }
6973
6974                var currIeId = ret['ieid'];
6975
6976
6977                var serverCount = ret.count;
6978
6979                if (ret['status'] == 'done') {
6980                    for(i=0; i < SUGAR.email2.accounts.ieIds.length; i++) {
6981                        if (i == SUGAR.email2.accounts.ieIds.length - 1) {
6982                            //We are all done
6983                            done = true;
6984                            break;
6985                        } else if (SUGAR.email2.accounts.ieIds[i] == currIeId) {
6986                            //Go to next account
6987                            currIeId = SUGAR.email2.accounts.ieIds[i+1];
6988                            ret.count = 0;
6989                            SUGAR.email2.accounts.totalMsgCount = -1;
6990                            break;
6991                        }
6992                    }
6993                }
6994                else if (ret.mbox && ret.totalcount && ret.count) {
6995                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
6996                    if (ret.count >= ret.totalcount) {
6997                        serverCount = 0;
6998                    }
6999                } else if (SUGAR.email2.accounts.totalMsgCount < 0 && ret.totalcount) {
7000                    SUGAR.email2.accounts.totalMsgCount = ret.totalcount;
7001                } else {
7002                        hideOverlay();
7003                overlay(app_strings.LBL_EMAIL_ERROR_DESC, app_strings.LBL_EMAIL_ERROR_TIMEOUT, 'alert');
7004                SUGAR.email2.accounts.totalMsgCount = -1;
7005                done = true;
7006                    }
7007
7008                if (done) {
7009                    SUGAR.email2.accounts.totalMsgCount = -1;
7010                    hideOverlay();
7011                    SUGAR.email2.folders.rebuildFolders();
7012                    SE.listView.refreshGrid();
7013                } else if (SUGAR.email2.accounts.totalMsgCount < 0) {
7014                YAHOO.SUGAR.MessageBox.updateProgress(0, mod_strings.LBL_CHECKING_ACCOUNT + ' '+ (i + 2) + ' '+ mod_strings.LBL_OF + ' ' + SUGAR.email2.accounts.ieIds.length);
7015                AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7016                                 '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=0&synch=" + ret.synch);
7017            } else {
7018                YAHOO.SUGAR.MessageBox.updateProgress((ret.count / SUGAR.email2.accounts.totalMsgCount) * 100,
7019                    app_strings.LBL_EMAIL_DOWNLOAD_STATUS.replace(/\[\[count\]\]/, ret.count).replace(/\[\[total\]\]/, SUGAR.email2.accounts.totalMsgCount));
7020                    AjaxObject.startRequest(AjaxObject.accounts.callbackCheckMailProgress, urlStandard +
7021                    '&emailUIAction=checkEmailProgress&ieId=' + currIeId + "&currentCount=" + serverCount +
7022                    '&mbox=' + ret.mbox + '&synch=' + ret.synch + '&totalcount=' + SUGAR.email2.accounts.totalMsgCount);
7023                }
7024            },
7025            failure : AjaxObject.handleFailure,
7026        timeout : AjaxObject.timeout,
7027        scope   : AjaxObject
7028         }
7029 };
7030
7031 ///////////////////////////////////////////////////////////////////////////////
7032 ////    COMPOSE LAYOUT
7033 AjaxObject.composeLayout = {
7034         /**
7035          * Populates the record id
7036          */
7037         saveDraftCleanup : function(o) {
7038                 hideOverlay();
7039                 var ret = JSON.parse(o.responseText);
7040                 if(ret)
7041                   SUGAR.email2.composeLayout.forceCloseCompose(ret.composeLayoutId);
7042                 else if (o.responseText)
7043                   overlay(mod_strings.LBL_ERROR_SAVING_DRAFT, o.responseText, 'alert');
7044         }
7045 };
7046
7047 AjaxObject.composeLayout.callback = {
7048         saveDraft : {
7049                 success : AjaxObject.composeLayout.saveDraftCleanup,
7050                 failure : AjaxObject.handleFailure,
7051                 timeout : AjaxObject.timeout,
7052                 scope   : AjaxObject
7053         }
7054 };
7055
7056 AjaxObject.detailView = {
7057         /**
7058          * Pops-up a printable view of an email
7059          */
7060         displayPrintable : function(o) {
7061                 var ret = JSON.parse(o.responseText);
7062                 var displayTemplate = new YAHOO.SUGAR.Template(SUGAR.email2.templates['viewPrintable']);
7063                 // 2 below must be in global context
7064                 meta = ret.meta;
7065                 meta['panelId'] = SUGAR.email2.util.getPanelId();
7066                 email = ret.meta.email;
7067                 if (typeof(email.cc) == 'undefined') {
7068                   email.cc = "";
7069                 }
7070
7071                 var out = displayTemplate.exec({
7072                         'app_strings'   : app_strings,
7073                         'theme'                 : theme,
7074                         'idx'                   : 'Preview',
7075                         'meta'                  : meta,
7076                         'email'                 : meta.email
7077                 });
7078
7079                 // open popup window
7080                 var popup = window.open('modules/Emails/templates/_blank.html', 'printwin' ,
7081                     'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
7082
7083                 popup.document.write(out);
7084                 popup.document.close();
7085         },
7086
7087         /**
7088          * Takes formatted response and creates a modal pop-over containing a title and content
7089          */
7090         displayView : function(o) {
7091                 var SED = SUGAR.email2.detailView;
7092                 var ret = JSON.parse(o.responseText);
7093
7094                 if(!SED.viewDialog) {
7095                         SED.viewDialog = new YAHOO.widget.Dialog("viewDialog", {
7096                                 modal:true,
7097                 visible:true,
7098                 fixedcenter:true,
7099                 constraintoviewport: true,
7100                                 shadow  : true
7101                         });
7102             SED.viewDialog.renderEvent.subscribe(function() {
7103                 var content = this.body.firstChild;
7104                 var viewH = YAHOO.util.Dom.getViewportHeight();
7105                 if (content) {
7106                         this.body.style.overflow = "auto";
7107                         this.body.style.width = "800px";
7108                         this.body.style.height = (viewH - 75 > content.clientHeight ? (content.clientHeight) : (viewH - 75)) + "px";
7109                 }
7110             }, SED.viewDialog);
7111                 } // end lazy load
7112                 SED.viewDialog.setHeader(ret.title);
7113                 SED.viewDialog.setBody(ret.html);
7114                 SED.viewDialog.render();
7115                 SED.viewDialog.show();
7116         },
7117
7118         /**
7119          * Generates a modal popup to populate with the contents of bean's full EditView
7120          */
7121         showQuickCreateForm : function(o) {
7122                 var SED = SUGAR.email2.detailView;
7123                 var ret = JSON.parse(o.responseText);
7124
7125                 if(!SED.quickCreateDialog) {
7126                         SED.quickCreateDialog = new YAHOO.widget.Dialog("quickCreate", {
7127                                 modal:true,
7128                                 visible:true,
7129                 fixedcenter:true,
7130                 constraintoviewport: true,
7131                                 shadow  : true
7132                         });
7133
7134             SED.quickCreateDialog.renderEvent.subscribe(function() {
7135                 var viewH = YAHOO.util.Dom.getViewportHeight();
7136                 var contH = 0;
7137                 for (var i in this.body.childNodes) {
7138                         if (this.body.childNodes[i].clientHeight) {
7139                                 contH += this.body.childNodes[i].clientHeight;
7140                         } else if (this.body.childNodes[i].offsetHeight) {
7141                                 contH += this.body.childNodes[i].offsetHeight;
7142                         } // if
7143                 }
7144                         this.body.style.width = "800px";
7145                         this.body.style.height = (viewH - 75 > contH ? (contH + 10) : (viewH - 75)) + "px";
7146                         this.body.style.overflow = "auto";
7147             }, SED.quickCreateDialog);
7148
7149             SED.quickCreateDialog.hideEvent.subscribe(function(){
7150                                 var qsFields = YAHOO.util.Dom.getElementsByClassName('.sqsEnabled', null, this.body);
7151                                 /*for(var qsField in qsFields){
7152                                         if (typeof QSFieldsArray[qsFields[qsField].id] != 'undefined')
7153                                         Ext.getCmp('combobox_'+qsFields[qsField].id).destroy();
7154                                 }*/
7155                         });
7156             SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_QUICK_CREATE);
7157                 } // end lazy load
7158                 if (ret.html) {
7159                         ret.html = ret.html.replace('<script type="text/javascript" src="include/SugarEmailAddress/SugarEmailAddress.js"></script>', "");
7160                 }
7161                 SED.quickCreateDialog.setBody(ret.html ? ret.html : "&nbsp;");
7162                 SED.quickCreateDialog.render();
7163                 SUGAR.util.evalScript(ret.html + '<script language="javascript">enableQS(true);</script>');
7164
7165                 SED.quickCreateDialog.ieId = ret.ieId;
7166                 SED.quickCreateDialog.uid = ret.uid;
7167         SED.quickCreateDialog.mbox = ret.mbox;
7168         SED.quickCreateDialog.qcmodule = ret.module;
7169
7170         SED.quickCreateDialog.show();
7171
7172                 var editForm = document.getElementById('form_EmailQCView_' + ret.module);
7173                 if (editForm) {
7174                   editForm.module.value = 'Emails';
7175                   var count = SUGAR.EmailAddressWidget.count[ret.module] ? SUGAR.EmailAddressWidget.count[ret.module] : 0;
7176                   var tableId = YAHOO.util.Dom.getElementsByClassName('emailaddresses', 'table', editForm)[0].id;
7177                   var instId = ret.module + count;
7178                   SED.quickCreateEmailsToAdd = ret.emailAddress;
7179                   SED.quickCreateEmailCallback = function(instId, tableId) {
7180                           var eaw = SUGAR.EmailAddressWidget.instances[instId];
7181                           if (typeof(eaw) == "undefined")
7182                                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7183                                                 + instId + "','" + tableId + "');", 100);
7184                           eaw.prefillEmailAddresses(tableId, SUGAR.email2.detailView.quickCreateEmailsToAdd);
7185                   }
7186                   window.setTimeout("SUGAR.email2.detailView.quickCreateEmailCallback('"
7187                                         + instId + "','" + tableId + "');", 100);
7188                 }
7189         },
7190
7191         saveQuickCreateForm : function(o) {
7192             hideOverlay();
7193                 SUGAR.email2.detailView.quickCreateDialog.hide();
7194                 validate['EditView'] = [ ];
7195         },
7196
7197         saveQuickCreateFormAndReply : function(o) {
7198             hideOverlay();
7199             var ret = JSON.parse(o.responseText);
7200         SUGAR.email2.detailView.quickCreateDialog.hide();
7201         var qcd = SUGAR.email2.detailView.quickCreateDialog;
7202         var type = (qcd.qcmodule == 'Cases') ? 'replyCase' : 'reply';
7203         if (ret) {
7204             var emailID = ret.id;
7205             SUGAR.email2.composeLayout.c0_replyForwardEmail(null, ret.id, 'sugar::Emails', type);
7206         } else {
7207             SUGAR.email2.composeLayout.c0_replyForwardEmail(qcd.ieId, qcd.uid, qcd.mbox, type);
7208         }
7209         //Cean the validate cache to prevent errors on the next call
7210         validate['EditView'] = [ ];
7211     },
7212
7213         saveQuickCreateFormAndAddToAddressBook : function(o) {
7214            hideOverlay();
7215                 SUGAR.email2.detailView.quickCreateDialog.hide();
7216                 SUGAR.email2.complexLayout.findPanel('contactsTab').show();
7217                 validate['EditView'] = [ ];
7218         },
7219
7220         handleAssignmentDialogAssignAction : function() {
7221
7222
7223             var assign_user_id = window.document.forms['Distribute'].elements['assigned_user_id'].value;
7224
7225             var dist = 'direct';
7226             var users = false;
7227             var rules = false;
7228             var get = "";
7229             var found_teams = false;
7230             var warning_message = mod_strings.LBL_WARN_NO_USERS;
7231             if(!found_teams && assign_user_id == '' )
7232             {
7233                 alert(warning_message);
7234                 return;
7235             }
7236
7237             var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7238             var uids = "";
7239             for(i=0; i<emailUids.length; i++) {
7240                 if(uids != '') {
7241                     uids += app_strings.LBL_EMAIL_DELIMITER;
7242                 }
7243                 uids += emailUids[i];
7244             }
7245
7246             var row = SUGAR.email2.grid.getSelectedRows()[0];
7247             var data = SUGAR.email2.grid.getRecord(row).getData();
7248             var ieid = data.ieId;
7249             var mbox = data.mbox;
7250             AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentAssign&uids=" + uids + "&ieId=" + ieid + "&folder=" + mbox + "&distribute_method=" + dist + "&users=" +assign_user_id + get);
7251             SUGAR.email2.contextMenus.assignToDialogue.hide();
7252             overlay('Assignment', app_strings.LBL_EMAIL_ONE_MOMENT);
7253
7254         },
7255
7256         handleAssignmentDialogDeleteAction : function() {
7257                 // TO pass list of UIDS/emailIds
7258                 var uids = SUGAR.email2.listView.getUidsFromSelection();
7259                 var row = SUGAR.email2.grid.getSelections()[0];
7260                 var ieid = row.data.ieId;
7261             var mbox = row.data.mbox;
7262         AjaxObject.startRequest(callbackAssignmentAction, urlStandard + '&emailUIAction=' + "doAssignmentDelete&uids=" + uids + "&ieId=" + ieId + "&folder=" + mbox);
7263         SUGAR.email2.contextMenus.assignmentDialog.hide();
7264                 overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7265
7266                 // AJAX Call
7267
7268         },
7269
7270         showEmailDetailView : function(o) {
7271         hideOverlay();
7272         var SED = SUGAR.email2.detailView;
7273                 var ret = JSON.parse(o.responseText);
7274
7275                 if(!SED.quickCreateDialog) {
7276                         SED.quickCreateDialog = new YAHOO.widget.Dialog("emailDetailDialog", {
7277                                 modal:true,
7278                                 visible:true,
7279                 //fixedcenter:true,
7280                 constraintoviewport: true,
7281                 draggable: true,
7282                                 autofillheight: "body",
7283                                 shadow  : true
7284                         });
7285                         SED.quickCreateDialog.renderEvent.subscribe(function() {
7286                 var viewHeight = YAHOO.util.Dom.getViewportHeight();
7287                 var contH = 0;
7288                 for (var i in this.body.childNodes) {
7289                         if (this.body.childNodes[i].offsetHeight)
7290                                 contH += this.body.childNodes[i].offsetHeight;
7291                 }
7292                         this.body.style.overflow = "auto";
7293                         this.body.style.width = "800px";
7294                         this.body.style.height = (viewHeight - 75 > contH ? (contH + 10) : (viewHeight - 75)) + "px";
7295                         this.center();
7296             }, SED.quickCreateDialog);
7297                 }
7298                 SED.quickCreateDialog.setHeader(app_strings.LBL_EMAIL_RECORD);
7299                 SED.quickCreateDialog.setBody(ret.html);
7300                 SED.quickCreateDialog.render();
7301         SUGAR.util.evalScript(ret.html);
7302         SED.quickCreateDialog.show();
7303         },
7304
7305         showAssignmentDialogWithData : function(o) {
7306         var SEC = SUGAR.email2.contextMenus;
7307                 hideOverlay();
7308         var ret = JSON.parse(o.responseText);
7309         if (!SEC.assignmentDialog) {
7310                 SEC.assignmentDialog = new YAHOO.widget.Dialog("assignmentDialog", {
7311                         visible:false,
7312                 fixedcenter:true,
7313                 constraintoviewport: true,
7314                         modal   : true
7315                 });
7316                 SEC.assignmentDialog.setBody("");
7317                 SEC.assignmentDialog.setHeader(app_strings.LBL_EMAIL_ASSIGNMENT);
7318                 SEC.assignmentDialog.renderEvent.subscribe(function() {
7319                 var iev = YAHOO.util.Dom.get("Distribute");
7320                 if (iev) {
7321                         this.body.style.width = "700px";
7322                 }
7323             },  SEC.assignmentDialog);
7324                 SEC.assignmentDialog.render();
7325         }
7326         SEC.assignmentDialog.setBody(ret);
7327         SEC.assignmentDialog.render();
7328         validate = [];
7329         SEC.assignmentDialog.show();
7330         SUGAR.util.evalScript(ret);
7331         },
7332
7333         showImportForm : function(o) {
7334                 var SED = SUGAR.email2.detailView;
7335                 var ret = JSON.parse(o.responseText);
7336
7337         document.getElementById('quickCreateContent').innerHTML = "";
7338         hideOverlay();
7339         if (!ret) {
7340             return false;
7341         }
7342
7343         if(!SED.importDialog) {
7344             SED.importDialog = new YAHOO.widget.Dialog("importDialog", {
7345                 modal:true,
7346                 visible:false,
7347                 fixedcenter:true,
7348                 constraintoviewport: true,
7349                 buttons : [{
7350                         text: app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR, isDefault: true, handler: function(){
7351                                 AjaxObject.detailView.getImportAction(SED.importDialog.ret); }
7352                 }]//,
7353                 //scroll : true
7354             });
7355             SED.importDialog.setHeader(app_strings.LBL_EMAIL_IMPORT_SETTINGS);
7356             SED.importDialog.setBody("");
7357             SED.importDialog.hideEvent.subscribe(function(){
7358                 for(var i in QSFieldsArray) {
7359                         if (QSFieldsArray[i] != null && typeof(QSFieldsArray[i]) == "object") {
7360                                 QSFieldsArray[i].destroy();
7361                                 delete QSFieldsArray[i];
7362                         }
7363                         if (QSProcessedFieldsArray[i]) {
7364                                 QSProcessedFieldsArray[i] = false;
7365                         } // if
7366                                 }
7367             });
7368             SED.importDialog.renderEvent.subscribe(function() {
7369                 var iev = YAHOO.util.Dom.get("ImportEditView");
7370                 if (iev) {
7371                         //this.body.style.height = (iev.clientHeight + 10) + "px";
7372                         this.body.style.width = "600px";
7373                 }
7374             }, SED.importDialog);
7375             SED.importDialog.render();
7376         } // end lazy load
7377         SED.importDialog.setBody(ret.html);
7378         SED.importDialog.ret = ret;
7379         SUGAR.util.evalScript(ret.html);
7380         SED.importDialog.render();
7381         validate = [];
7382         SED.importDialog.show();
7383         SED.importDialog.focusFirstButton();
7384     },
7385     getImportAction : function(ret) {
7386         if (!check_form('ImportEditView')) return false;
7387         if (!SUGAR.collection.prototype.validateTemSet('ImportEditView', 'team_name')) {
7388                 alert(mod_strings.LBL_EMAILS_NO_PRIMARY_TEAM_SPECIFIED);
7389                 return false;
7390         } // if
7391                 var get = "";
7392         var editView = document.getElementById('ImportEditView');
7393         if (editView.assigned_user_id != null) {
7394             get = get + "&user_id=" + editView.assigned_user_id.value
7395             //var user_id = editView.assigned_user_id.value;
7396         }
7397         var parent_id = editView.parent_id.value;
7398         var parent_type = editView.parent_type.value;
7399         var row = SUGAR.email2.grid.getSelectedRows()[0];
7400         row = SUGAR.email2.grid.getRecord(row);
7401         var data = row.getData();
7402         var ieId = data.ieId;
7403         var mbox = data.mbox;
7404         var serverDelete = editView.serverDelete.checked;
7405         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7406         var uids = "";
7407         for(i=0; i<emailUids.length; i++) {
7408             if(uids != '') {
7409                 uids += app_strings.LBL_EMAIL_DELIMITER;
7410             }
7411             uids += emailUids[i];
7412         }
7413
7414         var action = 'importEmail&uid=';
7415         if (ret.move) {
7416             action = 'moveEmails';
7417             action = action + '&sourceFolder=' + ret['srcFolder'];
7418             action = action + '&sourceIeId=' + ret['srcIeId'];
7419             action = action + '&destinationFolder=' + ret['dstFolder'];
7420             action = action + '&destinationIeId=' + ret['dstIeId'];
7421             action = action + '&emailUids=';
7422         }
7423         if (action.search(/importEmail/) != -1) {
7424             overlay(app_strings.LBL_EMAIL_IMPORTING_EMAIL, app_strings.LBL_EMAIL_ONE_MOMENT);
7425         } else {
7426             overlay("Moving Email(s)", app_strings.LBL_EMAIL_ONE_MOMENT);
7427         }
7428
7429         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=' + action + uids + "&ieId=" + ieId + "&mbox=" + mbox +
7430         get + "&parent_id=" + parent_id + "&parent_type=" + parent_type + '&delete=' + serverDelete);
7431         SUGAR.email2.detailView.importDialog.hide();
7432         document.getElementById('importDialogContent').innerHTML = "";
7433
7434     },
7435     showRelateForm : function(o) {
7436         var SED = SUGAR.email2.detailView;
7437         var ret = JSON.parse(o.responseText);
7438         document.getElementById('quickCreateContent').innerHTML = "";
7439         hideOverlay();
7440         if (!ret) {
7441             return false;
7442         }
7443         dialog_loaded = true;
7444
7445         if(!SED.relateDialog) {
7446             SED.relateDialog = new YAHOO.widget.Dialog('relateDialog', {
7447                                 modal:true,
7448                                 visible:true,
7449                 fixedcenter:true,
7450                 width: '800px',
7451                 constraintoviewport: true,
7452                                 buttons : [{
7453                         text: app_strings.LBL_EMAIL_RELATE_TO, isDefault: true, handler: function(){
7454                                         if (!check_form('RelateEditView')) return false;
7455                                         var get = "";
7456                         var editView = document.getElementById('RelateEditView');
7457                         var parent_id = editView.parent_id.value;
7458                         var parent_type = editView.parent_type.value;
7459                         var row = SUGAR.email2.grid.getSelectedRows()[0];
7460                         row  = SUGAR.email2.grid.getRecord(row);
7461                         var ieId = row.getData().ieId;
7462                         var mbox = row.getData().mbox;
7463                         var emailUids = SUGAR.email2.listView.getUidsFromSelection();
7464                         var uids = "";
7465                         for(i=0; i<emailUids.length; i++) {
7466                             if(uids != '') {
7467                                 uids += app_strings.LBL_EMAIL_DELIMITER;
7468                             }
7469                             uids += emailUids[i];
7470                         }
7471                         overlay(app_strings.LBL_EMAIL_PERFORMING_TASK, app_strings.LBL_EMAIL_ONE_MOMENT);
7472                         AjaxObject.startRequest(callbackStatusForImport, urlStandard + '&emailUIAction=relateEmails&uid=' + uids
7473                             + "&ieId=" + ieId + "&mbox=" + mbox + "&parent_id=" + parent_id + "&parent_type=" + parent_type);
7474                         SED.relateDialog.hide();
7475                         document.getElementById('relateDialogContent').innerHTML = "";
7476                         }
7477                 }]
7478                         });
7479
7480             SED.relateDialog.hideEvent.subscribe(function(){
7481                 if (QSFieldsArray['ImportEditView_parent_name'] != null) {
7482                         QSFieldsArray['ImportEditView_parent_name'].destroy();
7483                         delete QSFieldsArray['ImportEditView_parent_name'];
7484                 } // if
7485                                 if (QSProcessedFieldsArray['ImportEditView_parent_name']) {
7486                                         QSProcessedFieldsArray['ImportEditView_parent_name'] = false;
7487                                 } // if
7488             });
7489
7490             SED.relateDialog.renderEvent.subscribe(function() {
7491                 var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
7492                 var contH = 0;
7493                 for (var i in this.body.childNodes) {
7494                         if (this.body.childNodes[i].clientHeight)
7495                                 contH += this.body.childNodes[i].clientHeight;
7496                 }
7497             }, SED.relateDialog);
7498             SED.relateDialog.setHeader(app_strings.LBL_EMAIL_RELATE_EMAIL);
7499                 } // end lazy load
7500
7501         SED.relateDialog.setBody(ret.html);
7502         SED.relateDialog.render();
7503         SUGAR.util.evalScript(ret.html);
7504         SED.relateDialog.show();
7505     }
7506 };
7507 /**
7508  * DetailView callbacks
7509  */
7510 AjaxObject.detailView.callback = {
7511         emailDetail : {
7512                 success : function(o) {
7513                         SUGAR.email2.o = o;
7514                         var ret = JSON.parse(o.responseText);
7515                         SUGAR.email2.detailView.consumeMetaDetail(ret);
7516                 },
7517                 argument: [targetDiv],
7518                 failure : AjaxObject.handleFailure,
7519                 timeout : 0,
7520                 scope   : AjaxObject
7521         },
7522         emailPreview : {
7523                 success : function(o) {
7524                         SUGAR.email2.o = o;
7525                         var ret = JSON.parse(o.responseText);
7526                         SUGAR.email2.detailView.consumeMetaPreview(ret);
7527                 },
7528                 failure : AjaxObject.handleFailure,
7529                 timeout : 0,
7530                 scope   : AjaxObject
7531         },
7532         viewPrint : {
7533                 success : AjaxObject.detailView.displayPrintable,
7534                 failure : AjaxObject.handleFailure,
7535                 timeout : AjaxObject.timeout,
7536                 scope   : AjaxObject
7537         },
7538         viewRaw : {
7539                 success : AjaxObject.detailView.displayView,
7540                 failure : AjaxObject.handleFailure,
7541                 timeout : AjaxObject.timeout,
7542                 scope   : AjaxObject
7543         }
7544 };
7545
7546
7547
7548
7549
7550 AjaxObject.folders = {
7551         /**
7552          * check-mail post actions
7553          */
7554         checkMailCleanup : function(o) {
7555                 hideOverlay();
7556                 AjaxObject.folders.rebuildFolders(o); // rebuild TreeView
7557
7558                 // refresh focus ListView
7559                 SE.listView.refreshGrid();
7560                 SUGAR.email2.folders.startCheckTimer(); // resets the timer
7561         },
7562
7563         /**
7564          */
7565         rebuildFolders : function(o) {
7566                 hideOverlay();
7567
7568                 var data = JSON.parse(o.responseText);
7569
7570                 email2treeinit(SUGAR.email2.tree, data.tree_data, 'frameFolders', data.param);
7571                 SUGAR.email2.folders.setSugarFolders();
7572         }
7573 };
7574 AjaxObject.folders.callback = {
7575         checkMail : {
7576                 success : AjaxObject.folders.checkMailCleanup,
7577                 failure : AjaxObject.handleFailure,
7578                 timeout : 600000, // 5 mins
7579                 scope   : AjaxObject
7580         }
7581 }
7582
7583 AjaxObject.rules = {
7584         loadRulesForSettings : function(o) {
7585                 document.getElementById("rulesListCell").innerHTML = o.responseText;
7586                 // assume we have the class we need
7587                 SUGAR.routing.getStrings();
7588                 SUGAR.routing.getDependentDropdowns();
7589         }
7590 };
7591 ////    END PER MODULE CALLBACK OBJECTS
7592 ///////////////////////////////////////////////////////////////////////////
7593
7594
7595 var callback = {
7596         success : AjaxObject.handleSuccess,
7597         failure : AjaxObject.handleFailure,
7598         timeout : AjaxObject.timeout,
7599         scope   : AjaxObject
7600 };
7601 var callbackAccount = {
7602         success : AjaxObject.ieSaveSuccess,
7603         failure : AjaxObject.handleFailure,
7604         timeout : AjaxObject.timeout,
7605         scope   : AjaxObject
7606 };
7607 var callbackAccountDelete = {
7608         success : AjaxObject.ieDeleteSuccess,
7609         failure : AjaxObject.handleFailure,
7610         timeout : AjaxObject.timeout,
7611         scope   : AjaxObject
7612 };
7613 var callbackOutboundTest = {
7614         success : AjaxObject.ieSendSuccess,
7615         failure : AjaxObject.handleFailure,
7616         timeout : AjaxObject.timeout,
7617         scope   : AjaxObject
7618 };
7619
7620
7621
7622 var callbackTeamInfoForSettings = {
7623 success : function (o) {
7624         var data = JSON.parse(o.responseText);
7625         document.getElementById('EditViewGroupFolderTeamTD').innerHTML = data.defaultgroupfolder;
7626 },
7627 failure : AjaxObject.handleFailure,
7628 timeout : AjaxObject.timeout,
7629 scope   : AjaxObject
7630
7631 };
7632
7633 var callbackStatusForImport = {
7634 success : function (o) {
7635         hideOverlay();
7636         if (o.responseText != "")  {
7637                 var statusString = "";
7638                 var data = JSON.parse(o.responseText);
7639                 for(i=0; i<data.length; i++) {
7640                         statusString = statusString + data[i] + '<br/>';
7641                 }
7642                 overlay(SUGAR.language.get('Emails','LBL_IMPORT_STATUS_TITLE'), statusString, 'alert');
7643         }
7644         SE.listView.refreshGrid();
7645
7646 },
7647 failure : AjaxObject.handleFailure,
7648 timeout : AjaxObject.timeout,
7649 scope   : AjaxObject
7650
7651 };
7652 var callbackComposeCache = {
7653         success : AjaxObject.composeCache,
7654         failure : AjaxObject.handleFailure,
7655         timeout : AjaxObject.timeout,
7656         scope   : AjaxObject
7657 };
7658 var callbackDelete = {
7659         success : AjaxObject.handleDeleteReturn,
7660         failure : AjaxObject.handleFailure,
7661         timeout : AjaxObject.timeout,
7662         scope   : AjaxObject
7663 };
7664 var callbackEmailDetailMultiple = {
7665         success : function(o) {
7666                 hideOverlay();
7667                 var retMulti = JSON.parse(o.responseText);
7668                 var ret = new Object();
7669
7670                 for(var i=0; i<retMulti.length; i++) {
7671                         ret = retMulti[i];
7672
7673                         SUGAR.email2._setDetailCache(ret);
7674                         SUGAR.email2.detailView.populateDetailView(ret.meta.uid, ret.meta.mbox, ret.meta.ieId, true, SUGAR.email2.innerLayout);
7675                 }
7676         },
7677         failure : AjaxObject.handleFailure,
7678         timeout : 0,
7679         scope   : AjaxObject
7680 };
7681 var callbackListViewSortOrderChange = {
7682         success : AjaxObject.saveListViewSortOrderPart2,
7683         failure : AjaxObject.handleFailure,
7684         timeout : AjaxObject.timeout,
7685         scope   : AjaxObject,
7686         argument        : [ieId, ieName, focusFolder]
7687 };
7688 var callbackEmptyTrash = {
7689         success : function(o) {
7690                 hideOverlay();
7691                 AjaxObject.folderRenameCleanup;
7692         },
7693         failure : AjaxObject.handleFailure,
7694         timeout : AjaxObject.timeout,
7695         scope   : AjaxObject
7696 };
7697 var callbackClearCacheFiles = {
7698         success : function(o) {
7699                 hideOverlay();
7700         },
7701         failure : AjaxObject.handleFailure,
7702         timeout : AjaxObject.timeout,
7703         scope   : AjaxObject
7704 };
7705 var callbackFolderRename = {
7706         success : function(o) {hideOverlay();SUGAR.email2.folders.rebuildFolders();},
7707         failure : AjaxObject.handleFailure,
7708         timeout : AjaxObject.timeout,
7709         scope   : AjaxObject
7710 };
7711 var callbackFolderDelete = {
7712         success : function(o) {
7713                 var ret = JSON.parse(o.responseText);
7714                 if (ret.status) {
7715                     if (ret.folder_id) {
7716                         var node = SUGAR.email2.folders.getNodeFromId(ret.folder_id);
7717                         if(node)
7718                                 SUGAR.email2.tree.removeNode(node, true);
7719                     } else if (ret.ieId && ret.mbox) {
7720                         var node = SUGAR.email2.folders.getNodeFromIeIdAndMailbox(ret.ieId, ret.mbox);
7721                         if(node)
7722                                 SUGAR.email2.tree.removeNode(node, true);
7723                     }
7724                         hideOverlay();
7725                         //SUGAR.email2.folders.loadSettingFolder();
7726                 } else {
7727                         hideOverlay();
7728                         overlay(app_strings.LBL_EMAIL_ERROR_DESC, ret.errorMessage, 'alert');
7729                 } // else
7730         },
7731         failure : AjaxObject.handleFailure,
7732         timeout : AjaxObject.timeout,
7733         scope   : AjaxObject
7734 };
7735 var callbackFolderSave = {
7736         success : function(o) {
7737                 var ret = JSON.parse(o.responseText);
7738
7739                 switch(ret.action) {
7740                         case 'newFolderSave':
7741                                 SUGAR.email2.folders.rebuildFolders();
7742                         break;
7743                 }
7744         },
7745         failure : AjaxObject.handleFailure,
7746         timeout : AjaxObject.timeout,
7747         scope   : AjaxObject
7748 };
7749 var callbackFolderSubscriptions = {
7750         success : AjaxObject.updateFolderSubscriptions,
7751         failure : AjaxObject.handleFailure,
7752         timeout : AjaxObject.timeout,
7753         scope   : AjaxObject
7754 };
7755 var callbackFolderUpdate = {
7756         success : AjaxObject.updateFrameFolder,
7757         failure : AjaxObject.handleFailure,
7758         timeout : AjaxObject.timeout,
7759         scope   : AjaxObject
7760 };
7761 var callbackFolders = {
7762         success : AjaxObject.folders.rebuildFolders,
7763         //success : void(true),
7764         failure : AjaxObject.handleFailure,
7765         timeout : AjaxObject.timeout,
7766         scope   : AjaxObject
7767 };
7768 var callbackFullSync = {
7769         success : AjaxObject.fullSyncCleanup,
7770         failure : AjaxObject.handleFailure,
7771         timeout : 9999999999999,
7772         scope   : AjaxObject
7773 };
7774 var callbackGeneric = {
7775         success : function() {
7776                 hideOverlay();
7777         },
7778         failure : AjaxObject.handleFailure,
7779         timeout : AjaxObject.timeout,
7780         scope   : AjaxObject
7781 };
7782 var callbackIeAccountRetrieve = {
7783         success : function(o) {
7784                 // return JSON encoding
7785                 hideOverlay();
7786                 SUGAR.email2.accounts.fillIeAccount(o.responseText);
7787                 SUGAR.email2.accounts.showEditInboundAccountDialogue(false);
7788         },
7789         failure : AjaxObject.handleFailure,
7790         timeout : AjaxObject.timeout,
7791         scope   : AjaxObject
7792 };
7793 var callbackImportOneEmail = {
7794         success :  AjaxObject.detailView.showImportForm,
7795         failure : AjaxObject.handleFailure,
7796         timeout : AjaxObject.timeout,
7797         scope   : AjaxObject
7798 };
7799 var callbackRelateEmail = {
7800     success : AjaxObject.detailView.showRelateForm,
7801     failure : AjaxObject.handleFailure,
7802     timeout : AjaxObject.timeout,
7803     scope   : AjaxObject
7804 }
7805 var callbackEmailDetailView = {
7806     success : AjaxObject.detailView.showEmailDetailView,
7807     failure : AjaxObject.handleFailure,
7808     timeout : AjaxObject.timeout,
7809     scope   : AjaxObject
7810 }
7811 var callbackAssignmentDialog = {
7812         success :  AjaxObject.detailView.showAssignmentDialogWithData,
7813         failure : AjaxObject.handleFailure,
7814         timeout : AjaxObject.timeout,
7815         scope   : AjaxObject
7816 };
7817 var callbackAssignmentAction = {
7818         success :  function(o) {
7819                 SE.listView.refreshGrid();
7820                 hideOverlay();
7821                 if(o.responseText != '') {
7822                overlay('Assignment action result', o.responseText, 'alert');
7823             } // if
7824         } ,
7825         failure : AjaxObject.handleFailure,
7826         timeout : AjaxObject.timeout,
7827         scope   : AjaxObject
7828 };
7829 var callbackMoveEmails = {
7830         success :  function(o) {
7831             SE.listView.refreshGrid();
7832                 hideOverlay();
7833                 if(o.responseText != '') {
7834                overlay(app_strings.LBL_EMAIL_ERROR_DESC, o.responseText, 'alert');
7835             } // if
7836         } ,
7837         failure : AjaxObject.handleFailure,
7838         timeout : AjaxObject.timeout,
7839         scope   : AjaxObject
7840 };
7841 var callbackLoadAttachments = {
7842         success : AjaxObject.loadAttachments,
7843         failure : AjaxObject.handleFailure,
7844         timeout : AjaxObject.timeout,
7845         scope   : AjaxObject
7846 };
7847 var callbackLoadRules = {
7848         success : AjaxObject.rules.loadRulesForSettings,
7849         failure : AjaxObject.handleFailure,
7850         timeout : AjaxObject.timeout,
7851         scope   : AjaxObject
7852 };
7853 var callbackLoadSignature = {
7854         success : AjaxObject.loadSignature,
7855         failure : AjaxObject.handleFailure,
7856         timeout : AjaxObject.timeout,
7857         scope   : AjaxObject
7858 };
7859 var callbackDeleteSignature = {
7860         success : AjaxObject.handleDeleteSignature,
7861         failure : AjaxObject.handleFailure,
7862         timeout : AjaxObject.timeout,
7863         scope   : AjaxObject
7864 };
7865 /*var callbackMoveEmails = {
7866     success : function(o) { SUGAR.email2.listView.moveEmailsCleanup(o) },
7867     failure : AjaxObject.handleFailure,
7868     timeout : AjaxObject.timeout,
7869     scope   : AjaxObject
7870 }*/
7871 var callbackOutboundSave = {
7872         success : AjaxObject.accounts.saveOutboundCleanup,
7873         failure : AjaxObject.handleFailure,
7874         timeout : AjaxObject.timeout,
7875         scope   : AjaxObject
7876 };
7877 var callbackDefaultOutboundSave = {
7878         success : AjaxObject.accounts.saveDefaultOutboundCleanup,
7879         failure : AjaxObject.handleFailure,
7880         timeout : AjaxObject.timeout,
7881         scope   : AjaxObject
7882 };
7883 var callbackQuickCreate = {
7884         success : AjaxObject.detailView.showQuickCreateForm,
7885         failure : AjaxObject.handleFailure,
7886         timeout : AjaxObject.timeout,
7887         scope   : AjaxObject
7888 };
7889 var callbackQuickCreateSave = {
7890         success : AjaxObject.detailView.saveQuickCreateForm,
7891         failure : AjaxObject.handleFailure,
7892         timeout : AjaxObject.timeout,
7893         scope   : AjaxObject
7894 };
7895 var callbackQuickCreateSaveAndAddToAddressBook = {
7896         success : AjaxObject.detailView.saveQuickCreateFormAndAddToAddressBook,
7897         failure : AjaxObject.handleFailure,
7898         timeout : AjaxObject.timeout,
7899         scope   : AjaxObject
7900 };
7901 var callbackQuickCreateSaveAndReply = {
7902     success : AjaxObject.detailView.saveQuickCreateFormAndReply,
7903     failure : AjaxObject.handleFailure,
7904     timeout : AjaxObject.timeout,
7905     scope   : AjaxObject
7906 }
7907 var callbackQuickCreateSaveAndReplyCase = {
7908     success : AjaxObject.detailView.saveQuickCreateFormAndReplyCase,
7909     failure : AjaxObject.handleFailure,
7910     timeout : AjaxObject.timeout,
7911     scope   : AjaxObject
7912 }
7913 var callbackRebuildShowAccountList = {
7914         success : AjaxObject.rebuildShowFolders,
7915         failure : AjaxObject.handleFailure,
7916         timeout : AjaxObject.timeout,
7917         scope   : AjaxObject
7918 };
7919
7920 var callbackRefreshSugarFolders = {
7921         success : function(o) {
7922                 var t = JSON.parse(o.responseText);
7923                 SUGAR.email2.folders.setSugarFoldersEnd(t);
7924         },
7925         failure : AjaxObject.handleFailure,
7926         timeout : AjaxObject.timeout,
7927         scope   : AjaxObject
7928 };
7929 var callbackReplyForward = {
7930         success : AjaxObject.handleReplyForward,
7931         finish : function(a, retryCount) {
7932                 if (typeof(retryCount) == 'undefined') {
7933                         retryCount = 0;
7934                 } else {
7935                         retryCount++;
7936                 }
7937                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
7938                 var t = tinyMCE.getInstanceById('htmleditor' + idx);
7939         try {
7940                         var html = t.getContent();
7941
7942             if (a.type != 'draft') {
7943                         if(SUGAR.email2.userPrefs.signatures.signature_prepend == 'true') {
7944                                 html += "&nbsp;<div><hr></div>" + a.description;
7945                         } else {
7946                                 html =  "&nbsp;<div><hr></div>" + a.description + html;
7947                         }
7948             }else {
7949                 html = a.description;
7950             }
7951
7952                         t.setContent(html);//
7953
7954                 } catch(e) {
7955                         if (retryCount < 5) {
7956                                 setTimeout("callbackReplyForward.finish(globalA, " + retryCount + ");", 500);
7957                                 return;
7958                         }
7959                 }
7960                 var tabArray = SUGAR.email2.innerLayout.get("tabs");
7961                 if (tabArray != null && tabArray.length > 0) {
7962                         for (i = 0 ; i < tabArray.length ; i++) {
7963                                 var tabObject = tabArray[i];
7964                                 if (tabObject.get("id") == ("composeTab" + idx)) {
7965                                         var tabLabel = a.name;
7966                                 if (tabLabel != null && tabLabel.length > 25) {
7967                                         tabLabel = tabLabel.substring(0, 25) + "...";
7968                                 } // if
7969                                         tabObject.get("labelEl").firstChild.data = tabLabel;
7970                                         break;
7971                                 }
7972                         }
7973                 }
7974
7975                 //SUGAR.email2.innerLayout.regions.center.getPanel('composeLayout' + idx).setTitle(a.name);
7976                 if (a.parent_name != null && a.parent_name != "") {
7977                         document.getElementById('data_parent_name' + idx).value = a.parent_name;
7978                 }
7979                 if (a.parent_type != null && a.parent_type != "") {
7980                         document.getElementById('data_parent_type' + idx).value = a.parent_type;
7981                 }
7982                 if (a.parent_id != null && a.parent_id != "") {
7983                         document.getElementById('data_parent_id' + idx).value = a.parent_id;
7984                 }
7985                 if (a.fromAccounts.status) {
7986                         var addressFrom = document.getElementById('addressFrom' + idx);
7987                 SUGAR.email2.util.emptySelectOptions(addressFrom);
7988                 var fromAccountOpts = a.fromAccounts.data;
7989                 for(i=0; i<fromAccountOpts.length; i++) {
7990                       var key = fromAccountOpts[i].value;
7991                       var display = fromAccountOpts[i].text;
7992                       var opt = new Option(display, key);
7993                       if (fromAccountOpts[i].selected) {
7994                         opt.selected = true;
7995                       }
7996                       addressFrom.options.add(opt);
7997                 }
7998                 } // if
7999                 hideOverlay();
8000
8001         },
8002         failure : AjaxObject.handleFailure,
8003         timeout : AjaxObject.timeout,
8004         scope   : AjaxObject,
8005         argument        : [sendType]
8006 };
8007 var callbackSendEmail = {
8008         success : AjaxObject.sendEmailCleanUp,
8009         failure : AjaxObject.handleFailure,
8010         timeout : AjaxObject.timeout,
8011         scope   : AjaxObject
8012 };
8013 var callbackSettings = {
8014         success : AjaxObject.updateUserPrefs,
8015         failure : AjaxObject.handleFailure,
8016         timeout : AjaxObject.timeout,
8017         scope   : AjaxObject
8018 };
8019 var callbackSettingsFolderRefresh = {
8020         success : AjaxObject.settingsFolderRefresh,
8021         failure : AjaxObject.handleFailure,
8022         timeout : AjaxObject.timeout,
8023         scope   : AjaxObject
8024 };
8025 var callbackLoadSettingFolder = {
8026         success : function(o) {
8027                 AjaxObject.settingsFolderRefresh(o);
8028                 SUGAR.email2.accounts.rebuildFolderList(); // refresh frameFolder
8029         },
8030         failure : AjaxObject.handleFailure,
8031         timeout : AjaxObject.timeout,
8032         scope   : AjaxObject
8033
8034 };
8035 var callbackUploadAttachment = {
8036         success : AjaxObject.uploadAttachmentSuccessful,
8037         upload  : AjaxObject.uploadAttachmentSuccessful,
8038         failure : AjaxObject.handleFailure,
8039         timeout : AjaxObject.timeout,
8040         scope   : AjaxObject
8041 };
8042 var callbackUserPrefs = {
8043         success : function(o) {
8044                 SUGAR.email2.userPrefs = JSON.parse(o.responseText);
8045         },
8046         failure : AjaxObject.handleFailure,
8047         timeout : AjaxObject.timeout,
8048         scope   : AjaxObject
8049 };
8050
8051 var callbackContextmenus = {
8052         markUnread : {
8053                 success : AjaxObject.markEmailCleanup,
8054                 failure : AjaxObject.handleFailure,
8055                 timeout : AjaxObject.timeout,
8056                 scope   : AjaxObject
8057         }
8058 };
8059
8060 var callbackCheckEmail2 = {
8061         success : function(o) {
8062                 var ret = JSON.parse(o.responseText);
8063                 overlay(app_strings.LBL_EMAIL_CHECKING_NEW, ret.text);
8064
8065
8066         },
8067         failure : AjaxObject.handleFailure,
8068         timeout : AjaxObject.timeout,
8069         scope   : AjaxObject
8070 }// End of File modules/Emails/javascript/ajax.js
8071                                 
8072 /*********************************************************************************
8073  * SugarCRM is a customer relationship management program developed by
8074  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8075  * 
8076  * This program is free software; you can redistribute it and/or modify it under
8077  * the terms of the GNU Affero General Public License version 3 as published by the
8078  * Free Software Foundation with the addition of the following permission added
8079  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8080  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8081  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8082  * 
8083  * This program is distributed in the hope that it will be useful, but WITHOUT
8084  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8085  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8086  * details.
8087  * 
8088  * You should have received a copy of the GNU Affero General Public License along with
8089  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8090  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8091  * 02110-1301 USA.
8092  * 
8093  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8094  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8095  * 
8096  * The interactive user interfaces in modified source and object code versions
8097  * of this program must display Appropriate Legal Notices, as required under
8098  * Section 5 of the GNU Affero General Public License version 3.
8099  * 
8100  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8101  * these Appropriate Legal Notices must retain the display of the "Powered by
8102  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8103  * technical reasons, the Appropriate Legal Notices must display the words
8104  * "Powered by SugarCRM".
8105  ********************************************************************************/
8106
8107 function gridInit() {
8108         if(SUGAR.email2.grid) {
8109                 SUGAR.email2.grid.destroy();
8110         }
8111         
8112         e2Grid = {
8113                 init : function() {
8114                 
8115                         var Ck = YAHOO.util.Cookie;
8116                         var widths = [ 10, 10, 150, 250, 175, 125 ];
8117
8118                         if (Ck.get("EmailGridWidths")) {
8119                                 for (var i=0; i < widths.length; i++) {
8120                                         widths[i] = Ck.getSub("EmailGridWidths", i+ "", Number);
8121                                 }
8122                         } else {
8123                                 for (var i=0; i < widths.length; i++) {
8124                                         Ck.setSub("EmailGridWidths", i + "", widths[i], {expires: SUGAR.email2.nextYear});
8125                                 }
8126                         }
8127                         
8128                         // changes "F" to an icon
8129                         function flaggedIcon(cell, record, column, value) {
8130                                 if(value != "") {
8131                                         cell.innerHTML = "<span style='color: #f00; font-weight:bold;'>!</span>";
8132                                 }
8133                         }
8134                         // changes "A" to replied icon
8135                         function repliedIcon(cell, record, column, value) {
8136                                 if(value != "") {
8137                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>";
8138                                 }
8139                         }
8140                 function attachIcon(cell, record, column, value) {
8141                                 if(value == "1") {
8142                                         cell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>";
8143                                 }
8144                         }
8145
8146                         var colModel = 
8147                                 [
8148                                         {
8149                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif' class='image' border='0' width='10' align='absmiddle'>", 
8150                                                 width: 10, 
8151                                                 sortable: false, 
8152                                                 fixed: true,
8153                                                 resizeable: true,
8154                                                 formatter: attachIcon,
8155                                                 key: 'hasAttach'
8156                                         }, 
8157                                     {
8158                                                 label: "<span style='color: #f00; font-weight:bold;'>!</span>", 
8159                                                 width: widths[0], 
8160                                                 sortable: true, 
8161                                                 fixed: true,
8162                                                 resizeable: true,
8163                                                 formatter: flaggedIcon,
8164                                                 key: 'flagged'
8165                                         }, 
8166                                         {
8167                                                 label: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=export.gif' class='image' border='0' width='10' align='absmiddle'>", 
8168                                                 width: widths[1], 
8169                                                 sortable: true, 
8170                                                 fixed: true,
8171                                                 resizeable: true,
8172                                                 formatter: repliedIcon,
8173                                                 key: 'status'
8174                                         },
8175                                         {
8176                                                 label: app_strings.LBL_EMAIL_FROM, 
8177                                                 width: widths[2],
8178                                                 sortable: true,
8179                                                 resizeable: true,
8180                                                 key: 'from'
8181                                         }, 
8182                                         {
8183                                                 label: app_strings.LBL_EMAIL_SUBJECT,
8184                                                 width: widths[3], 
8185                                                 sortable: true,
8186                                                 resizeable: true,
8187                                                 key: 'subject'
8188                                         }, 
8189                                         {
8190                                                 label: mod_strings.LBL_LIST_DATE,
8191                                                 width: widths[4], 
8192                                                 sortable: true,
8193                                                 resizeable: true,
8194                         key: 'date'
8195                                         }, 
8196                                         {
8197                                                 label: app_strings.LBL_EMAIL_TO,
8198                                                 width: widths[5], 
8199                                                 sortable: false,
8200                                                 resizeable: true,
8201                         key: 'to_addrs'
8202                                         }, 
8203                                         {
8204                                                 label: 'uid',
8205                                                 hidden: true,
8206                         key: 'uid'
8207                                         }, 
8208                                         {
8209                                                 label: 'mbox',
8210                                                 hidden: true,
8211                         key: 'mbox'
8212                                         }, 
8213                                         {
8214                                                 label: 'ieId',
8215                                                 hidden: true,
8216                         key: 'ieId'
8217                                         }, 
8218                                         {       
8219                                                 label: 'site_url',
8220                                                 hidden: true,
8221                         key: 'site_url'
8222                                         },
8223                                         {       label: 'seen',
8224                                                 hidden: true,
8225                         key: 'seen'
8226                                         },
8227                                         {       label: 'type',
8228                                                 hidden: true,
8229                         key: 'type'
8230                                         }
8231                                 ];
8232                         
8233                         var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8234                                 responseType: YAHOO.util.DataSource.TYPE_JSON,
8235                                 responseSchema: {
8236                                     resultsList: 'Email',
8237                             fields: ['flagged', 'status', 'from', 'subject', 'date','to_addrs', 'uid', 'mbox', 'ieId', 'site_url', 'seen', 'type', 'AssignedTo','hasAttach'],
8238                             metaFields: {total: 'TotalCount', unread:"UnreadCount", fromCache: "FromCache"}
8239                                 }
8240                     });
8241                         var params = {
8242                                         to_pdf : "true",
8243                                         module : "Emails",
8244                                         action : "EmailUIAjax",
8245                                         emailUIAction : "getMessageList",
8246                                         mbox : "INBOX",
8247                                         ieId : "",
8248                                         forceRefresh : "false"
8249                         };
8250                         if(lazyLoadFolder != null) {
8251                                 params['mbox'] = lazyLoadFolder.folder;
8252                                 params['ieId'] = lazyLoadFolder.ieId;
8253                                 //Check if the folder is a Sugar Folder
8254                                 var test = new String(lazyLoadFolder.folder);
8255                                 if(test.match(/SUGAR\./)) {
8256                                         params['emailUIAction'] = 'getMessageListSugarFolders';
8257                                         params['mbox'] = test.substr(6);
8258                                 }
8259                         }
8260                         //dataModel.initPaging(urlBase, SUGAR.email2.userPrefs.emailSettings.showNumInList);
8261         
8262                         // create the Grid
8263                         var grid = SUGAR.email2.grid = new YAHOO.SUGAR.SelectionGrid('emailGrid', colModel, dataModel, {
8264                                 MSG_EMPTY: SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8265                                 dynamicData: true,
8266                                 paginator: new YAHOO.widget.Paginator({ 
8267                                         rowsPerPage:parseInt(SUGAR.email2.userPrefs.emailSettings.showNumInList),  
8268                                         containers : ["dt-pag-nav"],
8269                                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8270                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8271                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8272                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8273                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8274                                 }),
8275                                 initialRequest:SUGAR.util.paramsToUrl(params),
8276                                 width:  "800px",
8277                                 height: "400px"
8278                         });
8279
8280                         initRowDD();
8281
8282                         //Override Paging request construction
8283                         grid.set("generateRequest", function(oState, oSelf) {
8284                     oState = oState || {pagination:null, sortedBy:null};
8285                     var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[1].getKey();
8286                     var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8287                     var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8288                     var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8289                     // Build the request 
8290                     var ret = 
8291                             SUGAR.util.paramsToUrl(oSelf.params) + 
8292                             "&sort=" + sort +
8293                         "&dir=" + dir +
8294                         "&start=" + startIndex +
8295                         ((results !== null) ? "&limit=" + results : "");
8296                     return  ret;
8297                 });
8298                         
8299                         
8300                         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8301                                 oPayload = oPayload || { };
8302                                 
8303                                 oPayload.totalRecords = oResponse.meta.total;
8304                                 oPayload.unreadRecords = oResponse.meta.unread;
8305                                 
8306                         var tabObject = SE.innerLayout.get("tabs")[0];
8307                         var mboxTitle = "";
8308                         if (this.params.mbox != null) {
8309                                 mboxTitle = this.params.mbox;
8310                         }
8311                         var tabtext = mboxTitle + " (" + oResponse.meta.total + " " + app_strings.LBL_EMAIL_MESSAGES + " )";
8312                         tabObject.get("labelEl").firstChild.data = tabtext;
8313                         
8314                         if (SE.tree) {
8315                                 var node = SE.tree.getNodeByProperty('id', this.params.ieId) || SE.tree.getNodeByProperty('origText', this.params.mbox);
8316                                 if (node) {
8317                                         node.data.unseen = oResponse.meta.unread;
8318                                         SE.accounts.renderTree();
8319                                 }
8320                         }
8321                                 return oPayload; 
8322                         }
8323                         
8324                         var resize = grid.resizeGrid = function () {
8325                                 SUGAR.email2.grid.set("width",  SUGAR.email2.grid.get("element").parentNode.clientWidth + "px");
8326                                 SUGAR.email2.grid.set("height", (SUGAR.email2.grid.get("element").parentNode.clientHeight - 47) + "px");
8327                         }
8328                         grid.convertDDRows = function() {
8329                                 var rowEl = this.getFirstTrEl();
8330                                 while (rowEl != null) {
8331                                         new this.DDRow(this, this.getRecord(rowEl), rowEl);
8332                                         rowEl = this.getNextTrEl(rowEl);
8333                                 }
8334                         }
8335                         
8336                         
8337                         grid.on("columnResizeEvent", function(o) {
8338                                 //Find the index of the column
8339                                 var colSet = SUGAR.email2.grid.getColumnSet().flat;
8340                                 for (var i=0; i < colSet.length; i++) {
8341                                         if (o.column == colSet[i]) {
8342                                                 //Store it in the cookie
8343                                                 Ck.setSub("EmailGridWidths", i + "", o.width, {expires: SUGAR.email2.nextYear});
8344                                         }
8345                                 }
8346                                 //this.resizeGrid();
8347                         }, null, grid); 
8348                         
8349                         grid.on("postRenderEvent", function() {this.convertDDRows()}, null, grid);
8350                         grid.on("rowClickEvent", SUGAR.email2.listView.handleClick);  
8351                         grid.on("rowDblclickEvent", SUGAR.email2.listView.getEmail);  
8352                         grid.render();
8353                         SUGAR.email2.listViewLayout.on("render", resize);
8354                         resize();
8355                         
8356                         //Setup the default load parameters
8357                         SUGAR.email2.grid.params = params;
8358                         
8359                         grid.on('postRenderEvent', SUGAR.email2.listView.setEmailListStyles);
8360                         dataModel.subscribe("requestEvent", grid.disable, grid, true);
8361                         dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8362                 }
8363         };
8364         e2Grid.init();
8365 };
8366
8367
8368 function initRowDD() {
8369         var sg = SUGAR.email2.grid,
8370         Dom = YAHOO.util.Dom;
8371         sg.DDRow = function(oDataTable, oRecord, elTr) {
8372                 if(oDataTable && oRecord && elTr) {
8373                         this.ddtable = oDataTable;
8374                 this.table = oDataTable.getTableEl();
8375                 this.row = oRecord;
8376                 this.rowEl = elTr;
8377                 this.newIndex = null;
8378                 this.init(elTr);
8379                 this.initFrame(); // Needed for DDProxy
8380                 this.invalidHandleTypes = {};
8381             }   
8382         };
8383         
8384         YAHOO.extend(sg.DDRow, YAHOO.util.DDProxy, {
8385             _resizeProxy: function() {
8386                 this.constructor.superclass._resizeProxy.apply(this, arguments);
8387                 var dragEl = this.getDragEl(),
8388                     el = this.getEl();
8389                 var xy = Dom.getXY(el);
8390                 
8391                 Dom.setStyle(dragEl, 'height', this.rowEl.offsetHeight + "px");
8392                 Dom.setStyle(dragEl, 'width', (parseInt(Dom.getStyle(dragEl, 'width'),10) + 4) + 'px');
8393                 Dom.setXY(dragEl, [xy[0] - 100, xy[1] - 20] );
8394                 Dom.setStyle(dragEl, 'display', "");
8395             },
8396             
8397             startDrag: function(x, y) { 
8398                 //Check if we should be dragging a set of rows rather than just the one.
8399                 var selectedRows = this.ddtable.getSelectedRows();
8400                 var iSelected = false;
8401                 for (var i in selectedRows) {
8402                         if (this.rowEl.id == selectedRows[i]) {
8403                                 iSelected = true;
8404                                 break
8405                         }
8406                 }
8407                 if (iSelected) {
8408                         this.rows = [];
8409                         for (var i in selectedRows) {
8410                                 this.rows[i] = this.ddtable.getRecord(selectedRows[i]);
8411                         }
8412                 } else {
8413                         this.rows = [this.row];
8414                         this.ddtable.unselectAllRows();
8415                         this.ddtable.selectRow(this.row);
8416                 }
8417                 
8418                 //Initialize the dragable proxy
8419                 var dragEl = this.getDragEl(); 
8420                 var clickEl = this.getEl(); 
8421                 Dom.setStyle(clickEl, "opacity", "0.25"); 
8422                 dragEl.innerHTML = "<table><tr>" + clickEl.innerHTML + "</tr></table>"; 
8423                 Dom.addClass(dragEl, "yui-dt-liner");
8424                 Dom.setStyle(dragEl, "opacity", "0.5"); 
8425                 Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 2) + "px");
8426                 Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor")); 
8427                     Dom.setStyle(dragEl, "border", "2px solid gray"); 
8428             },
8429             
8430             clickValidator: function(e) {
8431                 if (this.row.getData()[0] == " ")
8432                         return false;
8433                 var target = YAHOO.util.Event.getTarget(e);
8434                 return ( this.isValidHandleChild(target) && 
8435                                 (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) );
8436             },
8437             /**
8438              * This funciton checks that the target of the drag is a table row in this
8439              * DDGroup and simply moves the sourceEL to that location as a preview.
8440              */
8441             onDragOver: function(ev, id) {
8442                 var node = SUGAR.email2.tree.getNodeByElement(Dom.get(id));
8443                 if (node && node != this.targetNode) {
8444                         this.targetNode = node;
8445                         SUGAR.email2.folders.unhighliteAll();
8446                         node.highlight();
8447                 }
8448             },
8449             
8450             onDragOut: function(e, id) {
8451                 if (this.targetNode) {
8452                         SUGAR.email2.folders.unhighliteAll();
8453                         this.targetNode = false;
8454                 }
8455             },
8456             endDrag: function() {
8457                 Dom.setStyle(this.getEl(), "opacity", "");
8458                 Dom.setStyle(this.getDragEl(), "display", "none"); 
8459                 if (this.targetNode) {
8460                         SUGAR.email2.folders.handleDrop(this.rows, this.targetNode);
8461                 }
8462                 SUGAR.email2.folders.unhighliteAll();
8463                 this.rows = null;
8464             }
8465         });
8466 }
8467
8468 function AddressSearchGridInit() {
8469     function moduleIcon(elCell, oRecord, oColumn, oData) {
8470         elCell.innerHTML = "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=" + oData + ".gif' class='image' border='0' width='16' align='absmiddle'>";
8471     };
8472     function selectionCheckBox(elCell, oRecord, oColumn, oData) {
8473         elCell.innerHTML =  '<input type="checkbox" onclick="SUGAR.email2.addressBook.grid.toggleSelectCheckbox(\'' + oRecord.getId() + '\', this.checked);">';
8474     };
8475     var checkHeader = '<input type="checkbox" ';
8476     if (SUGAR.email2.util.isIe()) {
8477         checkHeader += 'style="top:-5px" ';
8478     }
8479     checkHeader += 'onclick="SUGAR.email2.addressBook.grid.toggleSelectAll(this.checked);">';
8480     var colModel = 
8481             [{
8482                 label: checkHeader,
8483             width: 30,
8484             formatter: selectionCheckBox,
8485             key: 'bean_id'
8486         },
8487             {
8488                 label: mod_strings.LBL_LIST_TYPE,
8489                 width: 25,
8490                 formatter: moduleIcon,
8491                 key: 'bean_module'
8492         },
8493             {
8494                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_NAME, 
8495                 width: 180,
8496                 sortable: true,
8497                 key: 'name'
8498             }, 
8499             {
8500                 label: app_strings.LBL_EMAIL_ADDRESS_BOOK_EMAIL_ADDR,
8501                 width: 300, 
8502                 sortable: true,
8503                 key: 'email'
8504             }];
8505     
8506     var dataModel = new YAHOO.util.DataSource(urlBase + "?", {
8507                 responseType: YAHOO.util.XHRDataSource.TYPE_JSON,
8508         responseSchema: {
8509             resultsList: 'Person',
8510             fields: ['name', 'email', 'bean_id', 'bean_module'],
8511                     metaFields: {total: 'TotalCount'}
8512         },
8513         //enable sorting on the server accross all data
8514         remoteSort: true
8515     });
8516     dataModel.params = {
8517                 to_pdf          : true,
8518                 module          : "Emails",
8519                 action          : "EmailUIAjax",
8520                 emailUIAction:"getAddressSearchResults"
8521     }
8522     var rb = document.getElementById('hasRelatedBean').checked;
8523         if (rb) {
8524                 var idx = SUGAR.email2.composeLayout.currentInstanceId;
8525                 var relatedBeanId = document.getElementById('data_parent_id' + idx).value;
8526                 var relatedBeanType = document.getElementById('data_parent_type' + idx).value;
8527                 dataModel.params['related_bean_id'] = relatedBeanId;
8528                 dataModel.params['related_bean_type'] = relatedBeanType;
8529                 dataModel.params['person'] = document.getElementById('input_searchPerson').value;
8530         }
8531     SUGAR.email2.addressBook.addressBookDataModel = dataModel;
8532     
8533     var grid = SUGAR.email2.addressBook.grid = new YAHOO.widget.ScrollingDataTable("addrSearchGrid", colModel, dataModel, {
8534         MSG_EMPTY: "&nbsp;", //SUGAR.language.get("Emails", "LBL_EMPTY_FOLDER"),
8535                 dynamicData: true,
8536                 paginator: new YAHOO.widget.Paginator({ 
8537                         rowsPerPage: 25,  
8538                         containers : ["dt-pag-nav-addressbook"],
8539                         template: "<div class='pagination'>{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}</div>",
8540                                         firstPageLinkLabel:     "<button class='button'><div class='paginator-start'/></button>",
8541                                         previousPageLinkLabel:  "<button class='button'><div class='paginator-previous'/></button>",
8542                                         nextPageLinkLabel:              "<button class='button'><div class='paginator-next'/></button>",
8543                                         lastPageLinkLabel:              "<button class='button'><div class='paginator-end'/></button>"
8544                 }),
8545                 initialRequest:SUGAR.util.paramsToUrl(dataModel.params),
8546                 width:  "560px",
8547                 height: "250px"
8548     });
8549         //Override Paging request construction
8550         grid.set("generateRequest", function(oState, oSelf) {
8551         oState = oState || {pagination:null, sortedBy:null};
8552         var sort = (oState.sortedBy) ? oState.sortedBy.key : oSelf.getColumnSet().keys[0].getKey();
8553         var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
8554         var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
8555         var results = (oState.pagination) ? oState.pagination.rowsPerPage : null;
8556         // Build the request 
8557         var ret = 
8558             SUGAR.util.paramsToUrl(oSelf.getDataSource().params) + 
8559             "&sort=" + sort + "&dir=" + dir + "&start=" + startIndex +
8560             ((results !== null) ? "&limit=" + results : "");
8561         return  ret;
8562     });
8563     
8564         grid.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
8565                 oPayload = oPayload || { };
8566                 oPayload.totalRecords = oResponse.meta.total;
8567                 return oPayload; 
8568         }
8569         
8570         grid.clickToggleSelect= function(args) {
8571                 var isIE = (args.event.target == null);
8572                 var targetElement = isIE ? args.event.srcElement : args.event.target;
8573                 if(targetElement.type == null || targetElement.type != 'checkbox') {
8574                         SUGAR.email2.addressBook.grid.toggleSelect(args.target.id);
8575                 }
8576         }
8577         
8578         grid.reSelectRowsOnRender = function (){
8579             var rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8580         for (var i = 0; i < rows.length; i++) 
8581         {
8582                 var emailAddress = rows[i].getData("email");
8583             var alreadyAdded = SUGAR.email2.addressBook.doesEmailAdddressExistInResultTable(emailAddress);
8584             if(alreadyAdded)
8585             {
8586                 rows[i].setData("selected",  true);
8587                         SUGAR.email2.addressBook.grid.selectRow(rows[i]);
8588             }
8589             else
8590             {
8591                 rows[i].setData("selected",  false);
8592                 SUGAR.email2.addressBook.grid.unselectRow(rows[i]);
8593             }
8594         }
8595         }
8596         grid.subscribe("rowMouseoverEvent", grid.onEventHighlightRow); 
8597         grid.subscribe("rowMouseoutEvent", grid.onEventUnhighlightRow); 
8598         grid.subscribe("rowClickEvent", grid.clickToggleSelect);
8599     grid.subscribe("postRenderEvent", grid.reSelectRowsOnRender);
8600     
8601     grid.render();
8602     dataModel.subscribe("requestEvent", grid.disable, grid, true);
8603     dataModel.subscribe("responseParseEvent", grid.undisable, grid, true);
8604     
8605     grid.toggleSelectCheckbox = function(id,checked){
8606         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8607         row.setData("checked",checked);
8608     };
8609     grid.toggleSelect = function(id, checked) {
8610         var row = SUGAR.email2.addressBook.grid.getRecord(id);
8611         checked = row.getData("selected");
8612         if (!checked)
8613         {
8614             SUGAR.email2.addressBook.grid.selectRow(row);
8615             SE.addressBook.insertContactRowToResultTable(id,null)
8616         } else 
8617         {
8618             SUGAR.email2.addressBook.grid.unselectRow(row);
8619             SE.addressBook.removeRowFromGridResults(id,row.getData("email"));
8620         }
8621         row.setData("selected", !checked);
8622     };
8623     
8624     grid.toggleSelectAll = function(checked) {
8625         rows = SUGAR.email2.addressBook.grid.getRecordSet().getRecords();
8626         for (var i = 0; i < rows.length; i++) {
8627                         if (typeof(rows[i]) != "undefined")
8628                                 rows[i].setData("checked",  checked);
8629         }
8630         var checkBoxes = SUGAR.email2.addressBook.grid.get("element").getElementsByTagName('input');
8631         for (var i = 0; i < checkBoxes.length; i++) {
8632             checkBoxes[i].checked = checked;
8633         }
8634     };
8635     
8636     //Initialize the grid result table.
8637     AddressSearchResultsGridInit();
8638 }
8639
8640
8641
8642 /**
8643 *  Initalize the results table for the address book selection.
8644 *
8645 */
8646 function AddressSearchResultsGridInit()
8647 {
8648     
8649     /* Full name sort funciton to compare by last name if available */
8650     var fullNameSort = function(a, b, desc) {
8651         // Deal with empty values
8652         if(!YAHOO.lang.isValue(a))
8653             return (!YAHOO.lang.isValue(b)) ? 0 : 1;
8654         else if(!YAHOO.lang.isValue(b))
8655             return -1;
8656
8657         var aNames = a.getData("name").split(' ');
8658         var bNames = b.getData("name").split(' ');
8659
8660         var aSortField = (aNames.length == 2) ? aNames[1] : a.getData("name");
8661         var bSortField = (bNames.length == 2) ? bNames[1] : b.getData("name");
8662
8663         return YAHOO.util.Sort.compare(aSortField,bSortField, desc);
8664
8665     };
8666     
8667     var typeDdOptions = [app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_TO.replace(/:$/,'') ,
8668                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_CC.replace(/:$/,''),
8669                          app_strings.LBL_EMAIL_ADDRESS_BOOK_ADD_BCC.replace(/:$/,'')]; 
8670               
8671     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})},
8672                      {key:'name',label:app_strings.LBL_EMAIL_ACCOUNTS_NAME,width: 280,sortable: true, sortOptions:{sortFunction:fullNameSort}}];
8673      
8674      var myDataSource = new YAHOO.util.DataSource([]); 
8675          myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY; 
8676          myDataSource.responseSchema = { 
8677                     fields: ["name","type","email_address","display_email_address","bean_id","idx"] 
8678                 };                                                                 
8679     
8680          var gridResults = SUGAR.email2.addressBook.gridResults = new YAHOO.widget.ScrollingDataTable("addrSearchResultGrid", ColumnDefs, myDataSource, {
8681                         width:  "350px",height: "250px", MSG_EMPTY: "&nbsp;"});
8682     
8683      var highlightEditableCell = function(oArgs) {
8684             var elCell = oArgs.target;
8685             if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
8686                 this.highlightCell(elCell);
8687             }
8688         };
8689       
8690      gridResults.subscribe("cellMouseoverEvent", highlightEditableCell);
8691      gridResults.subscribe("cellMouseoutEvent", gridResults.onEventUnhighlightCell);
8692      gridResults.subscribe("cellClickEvent", gridResults.onEventShowCellEditor);
8693      gridResults.subscribe("rowMouseoverEvent", gridResults.onEventHighlightRow); 
8694          gridResults.subscribe("rowMouseoutEvent", gridResults.onEventUnhighlightRow); 
8695      
8696      //Setup the context menus
8697      var onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) { 
8698              var task = p_aArgs[1]; 
8699              if(task) 
8700              { 
8701                  var elRow = this.contextEventTarget; 
8702                  elRow = p_myDataTable.getTrEl(elRow); 
8703          
8704                  if(elRow) 
8705                  { 
8706                      switch(task.index) 
8707                      { 
8708                          case 0:     
8709                              var oRecord = p_myDataTable.getRecord(elRow); 
8710                              p_myDataTable.deleteRow(elRow);  
8711                              SUGAR.email2.addressBook.grid.reSelectRowsOnRender();    
8712                      } 
8713                  } 
8714              } 
8715          };
8716      var contextMenu = new YAHOO.widget.ContextMenu("contextmenu", 
8717                         {trigger:gridResults.getTbodyEl()}); 
8718          contextMenu.addItem(app_strings.LBL_EMAIL_DELETE); 
8719          contextMenu.render("addrSearchResultGrid"); 
8720          contextMenu.clickEvent.subscribe(onContextMenuClick, gridResults); 
8721 }
8722 // End of File modules/Emails/javascript/grid.js
8723                                 
8724 /*********************************************************************************
8725  * SugarCRM is a customer relationship management program developed by
8726  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
8727  * 
8728  * This program is free software; you can redistribute it and/or modify it under
8729  * the terms of the GNU Affero General Public License version 3 as published by the
8730  * Free Software Foundation with the addition of the following permission added
8731  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
8732  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
8733  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
8734  * 
8735  * This program is distributed in the hope that it will be useful, but WITHOUT
8736  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
8737  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
8738  * details.
8739  * 
8740  * You should have received a copy of the GNU Affero General Public License along with
8741  * this program; if not, see http://www.gnu.org/licenses or write to the Free
8742  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
8743  * 02110-1301 USA.
8744  * 
8745  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
8746  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
8747  * 
8748  * The interactive user interfaces in modified source and object code versions
8749  * of this program must display Appropriate Legal Notices, as required under
8750  * Section 5 of the GNU Affero General Public License version 3.
8751  * 
8752  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
8753  * these Appropriate Legal Notices must retain the display of the "Powered by
8754  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
8755  * technical reasons, the Appropriate Legal Notices must display the words
8756  * "Powered by SugarCRM".
8757  ********************************************************************************/
8758
8759 /**
8760   Complex layout init
8761  */
8762 function complexLayoutInit() {
8763         var se = SUGAR.email2;
8764         var Dom = YAHOO.util.Dom;
8765         se.e2Layout = {
8766         getInnerLayout : function(rows) {
8767                 se.listViewLayout = new YAHOO.widget.Layout('listViewDiv', {
8768                 parent: se.complexLayout,  
8769                         border:true,
8770                     hideOnLayout: true,
8771                     height: 400,
8772                                 units: [{
8773                                         position: "center",
8774                                     scroll:false, // grid should autoScroll itself
8775                                     split:true,
8776                                     body: "<div id='emailGrid'></div><div id='dt-pag-nav'></div> "
8777                                 },{
8778                                         position: "bottom",
8779                                     scroll:true,
8780                                     collapse: false,
8781                                     resize: true,
8782                                     useShim:true,
8783                                     height:'250',
8784                                     body: "<div id='listBottom' />"
8785                                 },{
8786                                     position: "right",
8787                                     scroll:true,
8788                                     collapse: false,
8789                                     resize: true,
8790                                     useShim:true,
8791                                     width:'250',
8792                                     body: "<div id='listRight' />",
8793                                     titlebar: false //,header: "right"
8794                                 }]
8795             });
8796                 se.complexLayout.on("render", function(){
8797                         var height = SUGAR.email2.innerLayout.get("element").clientHeight - 30;
8798                                 SUGAR.email2.innerLayout.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8799                                 SUGAR.email2.listViewLayout.set("height", height);
8800                                 SUGAR.email2.listViewLayout.render();
8801                 });
8802             se.listViewLayout.render();
8803             //CSS hack for now
8804             se.listViewLayout.get("element").parentNode.parentNode.style.padding = "0px"
8805             var rp = se.listViewLayout.resizePreview = function() {
8806                 var pre = Dom.get("displayEmailFramePreview");
8807                 if (pre) {
8808                         var parent = Dom.getAncestorByClassName(pre, "yui-layout-bd");
8809                         pre.style.height = (parent.clientHeight - pre.offsetTop) + "px";
8810                 }
8811             };
8812             se.listViewLayout.getUnitByPosition("bottom").on("heightChange", se.autoSetLayout);
8813             se.listViewLayout.getUnitByPosition("right").on("endResize", se.autoSetLayout);
8814             se.e2Layout.setPreviewPanel(rows);
8815             se.previewLayout = se.listViewLayout;
8816             return se.listViewLayout;
8817         },
8818         
8819         getInnerLayout2Rows : function() {
8820             return this.getInnerLayout(true);
8821         },
8822         getInnerLayout2Columns : function() {
8823             return this.getInnerLayout(false);
8824         },
8825         
8826         init : function(){
8827             // initialize state manager, we will use cookies
8828 //                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
8829                 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
8830                 se.complexLayout = new YAHOO.widget.Layout("container", {
8831                         border:true,
8832                 hideOnLayout: true,
8833                 height: Dom.getViewportHeight() - (document.getElementById('header').clientHeight ) - 65,
8834                 width: Dom.getViewportWidth() - 40,
8835                 units: [{
8836                         position: "center",
8837                     scroll:false,
8838                     body: "<div id='emailtabs'></div>"
8839                 },
8840                 {
8841                         position: "left",
8842                         scroll: true,
8843                         body: "<div id='lefttabs'></div>",
8844                     collapse: true,
8845                     width: 210,
8846                     minWidth: 100,
8847                     resize:true,
8848                     useShim:true,
8849                     titlebar: true,
8850                     header: "&nbsp;"
8851                 },
8852                 {
8853                     header: Dom.get('footerLinks').innerHTML,
8854                                         position: 'bottom',
8855                                         id: 'mbfooter',
8856                                         height: 22,
8857                                         border: false
8858                 }]
8859             });
8860                 se.complexLayout.render();
8861                 var tp = se.innerLayout = new YAHOO.widget.TabView("emailtabs");
8862                         tp.addTab(new YAHOO.widget.Tab({ 
8863                                 label: "Inbox",
8864                                 scroll : true,
8865                                 content : "<div id='listViewDiv'/>",
8866                                 id : "center",
8867                                 active : true
8868                         }));
8869                 var centerEl = se.complexLayout.getUnitByPosition('center').get('wrap');
8870                         tp.appendTo(centerEl);
8871                         //CSS hack for now
8872                         tp.get("element").style.borderRight = "1px solid #666"
8873                         
8874                         var listV =  this.getInnerLayout2Rows();
8875                         listV.set("height", tp.get("element").clientHeight - 25);
8876                         listV.render();
8877                 
8878             se.leftTabs = new YAHOO.widget.TabView("lefttabs");
8879             var folderTab = new YAHOO.widget.Tab({ 
8880                                 label: app_strings.LBL_EMAIL_FOLDERS_SHORT,
8881                                 scroll : true,
8882                                 content : "<div id='emailtree'/>",
8883                                 id : "tree",
8884                                 active : true
8885                         });
8886             folderTab.on("activeChange", function(o){ 
8887                 if (o.newValue) {
8888                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_FOLDERS);
8889                 }
8890             });
8891             se.leftTabs.addTab(folderTab);
8892             
8893             var tabContent = SUGAR.util.getAndRemove("searchTab");
8894             var searchTab = new YAHOO.widget.Tab({ 
8895                                 label: app_strings.LBL_EMAIL_SEARCH_SHORT,
8896                                 scroll : true,
8897                                 content : tabContent.innerHTML,
8898                                 id : tabContent.id
8899                         });
8900             searchTab.on("activeChange", function(o){ 
8901                 if (o.newValue) 
8902                 {
8903                         se.complexLayout.getUnitByPosition("left").set("header", app_strings.LBL_EMAIL_SEARCH);
8904                    //Setup the calendars if needed
8905                        Calendar.setup ({inputField : "searchDateFrom", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_from", singleClick : true, step : 1, weekNumbers:false});
8906                        Calendar.setup ({inputField : "searchDateTo", ifFormat : calFormat, showsTime : false, button : "jscal_trigger_to", singleClick : true, step : 1, weekNumbers:false});
8907                    
8908                        //Initalize sqs object for assigned user name 
8909                        se.e2Layout.initSQSObject('advancedSearchForm','assigned_user_name');  
8910                        
8911                        //Attach event handler for when the relate module option is selected for the correct sqs object
8912                        var parentSearchArgs = {'formName':'advancedSearchForm','fieldName':'data_parent_name_search',
8913                                                 'moduleSelectField':'data_parent_type_search','fieldId':'data_parent_id_search'};
8914                        YAHOO.util.Event.addListener('data_parent_type_search', 'change',function(){ 
8915                            SUGAR.email2.composeLayout.enableQuickSearchRelate(null,parentSearchArgs) });
8916                        
8917                        //If enter key is pressed, perform search
8918                        var  addKeyPressFields = ['searchSubject','searchFrom','searchTo','data_parent_name_search','searchDateTo','searchDateFrom','attachmentsSearch','assigned_user_name'];
8919                        for(var i=0; i < addKeyPressFields.length;i++)
8920                        {
8921                        YAHOO.util.Event.addListener(window.document.forms['advancedSearchForm'].elements[addKeyPressFields[i]],"keydown", function(e){
8922                                 if (e.keyCode == 13) {
8923                                         YAHOO.util.Event.stopEvent(e);
8924                                         SUGAR.email2.search.searchAdvanced();
8925                                 }
8926                        });
8927                        }
8928                                    //Initiate quick search for the search tab.  Do this only when the tab is selected rather than onDomLoad for perf. gains.
8929                        enableQS(true);
8930                        //Clear parent values if selecting another parent type.
8931                        YAHOO.util.Event.addListener('data_parent_type_search','change', 
8932                            function(){ 
8933                                document.getElementById('data_parent_id_search').value =''; 
8934                                document.getElementById('data_parent_name_search').value =''; 
8935                            });
8936                 
8937                 }
8938             });
8939             se.leftTabs.addTab(searchTab);
8940             
8941             var resizeTabBody = function() {
8942                 var height = SUGAR.email2.leftTabs.get("element").clientHeight - 30;
8943                                 SUGAR.email2.leftTabs.get("activeTab").get("contentEl").parentNode.style.height = height + "px";
8944             }
8945             resizeTabBody();
8946             se.complexLayout.on("render", resizeTabBody);
8947             se.leftTabs.on("activeTabChange", resizeTabBody);
8948                         //hack to allow left pane scroll bar to fully show
8949                 var lefttabsDiv = document.getElementById('lefttabs');
8950                         var lefttabsDivParent = Dom.getAncestorBy(lefttabsDiv);
8951                         var lefttabsDivGParent = Dom.getAncestorBy(lefttabsDivParent);
8952                         lefttabsDivParent.style.width = lefttabsDivGParent.offsetWidth - 10 + "px";
8953           
8954         },
8955         initSQSObject: function(formName,fieldName)
8956         {
8957             var fullFieldName = formName + '_' + fieldName; //SQS Convention
8958             var resultName = fullFieldName + '_' + 'results';
8959             
8960             if (QSFieldsArray[fullFieldName] != null) 
8961             {
8962                 QSFieldsArray[fullFieldName].destroy();
8963                 delete QSFieldsArray[fullFieldName];
8964             }
8965             if (QSProcessedFieldsArray[fullFieldName])
8966             QSProcessedFieldsArray[fullFieldName] = false;
8967
8968             if( Dom.get(resultName) )
8969             {
8970                 var obj = document.getElementById(resultName);
8971                 obj.parentNode.removeChild(obj);
8972             }
8973         },
8974         setPreviewPanel: function(rows) {
8975                 if (rows) {
8976                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 0);
8977                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 250);
8978                 Dom.get("listRight").innerHTML = "";
8979                 Dom.get("listBottom").innerHTML = "<div id='_blank' />";
8980             } else {
8981                 SUGAR.email2.listViewLayout.getUnitByPosition("bottom").set("height", 0);
8982                 SUGAR.email2.listViewLayout.getUnitByPosition("right").set("width", 250);
8983                 Dom.get("listBottom").innerHTML = "";
8984                 Dom.get("listRight").innerHTML = "<div id='_blank' />";
8985             }
8986         }
8987     };
8988         se.e2Layout.init();
8989 }
8990
8991 var myBufferedListenerObject = new Object();
8992 myBufferedListenerObject.refit = function() {
8993     if(SUGAR.email2.grid) {
8994         SUGAR.email2.grid.autoSize();
8995     }
8996 }
8997 // End of File modules/Emails/javascript/complexLayout.js
8998                                 
8999 /*********************************************************************************
9000  * SugarCRM is a customer relationship management program developed by
9001  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9002  * 
9003  * This program is free software; you can redistribute it and/or modify it under
9004  * the terms of the GNU Affero General Public License version 3 as published by the
9005  * Free Software Foundation with the addition of the following permission added
9006  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9007  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9008  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9009  * 
9010  * This program is distributed in the hope that it will be useful, but WITHOUT
9011  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9012  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9013  * details.
9014  * 
9015  * You should have received a copy of the GNU Affero General Public License along with
9016  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9017  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9018  * 02110-1301 USA.
9019  * 
9020  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9021  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9022  * 
9023  * The interactive user interfaces in modified source and object code versions
9024  * of this program must display Appropriate Legal Notices, as required under
9025  * Section 5 of the GNU Affero General Public License version 3.
9026  * 
9027  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9028  * these Appropriate Legal Notices must retain the display of the "Powered by
9029  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9030  * technical reasons, the Appropriate Legal Notices must display the words
9031  * "Powered by SugarCRM".
9032  ********************************************************************************/
9033
9034
9035 /******************************************************************************
9036  * Initialize Email 2.0 Application
9037  */
9038
9039 //Override Sugar Languge so quick creates work properly
9040
9041
9042 function email2init() {
9043
9044         //Init Tiny MCE
9045     // var tinyConfig = "code,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull," +
9046     //             "separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,fontselect,fontsizeselect";
9047     if (!SUGAR.util.isTouchScreen()) {
9048          tinyMCE.init({
9049                  convert_urls : false,
9050          theme_advanced_toolbar_align : tinyConfig.theme_advanced_toolbar_align,
9051          width: tinyConfig.width,
9052          theme: tinyConfig.theme,
9053          theme_advanced_toolbar_location : tinyConfig.theme_advanced_toolbar_location,
9054          theme_advanced_buttons1 : tinyConfig.theme_advanced_buttons1,
9055          theme_advanced_buttons2 : tinyConfig.theme_advanced_buttons2,
9056          theme_advanced_buttons3 : tinyConfig.theme_advanced_buttons3,
9057          plugins : tinyConfig.plugins,
9058          elements : tinyConfig.elements,
9059          language : tinyConfig.language,
9060          extended_valid_elements : tinyConfig.extended_valid_elements,
9061          mode: tinyConfig.mode,
9062          strict_loading_mode : true,
9063                  force_br_newlines : true,
9064          forced_root_block : ''
9065      });
9066     }
9067          //alert('loadedTiny');
9068
9069     // initialze message overlay
9070     SUGAR.email2.e2overlay = new YAHOO.widget.Dialog("SUGAR.email2.e2overlay", {
9071             //iframe        : true,
9072             modal       : false,
9073             autoTabs    : true,
9074             width       : 300,
9075             height      : 120,
9076             shadow      : true
9077         }
9078     );
9079         // Hide Sugar menu
9080         if (SUGAR.themes.tempHideLeftCol)
9081         SUGAR.themes.tempHideLeftCol();
9082
9083         // add key listener for kb shortcust - disable backspace nav in mozilla/ie
9084 //      YAHOO.util.Event.addListener(window.document, 'keypress', SUGAR.email2.keys.overall);
9085
9086         // set defaults for YAHOO.util.DragDropManager
9087         YAHOO.util.DDM.mode = 0; // point mode, default is point (0)
9088
9089         SUGAR.email2.nextYear = new Date();
9090         SUGAR.email2.nextYear.setDate(SUGAR.email2.nextYear.getDate() + 360);
9091
9092         
9093     // initialize and display UI framework (complexLayout.js)
9094     complexLayoutInit();
9095     
9096     // initialize and display grid (grid.js)
9097     gridInit();
9098     
9099     // initialize treeview for folders
9100         //onloadTreeinit();
9101         SUGAR.email2.folders.rebuildFolders(true);
9102         
9103         
9104     //Setup the Message Box overlay
9105     /*Ext.MessageBox.maxWidth = 350;
9106     Ext.MessageBox.minProgressWidth = 350;
9107
9108         ///////////////////////////////////////////////////////////////////////////
9109         ////    CONTEXT MENUS
9110         // detailView array
9111         SUGAR.email2.contextMenus.detailViewContextMenus = new Object();
9112 */
9113         var SEC = SUGAR.email2.contextMenus; 
9114         
9115         //Grid menu
9116         var emailMenu = SEC.emailListContextMenu = new YAHOO.widget.ContextMenu("emailContextMenu", {
9117                 trigger: SUGAR.email2.grid.get("element"),
9118                 lazyload: true
9119         });
9120         emailMenu.subscribe("beforeShow", function() {
9121                 var oTarget = this.contextEventTarget;
9122                 if (typeof(oTarget) == "undefined")
9123                   return;
9124                 var grid = SUGAR.email2.grid;
9125                 var selectedRows = grid.getSelectedRows();
9126                 var multipleSelected = (selectedRows.length > 1) ? true: false;
9127                 if (!multipleSelected)
9128                 {
9129                         grid.unselectAllRows();
9130                         grid.selectRow(oTarget);
9131                         SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));    
9132                 }
9133                 else if(multipleSelected)
9134                 {
9135                     SUGAR.email2.contextMenus.showEmailsListMenu(grid, grid.getRecord(oTarget));
9136                 }
9137         });
9138         
9139         //When we need to access menu items later we can only do so by indexes so we create a mapping to allow
9140         //us to access individual elements easier by name rather than by index
9141         emailMenu.itemsMapping = {'viewRelationships':0, 'openMultiple': 1, 'archive' : 2,  'reply' : 3,'replyAll' : 4,'forward' : 5,
9142                                    'delete' : 6,'print' : 7,'mark' : 8,'assignTo' : 9, 'relateTo' : 10};
9143         emailMenu.addItems([
9144         {
9145             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_VIEW_RELATIONSHIPS,
9146             id: 'showDetailView',
9147             onclick: { fn: SEC.showDetailView }
9148         },
9149         {
9150             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=open_multiple.gif'/>" + app_strings.LBL_EMAIL_OPEN_ALL,
9151             onclick: { fn: SEC.openMultiple }
9152         },
9153         {
9154             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_archive.gif'/>" + app_strings.LBL_EMAIL_ARCHIVE_TO_SUGAR,
9155             onclick: { fn: SEC.archiveToSugar }
9156         },
9157         {
9158             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_reply.gif'/>"+ app_strings.LBL_EMAIL_REPLY,
9159             id: 'reply',
9160             onclick: { fn: SEC.replyForwardEmailContext }
9161         },
9162         {
9163             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_replyall.gif'/>" + app_strings.LBL_EMAIL_REPLY_ALL,
9164             id: 'replyAll',
9165             onclick: { fn: SEC.replyForwardEmailContext }
9166         },
9167         {
9168             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_forward.gif'/>" + app_strings.LBL_EMAIL_FORWARD,
9169             id: 'forward',
9170             onclick: { fn: SEC.replyForwardEmailContext }
9171         },
9172         {
9173             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_delete.gif'/>" + app_strings.LBL_EMAIL_DELETE,
9174             id: 'delete',
9175             onclick: { fn: SEC.markDeleted }
9176         },
9177         {
9178             text: "<img src='themes/default/images/Print_Email.gif'/>" + app_strings.LBL_EMAIL_PRINT,
9179             id: 'print',
9180             onclick: { fn: SEC.viewPrintable }
9181         },                
9182         // Mark... submenu
9183         {
9184             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_mark.gif'/>" + app_strings.LBL_EMAIL_MARK,
9185             submenu: {
9186                         id: "markEmailMenu",
9187                 itemdata : [
9188                     {
9189                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNREAD,
9190                         onclick: { fn: SEC.markUnread }
9191                     },
9192                     {
9193                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_READ,
9194                         onclick: { fn: SEC.markRead }
9195                     },
9196                     {
9197                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_FLAGGED,
9198                         onclick: { fn: SEC.markFlagged }
9199                     },
9200                     {
9201                         text: app_strings.LBL_EMAIL_MARK + " " + app_strings.LBL_EMAIL_MARK_UNFLAGGED,
9202                         onclick: {  fn: SEC.markUnflagged }
9203                     }
9204                 ]
9205             }
9206          },
9207         {
9208             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_assign.gif'/>" + app_strings.LBL_EMAIL_ASSIGN_TO,
9209                 id: 'assignTo',
9210                 onclick: { fn: SEC.assignEmailsTo }
9211          },
9212          {
9213             text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_relate.gif'/>" + app_strings.LBL_EMAIL_RELATE_TO,
9214             id: 'relateTo',
9215             onclick: { fn: SEC.relateTo }
9216          }
9217     ]);
9218         SEC.emailListContextMenu.render();
9219         
9220         //Handle the Tree folder menu trigger ourselves
9221         YAHOO.util.Event.addListener(YAHOO.util.Dom.get("emailtree"), "contextmenu", SUGAR.email2.folders.handleRightClick)
9222
9223         
9224         //Folder Menu
9225     SEC.frameFoldersContextMenu = new YAHOO.widget.ContextMenu("folderContextMenu", {
9226                 trigger: "",
9227                 lazyload: true 
9228         });
9229     SEC.frameFoldersContextMenu.addItems([
9230                 {   text: "<img src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=icon_email_check.gif'/>" + app_strings.LBL_EMAIL_CHECK,
9231                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9232                         onclick: {  fn: function() {
9233                         var node = SUGAR.email2.clickedFolderNode;
9234                         if (node.data.ieId) {
9235                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, false)};
9236                     }}
9237                 },
9238                 {   text: app_strings.LBL_EMAIL_MENU_SYNCHRONIZE,
9239                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9240                         onclick: {  fn: function() {
9241                         var node = SUGAR.email2.clickedFolderNode;
9242                         if (node.data.ieId) {
9243                             SUGAR.email2.folders.startEmailCheckOneAccount(node.data.ieId, true)};
9244                     }}
9245                 },
9246                 {
9247                     text: app_strings.LBL_EMAIL_MENU_ADD_FOLDER,
9248                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_ADD_FOLDER + "</i>",
9249                     onclick: {  fn: SUGAR.email2.folders.folderAdd }
9250                 },
9251                 {
9252                     text: app_strings.LBL_EMAIL_MENU_DELETE_FOLDER,
9253                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_DELETE_FOLDER + "</i>",
9254                     onclick: {  fn: SUGAR.email2.folders.folderDelete }
9255                 },
9256                 {
9257                     text: app_strings.LBL_EMAIL_MENU_RENAME_FOLDER,
9258                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_RENAME_FOLDER + "</i>",
9259                     onclick: {  fn: SUGAR.email2.folders.folderRename }
9260                  },
9261                  {
9262                     text: app_strings.LBL_EMAIL_MENU_EMPTY_TRASH,
9263                     //helptext: "<i>" + app_strings.LBL_EMAIL_MENU_HELP_EMPTY_TRASH + "</i>",
9264                     onclick: {  fn: SUGAR.email2.folders.emptyTrash }
9265                   },
9266                  {
9267                     text: app_strings.LBL_EMAIL_MENU_CLEAR_CACHE,
9268                     onclick: {  fn: function() {
9269                         var node = SUGAR.email2.clickedFolderNode;
9270                         if (node.data.ieId) {
9271                             SUGAR.email2.folders.clearCacheFiles(node.data.ieId)};
9272                     }}
9273                   } 
9274         ]);
9275     SEC.frameFoldersContextMenu.render();
9276     
9277     SEC.initContactsMenu = function() {
9278         // contacts
9279         SEC.contactsContextMenu = new YAHOO.widget.ContextMenu("contactsMenu", {
9280                 trigger: "contacts",
9281                 lazyload: true
9282         });
9283         SEC.contactsContextMenu.addItems([
9284                 {
9285                         text: app_strings.LBL_EMAIL_MENU_REMOVE,
9286                         onclick:{ fn: SUGAR.email2.addressBook.removeContact }
9287                 },
9288                 {
9289                         text: app_strings.LBL_EMAIL_MENU_COMPOSE,
9290                         onclick:{ fn: function() {SUGAR.email2.addressBook.composeTo('contacts')}}
9291                 }
9292         ]);
9293         SEC.contactsContextMenu.subscribe("beforeShow", function() {
9294                 var oTarget = this.contextEventTarget, grid = SUGAR.email2.contactView;
9295                 if (oTarget && !grid.isSelected(oTarget)) {
9296                         grid.unselectAllRows();
9297                         grid.selectRow(oTarget);
9298                 }
9299         });
9300         SEC.contactsContextMenu.render();
9301         }
9302         
9303         
9304         // set auto-check timer
9305         SUGAR.email2.folders.startCheckTimer();
9306         // check if we're coming from an email-link click
9307         setTimeout("SUGAR.email2.composeLayout.composePackage()", 2000);
9308         
9309         YAHOO.util.Event.on(window, 'resize', SUGAR.email2.autoSetLayout);
9310         
9311         //Init fix for YUI 2.7.0 datatable sort.
9312         SUGAR.email2.addressBook.initFixForDatatableSort();
9313 }
9314
9315 function createTreePanel(treeData, params) {
9316         var tree = new YAHOO.widget.TreeView(params.id);
9317         var root = tree.getRoot();
9318         
9319         //if (treeData.nodes && treeData[0].id == "Home")
9320         //      treeData = treeData[0];
9321
9322         addChildNodes(root, treeData);
9323         
9324         return tree;
9325 }
9326
9327 function addChildNodes(parentNode, parentData) {
9328         var Ck = YAHOO.util.Cookie;
9329         var nextyear = SUGAR.email2.nextYear;
9330         var nodes = parentData.nodes || parentData.children;
9331         for (i in nodes) {
9332                 if (typeof(nodes[i]) == 'object') {
9333                         if (nodes[i].data) {
9334                                 nodes[i].data.href = '#';
9335                                 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)
9336                                 node.action = nodes[i].data.action;
9337                         } else {
9338                                 if (nodes[i].id == SUGAR.language.get('app_strings','LBL_EMAIL_HOME_FOLDER')) {
9339                                         addChildNodes(parentNode, nodes[i]);
9340                                         return;
9341                                 }
9342                                 nodes[i].expanded = Ck.getSub("EmailTreeLayout", nodes[i].id + "") == "true";
9343                                 Ck.setSub("EmailTreeLayout", nodes[i].id + "", nodes[i].expanded ? true : false, {expires: SUGAR.email2.nextYear});
9344                                 if (nodes[i].cls) {
9345                                         nodes[i].className = nodes[i].cls;
9346                                 }
9347                                 nodes[i].href = "#";
9348                                 if (nodes[i].text) nodes[i].label = nodes[i].text;
9349                                 //Override YUI child node creation
9350                                 if (nodes[i].children) {
9351                                         nodes[i].nodes = nodes[i].children;
9352                                         nodes[i].children = [ ];
9353                                 }
9354                                 var node = new YAHOO.widget.TextNode(nodes[i], parentNode);
9355                         }
9356                         
9357                         if (typeof(nodes[i].nodes) == 'object') {
9358                                 addChildNodes(node, nodes[i]);
9359                         }
9360                 }
9361         }
9362 }
9363
9364 /**
9365  * Custom TreeView initialization sequence to setup DragDrop targets for every tree node
9366  */
9367 function email2treeinit(tree, treedata, treediv, params) {
9368         //ensure the tree data is not corrupt
9369         if (!treedata) {
9370            return;
9371         }
9372         if (SUGAR.email2.tree) {
9373                 SUGAR.email2.tree.destroy();
9374                 SUGAR.email2.tree = null;
9375         }
9376         
9377         var tree = SUGAR.email2.tree = createTreePanel({nodes : {}}, {
9378                 id: 'emailtree'
9379         });
9380         
9381         tree.subscribe("clickEvent", SUGAR.email2.folders.handleClick);
9382         tree.subscribe("collapseComplete", function(node){YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", false, {expires: SUGAR.email2.nextYear});});
9383         tree.subscribe("expandComplete", function(node){
9384                 YAHOO.util.Cookie.setSub("EmailTreeLayout", node.data.id + "", true, {expires: SUGAR.email2.nextYear});
9385                 for (var i in node.children) {
9386                         SE.accounts.setupDDTarget(node.children[i]);
9387                 }
9388         });
9389         tree.setCollapseAnim("TVSlideOut");
9390         tree.setExpandAnim("TVSlideIn");
9391         var root = tree.root;
9392         while (root.hasChildren()) {
9393                 var node = root.children[0];
9394                 node.destroy();
9395                 tree.removeNode(root.children[0], false);
9396         }
9397         addChildNodes(root, treedata);
9398         tree.render();
9399         SUGAR.email2.accounts.renderTree();
9400 }
9401
9402 SUGAR.email2.folders.folderDD = function(id, sGroup, config) {
9403         SUGAR.email2.folders.folderDD.superclass.constructor.call(this, id, sGroup, config);
9404 };
9405
9406
9407 YAHOO.extend(SUGAR.email2.folders.folderDD, YAHOO.util.DDProxy, {    
9408     startDrag: function(x, y) {
9409                 var Dom = YAHOO.util.Dom;       
9410                 this.dragNode = SUGAR.email2.tree.getNodeByElement(this.getEl());
9411                 
9412                 this.dragId = "";
9413                 var dragEl = this.getDragEl();  
9414         var clickEl = this.getEl(); 
9415         Dom.setStyle(clickEl, "color", "#AAA");
9416         Dom.setStyle(clickEl, "opacity", "0.25"); 
9417         dragEl.innerHTML = clickEl.innerHTML; 
9418          
9419         Dom.addClass(dragEl, "ygtvcell");
9420         Dom.addClass(dragEl, "ygtvcontent");
9421         Dom.addClass(dragEl, "folderDragProxy");
9422         Dom.setStyle(dragEl, "height", (clickEl.clientHeight - 5) + "px");
9423         Dom.setStyle(dragEl, "width", (clickEl.clientWidth - 5) + "px");
9424         Dom.setStyle(dragEl, "backgroundColor", "#FFF"); 
9425         Dom.setStyle(dragEl, "opacity", "0.5"); 
9426             Dom.setStyle(dragEl, "border", "1px solid #AAA");
9427     },
9428     
9429     onDragOver: function(ev, id) {
9430         var Dom = YAHOO.util.Dom;
9431         if (id != this.dragId)
9432         {
9433                 var node = SUGAR.email2.tree.getNodeByElement(YAHOO.util.Dom.get(id));
9434                 if(node.data.cls != "sugarFolder") {
9435                         SUGAR.email2.folders.unhighliteAll();
9436                         return;
9437                 }
9438                 this.dragId = id;
9439                 this.targetNode = node;
9440                 SUGAR.email2.folders.unhighliteAll();
9441                 node.highlight();
9442         }
9443     },
9444     
9445     onDragOut: function(e, id) {
9446         if (this.targetNode) {
9447                 SUGAR.email2.folders.unhighliteAll();
9448                 this.targetNode = false;
9449                 this.dragId = false;
9450         }
9451     },
9452     
9453     endDrag: function() { 
9454         YAHOO.util.Dom.setStyle(this.getEl(), "opacity", "1.0");
9455         if (this.targetNode) {
9456                 SUGAR.email2.folders.moveFolder(this.dragNode.data.id, this.targetNode.data.id);
9457         }
9458     }
9459 });// End of File modules/Emails/javascript/init.js
9460                                 
9461 /*********************************************************************************
9462  * SugarCRM is a customer relationship management program developed by
9463  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9464  * 
9465  * This program is free software; you can redistribute it and/or modify it under
9466  * the terms of the GNU Affero General Public License version 3 as published by the
9467  * Free Software Foundation with the addition of the following permission added
9468  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9469  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9470  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9471  * 
9472  * This program is distributed in the hope that it will be useful, but WITHOUT
9473  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9474  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9475  * details.
9476  * 
9477  * You should have received a copy of the GNU Affero General Public License along with
9478  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9479  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9480  * 02110-1301 USA.
9481  * 
9482  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9483  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9484  * 
9485  * The interactive user interfaces in modified source and object code versions
9486  * of this program must display Appropriate Legal Notices, as required under
9487  * Section 5 of the GNU Affero General Public License version 3.
9488  * 
9489  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9490  * these Appropriate Legal Notices must retain the display of the "Powered by
9491  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9492  * technical reasons, the Appropriate Legal Notices must display the words
9493  * "Powered by SugarCRM".
9494  ********************************************************************************/
9495
9496 SUGAR.email2.templates['compose'] = '<div id="composeLayout{idx}" class="ylayout-inactive-content"></div>' +
9497 '<div id="composeOverFrame{idx}" style="height:100%;width:100%">' +
9498 '       <form id="emailCompose{idx}" name="ComposeEditView{idx}" action="index.php" method="POST">' +
9499 '               <input type="hidden" id="email_id{idx}" name="email_id" value="">' +
9500 '               <input type="hidden" id="uid{idx}" name="uid" value="">' +
9501 '               <input type="hidden" id="ieId{idx}" name="ieId" value="">' +
9502 '               <input type="hidden" id="mbox{idx}" name="mbox" value="">' +
9503 '               <input type="hidden" id="type{idx}" name="type" value="">' +
9504 '               <input type="hidden" id="composeLayoutId" name="composeLayoutId" value="shouldNotSeeMe">' +
9505 '               <input type="hidden" id="composeType" name="composeType">' +
9506 '               <input type="hidden" id="fromAccount" name="fromAccount">' +
9507 '               <input type="hidden" id="sendSubject" name="sendSubject">' +
9508 '               <input type="hidden" id="sendDescription" name="sendDescription">' +
9509 '               <input type="hidden" id="sendTo" name="sendTo">' +
9510 '               <input type="hidden" id="sendBcc" name="sendBcc">' +
9511 '               <input type="hidden" id="sendCc" name="sendCc">' +
9512 '               <input type="hidden" id="setEditor" name="setEditor">' +
9513 '               <input type="hidden" id="saveToSugar" name="saveToSugar">' +
9514 '               <input type="hidden" id="parent_id" name="parent_id">' +
9515 '               <input type="hidden" id="parent_type" name="parent_type">' +
9516 '               <input type="hidden" id="attachments" name="attachments">' +
9517 '               <input type="hidden" id="documents" name="documents">' +
9518 '               <input type="hidden" id="outbound_email{idx}" name="outbound_email">' +
9519 '               <input type="hidden" id="templateAttachments" name="templateAttachments">' +
9520 '               <input type="hidden" id="templateAttachmentsRemove{idx}" name="templateAttachmentsRemove">' +
9521 '               <table id="composeHeaderTable{idx}" cellpadding="0" cellspacing="0" border="0" width="100%" class="list">' +
9522 '                       <tr>' +
9523 '                               <th><table cellpadding="0" cellspacing="0" border="0"><tbody><tr ><td style="padding: 0px !important;margin:0px; !important" >' +
9524 '                                       <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>' +
9525 '                                       <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>' +
9526 '                                       <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>' +
9527 '                                       <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>' +
9528 '</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>' + 
9529 '&nbsp;</td><td style="padding: 0px !important;margin:0px; !important"><input id="data_parent_id{idx}" name="data_parent_id{idx}" type="hidden" value="">' +
9530 '<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>' +
9531 '                       </td></tr></tbody></table></th>'     +
9532 '                       </tr>' +
9533 '                       <tr>' +
9534 '                               <td>' +
9535 '                                       <div style="margin:5px;">' +
9536 '                                       <table cellpadding="4" cellspacing="0" border="0" width="100%">' +
9537 '                                               <tr>' +
9538 '                                                       <td class="emailUILabel" NOWRAP >' +
9539 '                                                               {app_strings.LBL_EMAIL_FROM}:' +
9540 '                                                       </td>' +
9541 '                                                       <td class="emailUIField" NOWRAP>' +
9542 '                                                               <div>' +
9543 '                                                                       &nbsp;&nbsp;<select style="width: 500px;" class="ac_input" id="addressFrom{idx}" name="addressFrom{idx}"></select>' +
9544 '                                                               </div>' +
9545 '                                                       </td>' +
9546 '                                               </tr>' +
9547 '                                               <tr>' +
9548 '                                                       <td class="emailUILabel" NOWRAP>' +
9549 '                                                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressTO{idx}\')">' + 
9550 '                                   {app_strings.LBL_EMAIL_TO}:' +
9551 '                               </button>' + 
9552 '                                                       </td>' +
9553 '                                                       <td class="emailUIField" NOWRAP>' +
9554 '                                                               <div class="ac_autocomplete">' +
9555 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressTO{idx}" name="addressTO{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9556 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressTO{idx}" href="#" style="display: none;">+<span id="DetailaddressTO{idx}">&nbsp;</span></a> </span>' +
9557 '                                                                       <div class="ac_container" id="addressToAC{idx}"></div>' +
9558 '                                                               </div>' +
9559 '                                                       </td>' +
9560 '                                               </tr>' +
9561 '                                               <tr id="add_addr_options_tr{idx}">' +
9562 '                                                       <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>'+
9563 '                                               </tr>'+
9564 '                                               <tr class="yui-hidden" id="cc_tr{idx}">' +
9565 '                                                       <td class="emailUILabel" NOWRAP>' +
9566 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressCC{idx}\')">' + 
9567 '                                                               {app_strings.LBL_EMAIL_CC}:' +
9568 '                               </button>' + 
9569 '                                                       </td>' +
9570 '                                                       <td class="emailUIField" NOWRAP>' +
9571 '                                                               <div class="ac_autocomplete">' +
9572 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressCC{idx}" name="addressCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9573 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressCC{idx}" href="#"  style="display: none;">+<span id="DetailaddressCC{idx}">&nbsp;</span></a> </span>' + 
9574 '                                                                       <div class="ac_container" id="addressCcAC{idx}"></div>' +
9575 '                                                               </div>' +
9576 '                                                       </td>' +
9577 '                                               </tr>' +
9578 '                                               <tr class="yui-hidden" id="bcc_tr{idx}">' +
9579 '                                                       <td class="emailUILabel" NOWRAP>' +
9580 '                               <button class="button" type="button" onclick="SUGAR.email2.addressBook.selectContactsDialogue(\'addressBCC{idx}\')">' + 
9581 '                               {app_strings.LBL_EMAIL_BCC}:' +
9582 '                               </button>' + 
9583 '                                                       </td>' +
9584 '                                                       <td class="emailUIField" NOWRAP>' +
9585 '                                                               <div class="ac_autocomplete">' +
9586 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="addressBCC{idx}" name="addressBCC{idx}" onkeyup="SE.composeLayout.showAddressDetails(this);">' +
9587 '                                                                       <span class="rolloverEmail"> <a id="MoreaddressBCC{idx}" href="#" style="display: none;">+<span id="DetailaddressBCC{idx}">&nbsp;</span></a> </span>' +
9588 '                                                                       <div class="ac_container" id="addressBccAC{idx}"></div>' +
9589 '                                                               </div>' +
9590 '                                                       </td>' +
9591 '                                               </tr>' +
9592 '                                               <tr>' +
9593 '                                                       <td class="emailUILabel" NOWRAP width="1%">' +
9594 '                                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9595 '                                                       </td>' +
9596 '                                                       <td class="emailUIField" NOWRAP width="99%">' +
9597 '                                                               <div class="ac_autocomplete">' +
9598 '                                                                       &nbsp;&nbsp;<input class="ac_input" type="text" size="96" id="emailSubject{idx}" name="subject{idx}" value="">' +
9599 '                                                               </div>' +
9600 '                                                       </td>' +
9601 '                                               </tr>' +
9602 '                                       </table>' +
9603 '                                       </div>' +
9604 '                               </td>'   +
9605 '                       </tr>' +
9606 '               </table>' +
9607 '               <textarea id="htmleditor{idx}" name="htmleditor{idx}" style="width:100%; height: 100px;"></textarea>' +
9608 '               <div id="divAttachments{idx}" class="ylayout-inactive-content">' +
9609 '                       <div style="padding:5px;">' +
9610 '                               <table cellpadding="2" cellspacing="0" border="0">' +
9611 '                                       <tr>' +
9612 '                                               <th>' +
9613 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS}</b>' +
9614 '                                                       <br />' +
9615 '                                                       &nbsp;' +
9616 '                                               </th>' +
9617 '                                       </tr>' +
9618 '                                       <tr>' +
9619 '                                               <td>' +
9620 '                                                       <input type="button" name="add_file_button" onclick="SUGAR.email2.composeLayout.addFileField();" value="{mod_strings.LBL_ADD_FILE}" class="button" />' +
9621 '                                                       <div id="addedFiles{idx}" name="addedFiles{idx}"></div>' +
9622 '                                               </td>' +
9623 '                                       </tr>' +
9624 '                                       <tr>' +
9625 '                                               <td>' +
9626 '                                                       &nbsp;' +
9627 '                                                       <br />' +
9628 '                                                       &nbsp;' +
9629 '                                               </td>' +
9630 '                                       </tr>' +
9631 '                                       <tr>' +
9632 '                                               <th>' +
9633 '                                                       <b>{app_strings.LBL_EMAIL_ATTACHMENTS2}</b>' +
9634 '                                                       <br />' +
9635 '                                                       &nbsp;' +
9636 '                                               </th>' +
9637 '                                       </tr>' +
9638 '                                       <tr>' +
9639 '                                               <td>' +
9640 '                                                       <input type="button" name="add_document_button" onclick="SUGAR.email2.composeLayout.addDocumentField({idx});" value="{mod_strings.LBL_ADD_DOCUMENT}" class="button" />' +
9641 '                                                       <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>' +
9642 '                                               </td>' +
9643 '                                       </tr>' +
9644 '                                       <tr>' +
9645 '                                               <td>' +
9646 '                                                       &nbsp;' +
9647 '                                                       <br />' +
9648 '                                                       &nbsp;' +
9649 '                                               </td>' +
9650 '                                       </tr>' +
9651 '                                       <tr>' +
9652 '                                               <th>' +
9653 '                                                       <div id="templateAttachmentsTitle{idx}" style="display:none"><b>{app_strings.LBL_EMAIL_ATTACHMENTS3}</b></div>' +
9654 '                                                       <br />' +
9655 '                                                       &nbsp;' +
9656 '                                               </th>' +
9657 '                                       </tr>' +
9658 '                                       <tr>' +
9659 '                                               <td>' +
9660 '                                                       <div id="addedTemplateAttachments{idx}"></div>' +
9661 '                                               </td>' +
9662 '                                       </tr>' +
9663 '                               </table>' +
9664 '                       </div>' +
9665 '               </div>' +
9666 '       </form>' +
9667 '               <div id="divOptions{idx}" class="ylayout-inactive-content"' +
9668 '             <div style="padding:5px;">' +
9669 '                       <form name="composeOptionsForm{idx}" id="composeOptionsForm{idx}">' + 
9670 '                               <table border="0" width="100%">' +
9671 '                                       <tr>' +
9672 '                                               <td NOWRAP style="padding:2px;">' +
9673 '                                                       <b>{app_strings.LBL_EMAIL_TEMPLATES}:</b>' +
9674 '                                               </td>' +
9675 '                                       </tr>' +
9676 '                                       <tr>' +
9677 '                                               <td NOWRAP style="padding:2px;">' +
9678 '                                                       <select name="email_template{idx}" id="email_template{idx}"  onchange="SUGAR.email2.composeLayout.applyEmailTemplate(\'{idx}\', this.options[this.selectedIndex].value);"></select>' +
9679 '                                               </td>' +
9680 '                                       </tr>' +
9681 '                               </table>' +
9682 '                               <br />' +
9683 '                               <table border="0" width="100%">' +
9684 '                                       <tr>' +
9685 '                                               <td NOWRAP style="padding:2px;">' +
9686 '                                                       <b>{app_strings.LBL_EMAIL_SIGNATURES}:</b>' +
9687 '                                               </td>' +
9688 '                                       </tr>' +
9689 '                                       <tr>' +
9690 '                                               <td NOWRAP style="padding:2px;">' +
9691 '                                                       <select name="signatures{idx}" id="signatures{idx}" onchange="SUGAR.email2.composeLayout.setSignature(\'{idx}\');"></select>' +
9692 '                                               </td>' +
9693 '                                       </tr>' +
9694 '                               </table>' +
9695 '                               <table border="0" width="100%">' +
9696 '                                       <tr>' +
9697 '                                               <td NOWRAP style="padding:2px;">' +
9698 '                                                       <input type="checkbox" id="setEditor{idx}" name="setEditor{idx}" value="1" onclick="SUGAR.email2.composeLayout.renderTinyMCEToolBar(\'{idx}\', this.checked);"/>&nbsp;' +
9699 '                                                       <b>{mod_strings.LBL_SEND_IN_PLAIN_TEXT}</b>' +
9700 '                                               </td>' +
9701 '                                       </tr>' +
9702 '                               </table>' +
9703 '         </form>' +
9704 '                       </div> ' +
9705 '               </div>' +
9706 '</div>';
9707 // End of File modules/Emails/javascript/composeEmailTemplate.js
9708                                 
9709 /*********************************************************************************
9710  * SugarCRM is a customer relationship management program developed by
9711  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9712  * 
9713  * This program is free software; you can redistribute it and/or modify it under
9714  * the terms of the GNU Affero General Public License version 3 as published by the
9715  * Free Software Foundation with the addition of the following permission added
9716  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9717  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9718  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9719  * 
9720  * This program is distributed in the hope that it will be useful, but WITHOUT
9721  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9722  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9723  * details.
9724  * 
9725  * You should have received a copy of the GNU Affero General Public License along with
9726  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9727  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9728  * 02110-1301 USA.
9729  * 
9730  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9731  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9732  * 
9733  * The interactive user interfaces in modified source and object code versions
9734  * of this program must display Appropriate Legal Notices, as required under
9735  * Section 5 of the GNU Affero General Public License version 3.
9736  * 
9737  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9738  * these Appropriate Legal Notices must retain the display of the "Powered by
9739  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9740  * technical reasons, the Appropriate Legal Notices must display the words
9741  * "Powered by SugarCRM".
9742  ********************************************************************************/
9743
9744 SUGAR.email2.templates['displayOneEmail'] = 
9745 '<div class="emailDetailTable" style="height:100%">' +
9746 '<div id="viewMenuDiv{idx}"></div>' + 
9747 '<div width="100%" class="displayEmailValue">' +
9748 '                                       <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>' +
9749 '                                       <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>' +
9750 '                                       <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>' +
9751 '                                       <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>' +
9752 '                                       <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>' +
9753 '                                       <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>' +
9754 '                                       <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>' +
9755 '                                       <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>' +
9756 '                                       <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>' +
9757 '</div>' +
9758 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%" >' +
9759 '                               <tr>' +
9760 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9761 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9762 '                                       </td>' +
9763 '                                       <td width="99%" class="displayEmailValue">' +
9764 '                                               {email.from_addr}' +
9765 '                                       </td>' +
9766 '                               </tr>' +
9767 '                               <tr>' +
9768 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9769 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9770 '                                       </td>' +
9771 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9772 '                                               <b>{email.name}</b>' +
9773 '                                       </td>' +
9774 '                               </tr>' +
9775 '                               <tr>' +
9776 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9777 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9778 '                                       </td>' +
9779 '                                       <td class="displayEmailValue">' +
9780 '                                               {email.date_start} {email.time_start}' +
9781 '                                       </td>' +
9782 '                               </tr>' +
9783 '                               <tr>' +
9784 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9785 '                                               {app_strings.LBL_EMAIL_TO}:' +
9786 '                                       </td>' +
9787 '                                       <td class="displayEmailValue">' +
9788 '                                               {email.toaddrs}' +
9789 '                                       </td>' +
9790 '                               </tr>' +
9791 '                               <tr>{meta.cc}</tr>' +
9792 '                               <tr>{email.attachments}</tr>' +
9793 '                       </table>' +
9794 '                       <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>' +
9795 //'                           {email.description}' +
9796 '</div>'
9797 ;// End of File modules/Emails/javascript/displayOneEmailTemplate.js
9798                                 
9799 /*********************************************************************************
9800  * SugarCRM is a customer relationship management program developed by
9801  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9802  * 
9803  * This program is free software; you can redistribute it and/or modify it under
9804  * the terms of the GNU Affero General Public License version 3 as published by the
9805  * Free Software Foundation with the addition of the following permission added
9806  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9807  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9808  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9809  * 
9810  * This program is distributed in the hope that it will be useful, but WITHOUT
9811  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9812  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9813  * details.
9814  * 
9815  * You should have received a copy of the GNU Affero General Public License along with
9816  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9817  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9818  * 02110-1301 USA.
9819  * 
9820  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9821  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9822  * 
9823  * The interactive user interfaces in modified source and object code versions
9824  * of this program must display Appropriate Legal Notices, as required under
9825  * Section 5 of the GNU Affero General Public License version 3.
9826  * 
9827  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9828  * these Appropriate Legal Notices must retain the display of the "Powered by
9829  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9830  * technical reasons, the Appropriate Legal Notices must display the words
9831  * "Powered by SugarCRM".
9832  ********************************************************************************/
9833
9834 SUGAR.email2.templates['viewPrintable'] = '<html>' +
9835 '<body onload="javascript:window.print();">' + 
9836 '<style>' + 
9837 'body {' + 
9838 '       margin: 0px;' + 
9839 '       font-family: helvetica, impact, sans-serif;' +
9840 '       font-size : 12pt;' +
9841 '} ' +
9842 'table {' +
9843 '       padding:10px;' +
9844 '}' +
9845 '</style>' +
9846 '<div>' +
9847 '<table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9848 '       <tr>' +
9849 '               <td>' +
9850 '                       <table cellpadding="0" cellspacing="0" border="0" width="100%">' +
9851 '                               <tr>' +
9852 '                                       <td NOWRAP valign="top" width="1%" class="displayEmailLabel">' +
9853 '                                               {app_strings.LBL_EMAIL_FROM}:' +
9854 '                                       </td>' +
9855 '                                       <td width="99%" class="displayEmailValue">' +
9856 '                                               {email.from_name} &lt;{email.from_addr}&gt;' +
9857 '                                       </td>' +
9858 '                               </tr>' +
9859 '                               <tr>' +
9860 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9861 '                                               {app_strings.LBL_EMAIL_SUBJECT}:' +
9862 '                                       </td>' +
9863 '                                       <td NOWRAP valign="top" class="displayEmailValue">' +
9864 '                                               <b>{email.name}</b>' +
9865 '                                       </td>' +
9866 '                               </tr>' +
9867 '                               <tr>' +
9868 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9869 '                                               {app_strings.LBL_EMAIL_DATE_SENT_BY_SENDER}:' +
9870 '                                       </td>' +
9871 '                                       <td class="displayEmailValue">' +
9872 '                                               {email.date_start} {email.time_start}' +
9873 '                                       </td>' +
9874 '                               </tr>' +
9875 '                               <tr>' +
9876 '                                       <td NOWRAP valign="top" class="displayEmailLabel">' +
9877 '                                               {app_strings.LBL_EMAIL_TO}:' +
9878 '                                       </td>' +
9879 '                                       <td class="displayEmailValue">' +
9880 '                                               {email.toaddrs}' +
9881 '                                       </td>' +
9882 '                               </tr>' +
9883 '                               {email.cc}' +
9884 '                               {email.attachments}' +
9885 '                       </table>' +
9886 '               </td>' +
9887 '       </tr>' +
9888 '       <tr>' +
9889 '               <td>' +
9890 '                       <table cellpadding="0" cellspacing="0" border="0" style="width:100%;">' +
9891 '                               <tr>' +
9892 '                                       <td style="border-top: 1px solid #333;">' +
9893 '                                               <div style="padding:5px;">' +
9894                                                         '{email.description}' +
9895 '                                               </div>' +
9896 '                                       </td>' +
9897 '                               </tr>' +
9898 '                       </table>' +
9899 '               </td>' +
9900 '       </tr>' +
9901 '</table>' +
9902 '</div>' +
9903 '</body></html>';
9904 // End of File modules/Emails/javascript/viewPrintable.js
9905                                 
9906 /*********************************************************************************
9907  * SugarCRM is a customer relationship management program developed by
9908  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9909  *
9910  * This program is free software; you can redistribute it and/or modify it under
9911  * the terms of the GNU Affero General Public License version 3 as published by the
9912  * Free Software Foundation with the addition of the following permission added
9913  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9914  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
9915  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
9916  *
9917  * This program is distributed in the hope that it will be useful, but WITHOUT
9918  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
9919  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
9920  * details.
9921  *
9922  * You should have received a copy of the GNU Affero General Public License along with
9923  * this program; if not, see http://www.gnu.org/licenses or write to the Free
9924  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
9925  * 02110-1301 USA.
9926  *
9927  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
9928  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
9929  *
9930  * The interactive user interfaces in modified source and object code versions
9931  * of this program must display Appropriate Legal Notices, as required under
9932  * Section 5 of the GNU Affero General Public License version 3.
9933  *
9934  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
9935  * these Appropriate Legal Notices must retain the display of the "Powered by
9936  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
9937  * technical reasons, the Appropriate Legal Notices must display the words
9938  * "Powered by SugarCRM".
9939  ********************************************************************************/
9940 function enableQS(noReload){YAHOO.util.Event.onDOMReady(function(){if(typeof sqs_objects=='undefined'){return;}
9941 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;}
9942 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');}
9943 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;}}
9944 if(QSProcessedFieldsArray[qs_index_id]){continue;}
9945 var qs_obj=sqs_objects[qs_index_id];var loaded=false;if(!document.forms[qs_obj.form]){continue;}
9946 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}
9947 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,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){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)){document.forms[this.qs_obj.form].elements[this.qs_obj.populate_list[key]].value=data[i];}}}},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="";}}
9948 this.oldValue="";}});if(typeof(SUGAR.config.quicksearch_querydelay)!='undefined'){search.queryDelay=SUGAR.config.quicksearch_querydelay;}
9949 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];}}}
9950 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]];}
9951 this.getInputEl().value=data[this.key];this.itemSelectEvent.fire(this,"",data);}});if(typeof QSFieldsArray[combo_id]=='undefined'&&qsFields[qsField].id){QSFieldsArray[combo_id]=search;}}}}});}
9952 function registerSingleSmartInputListener(input){if((c=input.className)&&(c.indexOf("sqsEnabled")!=-1)){enableQS(true);}}
9953 if(typeof QSFieldsArray=='undefined'){QSFieldsArray=new Array();QSProcessedFieldsArray=new Array();}// End of File include/javascript/quicksearch.js
9954